Showing posts with label online learning. Show all posts
Showing posts with label online learning. Show all posts

Networking in Swift: Building a RESTful API in PHP, Part 1

This is the second post in our tutorial series on networking in Swift. If you followed along in the introductory article, you have installed MAMP on your local machine, created an .htaccess file and set up the basic file structure for the project. In this tutorial, we'll begin building the API for our Super PHPlumbing Bros web service.

This RESTful API in PHP will serve content to the Swift-based iOS client application we'll create in the final part of the series. Our API will perform five distinct tasks when queried. It will provide: 1) inventory items response logic for our Plumbing Tools; 2) inventory items response logic for Plumbing Supplies; 3) inventory item response logic for Plumbing Tool with Description; 4) Inventory item response logic for Plumbing Supply with Description; 5) Error response logic.

In this article, we will cover the structure of our API queries, provide a simple bare bones interface for the service, and then build the first half of our custom API to serve up our plumbing supplies inventory.

API Queries
Our application will communicate with the web api through a simple url scheme. If you are not familiar with url schemes, take a brief detour through the linked Wikipedia page to learn about how they work (simply memorizing the components of a url scheme outright will save you lots of needless lookups later).

Our first stab at a url scheme looks crude. Here is the URL scheme that we will use to access our entire inventory of plumbing tools: http://localhost:8888/v1/PlumbingAPI.php?method=copper_pipes_and_fittings&format=json.

Let's take a closer look at this scheme. Any text in a URL that comes after the question mark (?) is known as the URL query component. Each key/value pair that follows is logically separated by an ampersand (&). In this example the query string contains two key/value pairs. These key/value pairs will get passed along to our PlumbingAPI.php script via an associative array known as $_GET[]. Within our PHP script we will access the values for the 'method' and 'format' keys as follows: $_GET['method'] and $_GET['format'] would return 'copper_pipes_and_fittings' and 'json', respectively, in the crude example above. We use these values to determine what was requested of our API.

A Bare Bones API
Let's get down to it. Using your text editor, open PlumbingAPI.php for both versioning folders, v1 and v2. Until further noted, we'll be entering the same code in both versions. For the skeletal structure of our API, we are going to adapt the code from Mark Roland's helpful tutorial on "How to Build a RESTful API Web Service in PHP." We'll explain each component as we add flesh to our bare-bones script. Here's a Gist of the script:


After reading through the code, copy it into the PlumbingAPI.php file in your v1 folder. Using the URL scheme from above, point your web browser at http://localhost:8888/v1/PlumbingAPI.php?method=copper_pipes_and_fittings&format=json, and you will see the API's response to the given method and format:

Simple API call to bare bones script


If you now navigate to http://localhost:8888/v1/PlumbingAPI.php?method=plumbing_tools&format=json, you'll see the response from the plumbing_tools method:

Second API call to bare bones script
  
If this is not working for you, then go back and make sure that you followed all the steps. If you do see a response in your web browser, then congratulations! You've successfully built and deployed your locally hosted web service. The various responses from our api are made possible by the following conditional code structure, from line 120 to the end of the file above:
// Copper Pipes and Fittings API //
if( strcasecmp($_GET['method'],'copper_pipes_and_fittings') == 0){
    echo 'Copper Pipes and Fittings API Call. <br>';
}

// Plumbing Tools API //
else if( strcasecmp($_GET['method'],'plumbing_tools') == 0){
    echo 'Plumbing Tools API Call. <br>';
}

// ** Deliver Response ** //
// Return Response to browser //
deliver_response($_GET['format'], $response);
With the exception of the function definitions, our script is executed from top to bottom. Notice the conditional if else if structure here. In our first API call we passed in the value 'copper_pipes_and_fittings' for the 'method' key. Recall that the parameters of a query string are passed in to the $_GET[] global array, which we read from in our first conditional if check. Since it evaluates to true in the first API call, we fall in that conditional block and therefore echo "Copper Pipes and Fittings API Call", followed by the function call: deliver_response($_GET['format'], $response). This last function call is what prints out the second line in the browser.

In our second api call, we passed in the value 'plumbing_tools' for the 'method' key in the URL. With this query, we fell into the conditional else-if check above. This gave us our alternate response. That's all there is to it!

Moving forward, we'll build on top of this primitive structure of conditional checks followed with a response using the echo call.  For explanations of built-in methods such as  strcasecmp() and echo, check out php.net and search for those calls to get documentation along with code samples on how to use them.

Building the Supplies Interface
We'll now begin building out the control flow for the various tasks our API will perform. In the first if conditional control flow replace the code at line 122 (echo 'Copper Pipes and Fittings API Call. <br>';) with the following:
// build payload //
$response['code'] = 1;
$response['api_version'] = '1.0.0';
$response['status'] = $api_response_code[ $response['code'] ]['HTTP Response'];
   
// if an 'item_id' was provided then return details for that item //
if ( $_GET['item_id'] ) {
    $response['item_id'] = strtoupper($_GET['item_id']);
    $response['data'] = copper_pipe_or_fitting_item_details(strtoupper($_GET['item_id']));
}
// else return our entire inventory of copper pipes and fittings //
else {
    $response['data'] = copper_pipes_and_fittings_inventory_without_description();
}
Save your PlumbingAPI.php file and point your browser to this URL: http://localhost:8888/v1/PlumbingAPI.php?method=copper_pipes_and_fittings&format=json. The response will appear as follows in your web browser:
Copper Pipes and Fittings Inventory without Descriptions.
Copper Pipes and Fittings Inventory.
Delivering Response. $api_response = Array, format = json
Your are seeing this response because our first if check did not fall through as we did not provide an 'item_id' key with an associated value pair as parameters in the query part of our URL. In other words, a parameter with this format, '&item_id=<some item id>', was not appended to the above URL. This resulted in our conditional control flow to fall through the else path. In this else block we call a method that we defined earlier: copper_pipes_and_fittings_inventory_without_description(). In our definition of this method, notice that we call another method: copper_pipes_and_fittings_inventory(). This last method is responsible for fetching our entire inventory of copper pipes and fittings along with all item details. Go to this method, found in lines 27 -33 above, and replace line 32 (echo 'Copper Pipes and Fittings Inventory. <br>';)<code> with the following:


This is an associative array of sub-arrays. Each sub-array contains all the information of one inventory item. There are twelve items in our hypothetical Copper Pipes and Fittings category, the information for which was cobbled together from online sources. In a real world scenario, this or a similar method would normally pull this data from a data store like a database. But for the sake of brevity we will skip this part. Now go to where we defined the method copper_pipes_and_fittings_inventory_without_description() (line 56 in the bare bones files above), and replace lines 57 and 58 with the following: 
return copper_pipes_and_fittings_inventory();
For now we'll simply return our entire inventory with descriptions. We will revisit this method later and write code to omit item descriptions. Now navigate to our response delivery function (function deliver_response($format, $api_response)), line 23 in the bare bones code, and replace its echo command in line 24 with the following:


The response to our API query gets processed here. If a parameter of 'format=json' is provided in the query part of the URL, then our script would fall through our first if check. This parameter informs our API that one of three available formatted responses was requested. We support three formats in this example: json, xml and html. 

Let's now write the code to process json format requests. In the first conditional if-check block (line 14) replace the comment (// JSON Response //) with the following code:
// Set HTTP Response Content Type //
header('Content-Type: application/json; charset=utf-8');

// Format data into a JSON response //
$json_response = json_encode($api_response, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);

// Deliver formatted data //
echo $json_response;
Save your PlumbingAPI.php file and point your browser to this url, http://localhost:8888/v1/PlumbingAPI.php?method=copper_pipes_and_fittings&format=json. The response will appear as follows in your web browser:
{
    "code": 1,
    "status": 200,
    "data": [
        {
            "id": "CP12010",
            "name": "1 inch copper pipe.",
            "image": "http://localhost:8888/assets/1_inch_copper_pipe.png",
            "description": "1 in. x 10 ft. Copper Type M Hard Temper Straight Pipe for a multitude of plumbing and heating purposes. It is NSF and ANSI Standard 61 certified. Made of hard-temper ASTM - B88 copper. For general plumbing and heating purposes. Alloy C12200 (DHP) meets industry standards and is NSF and ANSI Standard 61 certified. Meets or exceeds industry standards to deliver a high quality flow product. Plumbing and mechanical codes govern what types of products may be used for applications. Local codes should always be consulted for minimum requirements"
        },
        {
            "id": "CP12020",
            "name": "1 1/4 inch copper pipe.",
            "image": "http://localhost:8888/assets/1_1_4_inch_copper_pipe.png",
            "description": "1 1/4 in. x 10 ft. Copper Type M Hard Temper Straight Pipe for a multitude of plumbing and heating purposes. It is NSF and ANSI Standard 61 certified. Made of hard-temper ASTM - B88 copper. For general plumbing and heating purposes. Alloy C12200 (DHP) meets industry standards and is NSF and ANSI Standard 61 certified. Meets or exceeds industry standards to deliver a high quality flow product. Plumbing and mechanical codes govern what types of products may be used for applications. Local codes should always be consulted for minimum requirements"
        },
    .
    .
    .
    .
        {
            "id": "CP14040",
            "name": "1 1/2 inch copper elbow fitting.",
            "image": "http://localhost:8888/assets/1_1_2_inch_copper_elbow_fitting.png",
            "description": "1 1/3 in. Copper Type M Hard Temper Straight Pipe for a multitude of plumbing and heating purposes. It is NSF and ANSI Standard 61 certified. Made of hard-temper ASTM - B88 copper. For general plumbing and heating purposes. Alloy C12200 (DHP) meets industry standards and is NSF and ANSI Standard 61 certified. Meets or exceeds industry standards to deliver a high quality flow product. Plumbing and mechanical codes govern what types of products may be used for applications. Local codes should always be consulted for minimum requirements"
        }
    ],
    "api_version": "1.0.0"
}
The vertical ellipses indicate that we trimmed the actual response. You should see a lot more data in your browser. The problem with this response is that the copper pipes and fittings inventory response contains too much data. In our next step we'll trim the response so that item descriptions are omitted. 

It is not good practice to submit details of items when requesting them in bulk. In a real-world scenario, internet access is often spotty and unreliable. And serving up too much data could negatively impact your users' experience. And since users are often not aware that your application is not to blame for a given issue, but rather their connectivity to the network, they will associate this bad experience with your application. So, in an effort to mitigate connectivity issues, we should always prefer to send the least amount of data as possible over a network. Also, it is very unlikely that you can fit all this data for one item onto a screen when presenting the user with a list of items.

To omit item details, navigate to where we defined the method copper_pipes_and_fittings_inventory_without_description(), and replace our return command (return copper_pipes_and_fittings_inventory();) with this chunk of code:
    // pull our entire inventory of copper pipes and fittings //
    $inventory = copper_pipes_and_fittings_inventory();
   
    // container for inventory minus descriptions//
    $inventory_without_details = array();
   
    // iterate through inventory and duplicate all attributes except descriptions //
    foreach ($inventory as $key=>$value) {
        if (is_array($value)) {
            $inventory_item = array();
            foreach ($value as $subkey=>$subvalue) {
                if ( strcasecmp($subkey,'description') != 0 )
                    $inventory_item[$subkey] = $subvalue;
            }
            $inventory_without_details[$key] = $inventory_item;
        }
    }
    return $inventory_without_details;    
This code is straight forward. It iterates through the json objects and all the items into another container with the exception of key value pairs that are associated with a key name of 'description.' Save your PlumbingAPI.php file and point your browser to this url, http://localhost:8888/v1/PlumbingAPI.php?method=copper_pipes_and_fittings&format=json. The response will appear as follows in your web browser:
{
    "code": 1,
    "status": 200,
    "data": [
        {
            "id": "CP12010",
            "name": "1 inch copper pipe.",
            "image": "http://localhost:8888/assets/1_inch_copper_pipe.png"
        },
        {
            "id": "CP12020",
            "name": "1 1/4 inch copper pipe.",
            "image": "http://localhost:8888/assets/1_1_4_inch_copper_pipe.png"
        },
          .
    .
    .
    .
        {
            "id": "CP14040",
            "name": "1 1/2 inch copper elbow fitting.",
            "image": "http://localhost:8888/assets/1_1_2_inch_copper_elbow_fitting.png"
        }
    ],
    "api_version": "1.0.0"
}
Again, the vertical ellipses indicate that we trimmed the actual response. Notice that the descriptions have been omitted from the response. 

We will now write code to serve an individual copper pipe or fitting with a description. Find where the method function copper_pipe_or_fitting_item_details($item_id) is defined (line 66 in our bare bones API) and replace the two lines filling out the function (i.e. 67 and 68), with the following:
// pull our entire inventory of copper pipes and fittings //
$inventory = copper_pipes_and_fittings_inventory();
   
// container for item matching the provided item_id //
$inventory_item = array();
   
// iterate through our inventory and find the requested item //
foreach ($inventory as $key=>$value) {
    if (is_array($value) && strcasecmp($value['id'], $item_id) == 0) {
        foreach ($value as $subkey=>$subvalue) {
                $inventory_item[$subkey] = $subvalue;
        }
        break;
    }
}
return $inventory_item;
Save your php file and point your browser to this URL: http://localhost:8888/v1/PlumbingAPI.php?method=copper_pipes_and_fittings&item_id=CP12010&format=json. This is an endpoint to the first item from our json inventory response above. You should see the response below:
{
    "code": 1,
    "status": 200,
    "data": {
        "id": "CP12010",
        "name": "1 inch copper pipe.",
        "image": "http://localhost:8888/assets/1_inch_copper_pipe.png",
        "description": "1 in. x 10 ft. Copper Type M Hard Temper Straight Pipe for a multitude of plumbing and heating purposes. It is NSF and ANSI Standard 61 certified. Made of hard-temper ASTM - B88 copper. For general plumbing and heating purposes. Alloy C12200 (DHP) meets industry standards and is NSF and ANSI Standard 61 certified. Meets or exceeds industry standards to deliver a high quality flow product. Plumbing and mechanical codes govern what types of products may be used for applications. Local codes should always be consulted for minimum requirements"
    },
    "api_version": "1.0.0",
    "item_id": "CP12010"
}

Congratulations! We have completed the first half of our web API, serving up content for our copper pipes and fittings inventory. In the next article in the series, we'll complete the API to serve up our inventory of plumbing tools, and then begin building our Swift application to bring that content to our end user. Follow the line for part two on building a RESTful API in PHP.

This project can be found on GitHub.

As always, comments, questions, and suggestions are welcome below!

Index
Introduction
Introduction and Overview: From the Back End API to the End User Application

The Web API
Building a RESTful API in PHP, Part 1
Building a RESTful API in PHP, Part 2

The Swift Client App
Networking in Swift: Building the Swift Client, Part 1
Networking in Swift: Building the Swift Client, Part 2
Networking in Swift: Building the Swift Client, Part 3
Networking in Swift: Building the Swift Client, Part 4
Networking in Swift: Building the Swift Client, Part 5


This tutorial was authored by Stefan Agapie, a Senior iOS Software Engineer, and adapted for the present piece. 

Networking in Swift: From the Backend API to the End User App

Introduction
In this tutorial series, we will create an iOS application that will leverage Swift's networking layer to query a custom-built web service. First, we'll build a RESTful API in PHP from the bottom up and host it on our local machine. Then we'll craft an iOS Swift application to consume the content provided by the service, and present it to the end user in a collection view. The series is intended for people who have some degree of programming experience, but who have not yet obtained much practical knowhow on building an everyday, real-world, user-facing, mobile application. 

A typical use case for mobile applications requires the consumption of content that is hosted on a web server. For successful mobile app development, this means that you not only need to know how to build an application that consumes web content, but also to have a high level understanding (at the very least!) of how a web service actually delivers content to your mobile application.

This is important because you will encounter network related errors during your development cycle. And if you don't have at least a basic understanding of the web service that your are trying to communicate with, then you cannot be sure where the errors are originating from. In addition, you will likely also be asked, at work or by your own clients, to begin writing a mobile application that relies on a web service that has not been built yet! (This actually happens way too often!) In such cases, you can write your own temporary web service that delivers mock data to your application, if you know how to build one. Although there are other ways of delivering such mock data, this can be just as useful. 

In this article, we'll provide an overview of the project, and then work through the preliminary steps for running the web service on our local machine. In the following articles, we'll build out the PHP script that will execute the API, and finally construct our Swift application to query the service and return the relevant data to the end user.

The ABCs of APIs
What is an API and how will our Swift application interface with it? API stands for Application Programming Interface. A simple web search for 'API' will return many definitions with various types of descriptions and creative examples. I like to think of an API as a real object. 
Source

Since the internet is a series of pipes and tubes, our API will provide an interface to a plumbing supply inventory. Let's call our API the Mario Interface. Mario works at the front desk of a plumbing supply house called Super PHPlumbing Bros Inc. Mr. Swift is a plumber who needs some supplies to rescue a local potentate's daughter from the clutches of an invading warlord.

Mr. Swift finds PHPlumbing and walks up to the counter where he encounters Mario. Mr. Swift tells Mario that he would like some piping, mushrooms and a wrench. Mario says, "No problem, but first I need you to know exactly what you need," and hands Mr. Swift two forms.

Each form is titled with the company's name. Below the title, there are several check boxes, but only one may be checked per form. The relevant check boxes are: Piping/Fittings and Plumbing Tools. Below that is a description field for the requested items along with their quantity. 

Once completed, Mr. Swift hands the forms to Mario, who then passes them along to his employees, local Toads from the Mushroom Kingdom, who are tasked to assist him. The Toads find the relevant items, bring them out and place them on the counter. 

If at any point during this process there was a problem retrieving Mr. Swift's supplies, the Toads are responsible for reporting these errors up the chain of command, from the assistants up to Mario and terminating at Mr. Swift.

In our analogy, Mr. Swift is the client (our iOS application) in need of content or plumbing supplies. Super PHPlumbing Bros Inc. is the store or website that has the supplies or content that Mr. Swift is looking for. The form for getting supplies is the actual url (location of content) that is used to find and retrieve the content. And Mario, along with the Toads, comprise the API. 

APIs, and people like Mario, are needed to maintain a system of flow control structures that are necessary to efficiently run the business logic of the operation. Can you imagine a plumbing supply house that had no control structures like forms and employees to manage its everyday workflow? The princess would be doomed.

In this tutorial series, we'll construct a RESTful API in PHP to serve up an inventory of plumbing tools and supplies, and then build a custom Swift app to interface with the API and serve that inventory to the end user. For now, let's get our local server up and running. 

Setting Up the Local Server
Unfortunately, the PHP file that will serve our API will not execute on its own. A service is required to interpret and execute our PHP script. We therefore need to set up a place on our local machine to host our Super PHPlumbing Bros. supply house. One of the easiest ways to get a server up and running on a Mac is with MAMP. Once you've downloaded MAMP, you can run the package by double clicking it.

After the package mounts, follow the instructions to install the software. 

Once installed, navigate to your Applications folder and start MAMP. You will be prompted with several initialization screens. Once MAMP is installed, start the server my clicking the START button in the top right corner of the application window. 


The tiny box to the right of the word Apache should turn green if everything went smoothly. This means that your server is up and running! Now start a new session of Safari, and in the url field type the following address: http://localhost:8888 You should see a similar screen to the following, which indicates that all is in working order:

.htaccess
A .htaccess file provides directory level configuration on how a web server handles requests to resources that are in the same directory as the .htaccess file itself. Note that using .htaccess is discouraged for production environments, but for the purposes of our tutorial, it should work just fine. Using your favorite text editor, create a new file and name it .htaccess. In the screen capture above, notice the directory path next to the text, “Document root:”. Mine reads: "Document root: /Applications/MAMP/htdocs." This is where your PHP file, along with all related resources will live. Place your .htaccess file in this folder.

Remember, any file name that begins with a period “.” is a system file and is hidden by default. To view hidden files, you can use the "ls -a" command in a terminal. To view hidden files in Finder, you can follow the instructions here.

File Structure 
Navigate to the folder that contains your .htaccess file. For me, it's /Applications/MAMP/htdocs, and create three folders with the following names: v1, v2, assets. More on these folders later, but for now, your folder structure should more or less look like the following:

Using your text editor create a new file and call it PlumbingAPI.php. This file models the Mario Interface, our counter guy. Place a single copy in folder v1 and v2. The v1 and v2 folder will be used for version control. The earlier versions of an API would typically reside in folders with a smaller number while the most recent API edition would live in the folder with the largest number.

Moving Forward  
With that, we're all set to go! In the next segment of the tutorial we'll build our RESTful API in PHP, so let's take the plunge. Or, if you want to skip ahead, follow the link to the tutorial segment on building our Swift client application.


Hack Lab Intro: How to Set up a Home Hacking and Security Testing Lab

Introduction

This series of articles comprises an introductory tutorial on how to set up a home lab to experiment with common hacking and information security testing tools. Our setup will  allow us to explore the sorts of computer and network vulnerabilities that can be encountered on the internet, and to test the security of our own home computer network and networked devices, all from within an isolated and secure working environment. The series is geared toward individuals who have little or no prior experience with virtualization software or common hacking and security testing tools, but are interested in exploring network and computer security.

Over the course of the tutorial series, we will create two separate network configurations. The first will be a completely virtual environment populated by two virtual guest systems running inside a single host computer. This requires nothing more than an internet connection for the necessary downloads, and a computer with relatively modest RAM and disk resources.

The second configuration will be an everyday local area network of the sort that can be found in many homes, but which is isolated from the internet and where we can strictly control and monitor all network traffic. This setup is slightly more involved in terms of hardware than the first, requiring also a spare router.

Our monitoring and attack system in both configurations will be an instance of a Kali Linux virtual machine running inside an installation of the VirtualBox software package on our primary computer. Kali is a Linux operating system distribution intended for security testing and digital forensics.

In the first completely virtual network environment, our victim will be an instance of  Metasploitable2, a virtual machine that exhibits vulnerabilities that can be found on  everyday computer systems and software configurations. As noted at Offensive Security, "Metasploitable is an intentionally vulnerable Linux virtual machine. This VM can be used to conduct security training, test security tools, and practice common penetration testing techniques."

In the second network configuration, we will use the Kali Linux virtual machine to compromise an everyday local area network router of the sort that can be found on many home networks, in order to demonstrate just how easy it can be to steal login credentials  passed from another computer on the network.

The tutorial is broken down into four parts:
  • Part 1 covers the installation of VirtualBox and provides a walk through of a full installation of a Kali virtual machine on your primary lab computer. Along the way, we'll take a short detour on how to quickly run live Kali sessions without a full installation of the machine.
  • Part 4 provides details on setting up our second network configuration, which models an everyday home local area network. With the attack machine, we'll conduct a simple man-in-the-middle attack against the network's router, and demonstrate a serious security vulnerability by stealing login credentials sent to it from the victim machine, in this case, the host computer. 

Hack Lab Part 4: Compromising a Home Router on a Local Area Network

This is part four in our tutorial series on how to set up a home hacking and security testing lab. In part three, we set up a completely virtual network inside VirtualBox in order to use Kali to test the (in)security of the Metasploitable2 virtual machine. In the present article, we'll set up a local area network similar to one you might find in any home, and then walk through a man-in-the-middle attack against an everyday router.

Here's our hypothetical scenario: there is a malicious individual on a local area network listening in on the network traffic (sniffing it, as they say) using ARP poisoning in an attempt to steal login credentials from the router's administrator so as to hijack the device, and by extension, the network. In this scenario, Kali will once again function as the attacker but the host computer will be the victim.

This configuration will require a router specifically for the purpose of hosting our home lab's local area network. This could also be accomplished virtually, but having the external network will allow us to test the security of other external networked devices moving forward.

Configuring the Local Area Network
For the present test, which was successful, I picked up one of those ubiquitous Netgear WNR 2000 series home routers at a local flea market for ten dollars. You might even have an old router just lying around collecting dust. Plug the router in, turn it on, and configure it as desired. An online manual for this router stated that once you have connected your computer to it, you can navigate to the URL routerlogin.net or the device's ip address in a web browser to log in for administrative purposes. They further provided the factory default login credentials: 'admin' for the login name, and 'password' for the password. The first thing I did upon logging was to change the password using the router's so-called "Smart Wizard".

I prefer to hook up devices to the lab router through ethernet, and turn off wireless networking in the router when I'm feeling paranoid. Log into the router, and adjust settings as necessary. It should have DHCP, to provide ip addresses to hosts on the network. Keep it completely isolated from your actual home LAN that is connected to the internet, at the very least because connecting a second dhcp server to your main home network would cause a fair amount of chaos. We'll soon see whether this sort of interaction with the router is secure in any way. (Spoiler alert: in the case of the WNR 2000, it is not.)

Once your router is setup, open the Network settings in your Kali machine and change the attachment from the internal network to bridged mode, and attach it to the appropriate interface. (People who are more comfortable with managing multiple interfaces on Linux could just add a second adapter and switch between the two inside Kali.)  Under the Advanced section of Kali's Network settings, notice the drop down menu for Promiscuous Mode. This setting is important for our test. There are three options here: Deny, Allow VMs, and Allow All. Set it to Deny. This means that Kali will not be privy to any traffic directly to or from its host machine or other VMs that may be on the network.


Why have we set Promiscuous Mode to Deny?

Abstinence-Only Networking and the IP Stack
When Kali is running in bridged networking mode, so as far as the rest of the hosts on the network are concerned, it is a completely independent host. But it's not, it's a virtual machine, it shares its network interface with its host computer, and by extension with any other VMs that might also access that interface.

If we set promiscuous mode to Allow All, the Kali machine will pick up all traffic going over the network interface, to which it has access because it is itself bridged over this interface. That obviously includes the given network's traffic sent to and from the host computer on which the virtual machine is running, as well as any other virtual machines it might be running on that interface. If the host computer pings the router, Kali will pick up the traffic.

When promiscuous mode is set to Deny, on the other hand, Kali networks with the host computer (and any other virtual machines that might be on the network) as if they were all on completely separate physical devices. If the host computer pings the router, Kali will not pick up the traffic.

If there is a secondary computer on the network, even if Kali is in promiscuous mode, it will not be able to capture a ping from that computer to the router, or any other such traffic between them, for that matter, such as an http session.  

When we run the man-in-the-middle attack against the router and the host machine, however, we'll see that we can pick up traffic between them. One might wonder whether this is a true man-in-the-middle attack, because as we already know, the Kali guest and the host computer share an interface. Kali already has access to the host machine's traffic. Setting up the sniffer is basically just enabling promiscuous mode on the adapter setting.

However, we are not conducting a physical layer attack. ARP poisoning is conducted between the link layer and the network layer of the IP stack. This could be demonstrated with a secondary host on the network. An ARP attack by Kali against the secondary computer will still work even though Kali does not share a physical network interface with the victim, and could not detect such traffic even in promiscuous mode.


Reconnaissance and Scanning the Network
There should now be three hosts on the lab LAN: 1) the router, 2) the host computer (our victim), and 3) the Kali virtual machine (our attacker). Let's begin by conducting some passive monitoring of the network traffic.

Open up Wireshark on your Kali instance and conduct a live capture, to see what kind of traffic you can pick up on this network. (See part two in the series for info on how to properly configure Wireshark to conduct a live capture, if you haven't already.) Let the scan run for about half an hour. My capture picked up:
  • SSDP broadcasts from the router, alerting hosts as to its existence
  • ARP broadcasts from the victim computer and the Kali host machine, seeking out the router's hardware address from its ip address.
  • DNS requests to external websites for services running on Kali and the host machine, these are obviously unresolvable, since the network is not connected to the internet. (I would also like to shut down these services later if they are not system critical, as I don't like the idea of my machines contacting random services on the internet without my say so.)
Nothing really seems out of the ordinary here, so let's run a scan of the network. Here's the topology graphic produced by Zenmap from a default nmap scan of my lab network:


The router is at 192.168.1.1, the primary host computer is at 192.168.1.2 and the Kali machine is at 192.168.1.5. As you can see, Zenmap's color coding indicates that there may be some vulnerabilities in the router.

This scan discovered three open ports on the router, and found no open ports on any of the other hosts. Ports 23 (telnet) and 80 (HTTP) were found open by default on the router. We would expect port 80 to be open since you can log into the router with a web browser for administrative purposes. It seems a bit odd that the telnet port is open as well, as it is unlikely anyone today would be telnetting into the router on their home network. This is a security vulnerability, but, fortunately, this router does not actually allow simple telnet access to its administrative interface. Any basic attempts to connect to it via telnet are rejected, which makes one wonder why it is open to begin with.

Now let's attempt to systematically determine what traffic on the network the Kali instance is able to capture. All packets sent from or to the Kali VM will be captured in Wireshark, since the capture is running on that system: ex. ping requests to the router from Kali, ping requests to Kali from the host computer, HTTP traffic if you use a Kali web browser to navigate to the router's admin page, and so on.

As noted above, if your Kali virtual machine's network settings were in promiscuous mode, Wireshark would also capture any packets directly sent to or from the host computer. But this is not the case here as we have set promiscuous mode to Deny.

With promiscuous mode set to Deny, if you ping Kali from the host computer, the Wireshark capture will pick up all of these packets, since they are being sent directly to and from the Kali machine. However, if you ping the router from the host computer, none of the request or reply packets will be picked up by your Wireshark capture in Kali, nor will any other such traffic. For example, if you use a web browser on the host computer to navigate to the router's login interface, the capture will not detect any of this traffic.

With this observation, we have acquired our target. What we would like to do is two-fold: 1) pick up any direct traffic at all between the host computer and the router, 2) pick up any sensitive traffic (and any correspondingly sensitive information) sent between these devices.

Running a Man-in-the-Middle Attack with Ettercap
To compromise the traffic between the host computer and the router, we are going to use a program called Ettercap. As noted in its manual page, Ettercap is a "multi-purpose sniffer/content filter for man in the middle attacks." Ettercap can be run from the command line or through its graphical interface. To launch the graphical interface, type the following command into a terminal: sudo ettercap -G. The Ettercap graphical interface:


However, we're going to run Ettercap from the command line, as this conserves more resources on the host machine since it does not require excess RAM. Our plan is to use arp poisoning to capture traffic between the victim and the router. Reading through the Ettercap manual pages allows us to determine that we can use the following command to conduct our attack:
sudo ettercap -i eth0 -T -M arp /192.168.1.1/ /192.168.1.2/
Before we run the command, let's take a closer look at what's going on here: 
  1. sudo runs the command as a privileged user. This is necessary for Ettercap to conduct the packet capture.
  2. ettercap tells the shell to run the Ettercap program.
  3. -i eth0 tells Ettercap to run the capture on the eth0 interface inside Kali. This may be different for you depending on how you have your network adapters set up. If you try to run arp poisoning on an interface that is not enabled, Ettercap will likely complain that "No such device exists". If you run it on an interface that is enabled, but not connected to a network, Ettercap will complain that "ARP poisoning needs a non empty hosts list".
  4. -Tq tells Ettercap to run in text mode (-T), meaning it will print out any text characters found in its capture.
  5. -M tells Ettercap to run a man-in-the-middle attack.
  6. arp specifies that Ettercap should run an ARP poisoning man-in-the-middle attack.
  7. /192.168.1.1/ and /192.168.1.2/ specifies the two specific hosts we want to target.
Let's see if we can capture any traffic between the victim and the router. Start a Wireshark live capture on Kali. Now ping the router from your host computer, and just let it ride (ex. ping 192.168.1.1). If you are running in non-promiscuous mode, Kali will not pick up any of the ping requests and replies between the victim and the router.

Now run the Ettercap command above (with any necessary substitutions for your own network configuration) from a terminal in Kali. If successful, the Wireshark capture should now begin picking up the echo requests and replies between the victim and the router (as well as any other packets passing between them), and Ettercap will print to the terminal any text picked up in those packets. You can now stop the live capture, quit Ettercap and stop the ping from the host machine to analyze the results. 

The next question is whether we can pick up any sensitive information, such as login credentials, passing between the victim and the router. For this, we'll slightly modify our Ettercap command:
sudo ettercap -i eth0 -Tq -M arp /192.168.1.1/ /192.168.1.2/
As you can see, everything is the same here, except I've added a q to the -T option. This tells Ettercap to run in quiet mode, which means that it will not print any and all text it picks up in captured packets, but rather only text of potential significance, such as login credentials. For our test, we want to see if we can capture the victim's credentials when logging into the router.

Start a new Wireshark live capture in Kali. Run the Ettercap quiet mode command in a terminal. Now, on the host computer, use a web browser to navigate to the router and log in to the administrative interface. Here's the result in Ettercap when I ran this attack against the WNR 2000 router:


As you can see, Ettercap picked up the victim's user name (here: 'admin') as well as the password (here: 'supersecretstring'). Moreover, the router passed the login credentials over the network in plaintext six times when the victim logged in to the device! Obviously, 'supersecretstring' is not a very good password, but in the present case it doesn't really  matter how secure the password is, since the router passes it over the network in plaintext.  
The login credentials can also be found in the Wireshark packet capture run alongside the Ettercap ARP poisoning attack. My Wireshark capture picked up a lot of packets, so let's do a search for 'credentials':


Inspecting the first packet returned from this search, reveals the following under the HTTP section of the packet view:


And there they are, the user name and password, conveniently located under the authorization heading: 'admin:supersecretstring'.   In fact, it turns out the login credentials are sent in plaintext every time the victim loads another page in the router web interface!

The victim's router admin account has now been compromised. After the victim logs out of the router, the attacker can immediately log in with admin privileges, change the password and lock out the victim, or make changes to the system's settings, turning it off, etc. The "Smart Wizard" on the WNR 2000 router isn't so smart or wizardly after all!

Now the question is: does this attack work against the router on your home lab? Let us know in the comments.

Reflecting on this attack, one would probably ask: Can't we detect this attack as it was going on? Does it not create a whole load of excess traffic on the network? Wouldn't it be clear from a packet capture on the victim machine that the intrusion took place? Wouldn't it even identify the ip and hardware addresses of the attacker? The answer to all those questions is in the affirmative, but you'd need to have been monitoring the network traffic over the whole course of the login session to know that. A simpler solution for the potential victim is to check the system's ARP cache before logging in to the router. This will identify whether there are two hosts on the network with the same hardware address. Since hardware addresses are supposed to be universally unique, this is a tell-tale sign that ARP spoofing is in progress.


Moving Forward
Now that you have your lab's local area network set up, what can you do with it moving forward? Well, that's up to you! At the very least, you can use it to test the security of any given networked device you like, whether it's your main computer, a secondary computer, a cell phone, a tablet, a network drive or fileserver, a television or gaming console, and so on. Do you know what precise information your cell phone or laptop broadcasts to the entire local area network when you connect to any wireless device?

That concludes part four of our tutorial series on setting up a home hacking and security testing lab. If you've followed along from the beginning, you now have a virtual network you can use to explore the vulnerabilities in Metasploitable, an isolated local area network to test the security of any device you wish, and some familiarity with a handful of the many tools that are bundled with Kali.

As always, questions, comments, suggestions and criticism are welcome in the comments. Happy hacking!

Hack Lab Part 3: Installing the Victim Machine on a Virtual Network and Basic Exploits

This post is part three in our tutorial series on how to set up a home hacking and security testing lab. If you followed along in parts one and two, you have installed a Kali virtual machine in VirtualBox on your primary computer, and have begun exploring your home computer network with nmap and Wireshark, both of which come bundled in Kali.

In the present article, we will walk through the creation and installation of our victim machine, a virtual instance of Metasploitable2, and then configure our first lab network: a completely virtual internal network inside VirtualBox. We'll place the Metasploitable2 victim machine and the Kali attack machine on the virtual network, and conclude by showing one way to begin exploring and exploiting Metasploitable's various vulnerabilities with Kali, and then provide some resources for further study.

On that note, it must be stated at the outset that Metasploitable is an intentionally insecure machine, with a ridiculous number of vulnerabilities. It should never be exposed to the internet, or to an untrusted network. This is why we will connect it to a completely virtual network, one that cannot even be accessed by the host machine that is running VirtualBox.


Installing Metasploitable2 in VirtualBox
There are number of subtle differences between creating a Metasploitable virtual machine and creating a virtual instance of an everyday operating system such as Kali in VirtualBox, as wel shall see. Metasploitable2 is a prepackaged system intended for security testing and practicing common exploit techniques. Once the machine is set up, it does not require any updates or further configuration as was the case with Kali.

The first step, of course, is to download a copy of the Metasploitable2. Metasploitable2 was developed by Rapid7, the IT security group that created the Metasploit Framework, "a tool for developing and executing exploit code against a remote target machine," as noted at Wikipedia. The Metasploit Framework, as you may know, is also bundled in Kali, and the intentionally vulnerable Metasploitable2 system was created to provide a way to test the sorts of exploits that can be launched from Metasploit, among other tools.

You can download Metasploitable2 from Rapid7, but it is also available from other sources such as SourceForge. Once you've downloaded the file, unzip it, and place it wherever you prefer. I keep all my virtual machine .iso files and the like in a dedicated folder.

In the Metasploitable2 download, you'll notice a few differences from your Kali download. For Kali, we used the .iso disk image file to install the system on the machine. There is no .iso file for Metasploitable2. Instead we are instead going to install the Metasploitable.vmdk file, which stands for virtual machine disk format.

Start up VirtualBox and click "New" to begin setup of the victim system. Name the new virtual machine, select its type and version. I've just used the defaults here: Ubuntu, 32 bit. Click "Next".


Since we will not be using the Metasploitable system directly, but rather only interacting with it as a target, we can lower the amount of RAM we allocate for it.  I've chosen 384 MB as the initial setting. After you get it up and running, you might find that you can reduce it even further. In my experience, response times begin to noticeably lag around 256MB of RAM. Click "Next".


We do not need to create a virtual hard drive for Metasploitable. Instead the .vmdk file will act as a virtual hard drive itself. Select "Use an existing virtual hard drive file", then click the file-browser icon, navigate to your Metasploitable download files, and select the .vmdk file. Click "Create".


The newly created instance should now appear in your VirtualBox interface. Notice I have grouped my kali1 instance and my Metasploitable2 instances inside a folder labeled 'lab'. Grouping becomes very helpful once you have more than a couple virtual machines set up.


Now we need to tweak a couple settings for our Metasploitalbe virtual machine. Open the Settings window. I uncheck 'Floppy' in the boot order under the System menu, though this is not very important. In the Network settings, you'll notice that the default is the same as it was for Kali: there is a single network adapter enabled with NAT, natural address translation.


We're going to change NAT to an internal VirtualBox network. In the "Attached to" drop down menu, change adapter one by attaching it to "Internal Network". You can also name your new virtual network. The default name is 'intnet'. I'm going to call mine 'labnet'. Click OK.


We're not quite ready to fire up our victim system just yet. Or at least, I'm not, because I've chosen a new name for my internal network. My experience with internal networks in VirtualBox has been a bit inconsistent. I clearly recall that the first time I used an internal network, it just worked and no further config was necessary. On another computer, I later found that the default internal network 'intnet' had to be configured as you would any custom internal network. If you fire up your Metasploitable virtual machine, log in and find that you have a functioning ip address, you're all set and can skip the following section. Otherwise, read on.

Configuring the VirtualBox Internal Network
I have to now enable the VirtualBox internal network 'labnet' to which I've just attached my Metasploitable virtual machine. If we take a look at the VirtualBox user manual section on Internal Networking, we read:
Unless you configure the (virtual) network cards in the guest operating systems that are participating in the internal network to use static IP addresses, you may want to use the DHCP server that is built into VirtualBox to manage IP addresses for the internal network. Please see Section 8.35, “VBoxManage dhcpserver” for details.
Rather than set up static ip addresses for our virtual machines on the virtual internal network, let's set up the virtual dhcp server. Reading through the VirtualBox user manual section on managing the dhcp server, we can conclude that running the following command in a terminal on the host computer will appropriately configure the internal labnet network.
VBoxManage dhcpserver add --netname labnet --ip 192.168.1.1 --netmask 255.255.255.0 --lowerip 192.168.1.2 --upperip 192.168.1.255 --enable
What's going on here? Let's parse this command.
  • There is the command for the VirtualBox dhcp server: VBoxManage dhcpserver
  • We want to create a new network, therefore: add
  • We indicate the name of the new network: --netname labnet
  • We specify the ip address of the dhcp server itself: --ip 192.168.1.1
  • We specify the subnet or netmask: --netmask 255.255.255.0
  • We specify the lower ip address for the server: --lowerip 192.168.1.2
  • We specify the upper ip address for the server --upperip 192.168.1.254
  • Finally, we enable the network so it starts any time a machine on the network is started: --enable
If successful, you can now fire up your new victim system and it will automatically be connected to the newly-configured internal virtual network. Go to the VirtualBox interface, select the system and click Start. This is the Metasploitable login screen:


Run ip addr or ifconfig to confirm that the system has been given an ip address and make a note of it. The victim is prepped. Did I mention? Metasploitable is an intentionally insecure machine, with a ridiculous number of vulnerabilities. It should never be exposed to the internet, or to an insecure network!

Now let's put our attack machine on the internal network. Network adapters can be changed in this manner even if the machine is running, though in my experience, this can also lead to minor glitches in the functioning of the VM, so I usually shut down if I'm going to change network settings for a VM.

Select your Kali instance in the VirtualBox application interface, click Settings, go to the Network settings. Change the adapter from Bridged to Internal Network, and select the name of your newly created internal network. I also "Allow All" in promiscuous mode under the advanced settings, as this allows the Kali network interface to detect any and all packets to and from the other virtual machine (as well as the host computer, if it were able to connect to the same network). Click OK.

Start up Kali and log in if the machine is not running. Check ip addr or ifconfig to make sure you have gotten an ip address from the virtual dchp server. If so, you're all good! Open up the Ice Weasel browser that comes bundled with Kali. In the address bar, enter the ip address of your Metasploitable instance. When the page loads, you should see the web interface that is pre-configred on the Metasploitable virtual machine. It comes packaged with 5 different websites/webapps that are intentionally insecure: TWiki, phpMyAdmin, Mutillidae, DVWA, WebDAV:


At this point, you now have a virtual internal lab network running on your host computer, and two virtual machines running on that network: your Kali attack machine and your Metasploitable victim machine. Remember, this network is completely internal to VirtualBox. Your virtual machines cannot communicate with the host computer over this network and the host computer cannot communicate with the virtual machines over this network. They are isolated.

Exploring Metasploitable's Vulnerabilities
Now the real fun begins! The first thing you might do here is passive network monitoring to see what kind of packets, if any, the victim machine is sending out over the network. Fire up Wireshark inside Kali, and start a capture on the appropriate interface for the lab network. (See part two of this series on how to configure Wireshark for live capture.)

From the packet capture, you'll soon notice that Metasploitable sends out workstation and workgroup announcements every couple of minutes for services that are running on it. If you inspect those packets more closely, you'll find that those packets contain a good deal of information about the host machine sending them, as well as about the services running on it.

An an exercise, confirm by inspecting the packets you've captured that Metasploitable is: 1) a workstation, 2) a server, 3) a print queue server, 4) a Xenix server, 5) an NT Workstation, 6) an NT Server, and 7) a Master Browser. You can doubly confirm that the machine is running such services by browsing its shares over the network in the file manager. But where can we find the network login credentials to view the shares?

Now that we have some idea of what we're dealing with, let's conduct a few port scans of the victim system to see what vulnerabilities that might expose. Let's just go through some of the various default scan types built in to Zenmap to see what they bring to light.

A ping scan reveals that the host is up. A quick scan identifies 18 open ports, among them the reserved ports for ftp, ssh, telnet, smtp, htttp, mysql and so on. A regular scan identifies 23 open ports. An intense scan also reveals 23 open ports, but it also provides operating system and version information, along with more detailed information about the services running on the various ports. For example, it notes that anonymous ftp login is allowed on port 21, identifies the SSH server's hostkey fingerprint, and so on. Run the more intensive scans to see what else you can find.

As an exercise, analyze the command options used in the various Zenmap scans to determine why those particular scans revealed that particular information.  

It is worth noting here that a couple leads for tracking down Metasploitable's network login credentials are provided already in the simple quick scan. However, it is indicative of the system's complete insecurity that these leads make the question of determining the network login credentials moot. Can you identify any such lead and why it moots our earlier question?

If you've followed along this far, you're probably asking yourself: what's next?  (That is, if you haven't jumped ahead already.) Well, you now have a fully functioning virtual hacking lab outfitted with one of the most powerful attack systems and one of the most vulnerable victim systems around. It's time to start exploring some of the more involved tools bundled in Kali and see what other kinds of weaknesses you can identify and exploit in the various services running on the victim machine, including in the five websites and applications running on the system.  That, however, is beyond the scope of the present article, but here are some resources to help get started:
Like nmap and Wireshark, all three of these tools are listed in Kali's "Top Ten Security Tools" menu.

That concludes the present article. In part four of the series, we'll set up an external local area network and demonstrate how it is possible to steal login credentials from a victim machine logging in to a compromised router. As always, questions, comments, suggestions and criticism are welcome below.

Hack Lab Part 2: Exploring Your Home Computer Network with Kali Linux

This article is part two in our tutorial series on how to set up a home hacking and security testing lab. If you followed along in part one, installing a Kali Linux virtual machine in VirtualBox, you have installed VirtualBox on the primary computer for your home lab and created a Kali Linux virtual guest on this host machine. The Kali system has been fully updated and VirtualBox Guest Additions have been installed on it. Finally, your Kali VM has a single network adapter running in bridged mode and you have set up an administrator account on the Kali instance. 

Creating and configuring the virtual network setup outlined in the introduction, which we will do in part three of this series, requires a few more steps: we still have to download and install Metasploitable, set up the virtual network, etc. But if you're like me, you're probably already itching to start playing with all the toys Kali has to offer, if you haven't already!

Home Network Analysis 101
This article will show how some of the tools that come bundled in Kali can be used to explore your existing home computer network, and test whether you can successfully identify all the devices that are connected to it. In particular, we'll take a look at a set of tools that come bundled in Kali that can be used for network analysis: nmap/Zenmap and dumpcap/Wireshark.

These will come in handy in our eventual testing lab, but they can obviously also be used to explore your home local area network as well. Nmap is a command line network scanner, and Zenmap is a graphical interface to nmap. Dumpcap is a command line network traffic monitor, and Wireshark provides a powerful and versatile graphical interface to monitor network traffic and analyze network packet capture files.

Here's a simple experiment. Do you happen to know how many devices are currently connected to your home network? Can you identify all of them off the top of your head? Try to do so, and make a list of them. At the very least, we know there will be at least three: the Kali guest, the host machine you are running Kali on, and your router. There may also be more computers or cell phones connected to it, and maybe even your television, refrigerator or coffee maker!

We are first going to use nmap to see if we can identify any such devices on the network, and perhaps detect one or two that we did not think or know were connected to it. We'll then configure Wireshark and run a packet captures to get a sense for the normal traffic on the network, and then run another capture to analyze just how an nmap network scan works.

Determining Your IP Address
Before we can scan the network with nmap, we need to identify the ip address range we would like to examine. There are a number of different ways to determine your ip address on a Linux distribution such as Kali. You could use, for example, the ip or ifconfig commands in a terminal: ip addr, or sudo ifconfig.

(Note that if you are using an administrator account inside Kali, which is considered a best practice, when a non-root user enters a command such as ifconfig into a terminal, the shell will likely respond by complaining "command not found". In Kali, sensitive system commands like ifconfig have to be run as root. To access it from your administrator account, all you need to do is add "sudo" to the front of the command: sudo ifconfig.)

These commands will provide you will a wealth of information about your network interfaces. Identify the interface that is connected to the LAN (likely eth0), and make a note of the ip address indicated after "inet" for the ip addr command, or after "int addr:" for the ifconfig command. That is your ip address on your local area network. Here are a couple ifconfig and ip addr outputs posted by the Ubuntu Journeyman:



As you can see here, the ip address for this machine is 192.168.1.4.5. Yours is likely something similar to this: for example, 192.168.1.123 or 10.0.0.56 etc. Notice in the ip addr output above, the ip address is: 192.168.4.5/24.  That means 192.168.4.5 is the ip address of that specific machine, while the /24 at the end indicates the address space for the LAN's subnet, which in this case are all the addresses from 192.168.4.1 to 192.168.4.255.

If we were to scan this local area network with nmap, we would want to scope out all the addresses in the network's range, which means 192.168.4.1, 192.168.4.2, 192.168.4.3, 192.168.4.4, and so on, all the way to 192.168.4.255. One shorthand way of notating this is: 192.168.4.1-255. Another common shorthand is 192.168.4.0/24.  Of course, if your address were 10.0.0.121, then the shorthand would be: 10.0.0.1-255 or 10.0.0.0/24. 


Host Discovery
Let's assume your Kali VM has the ip address 192.168.1.5 on a subnet with possible host addresses from 192.168.1.1 to 192.168.1.255. Now that we know Kali's ip address and the address range we want to take a look at, open up a terminal and type: nmap. This will provide you with a long list of all the options available within the nmap program. Nmap is a powerful program and there are a lot of options! Perhaps the simplest possible network scan that can be conducted with nmap is a ping scan, for which we use the -sn option.

Now type nmap -sn 192.168.1.1-255 into your terminal and hit enter. (Don't forget to substitute the address range for your network if it is different from this!) This scan will tell you how many hosts nmap discovered by sending a ping echo request to each of the addresses in the range x.x.x.1-255, and provide you with a list of the ip addresses of the hosts that returned a ping reply. This is host discovery 101. Here is the ping scan output from nmap on a simple local area network I set up for the purpose:


The ping scan found 5 hosts up with the addresses: 192.168.1.1, .2, .3, .5 and .6.  Note that in the wild, this method of discovery may not work, as it is becoming increasingly common for administrators to configure their systems so that they do not reply to simple ping echo requests, leaving a would-be ping scanner none-the-wiser about their existence.

Did your scan find the same number of hosts that you had presumed were on your network? Were there more or less?

We can use the default nmap scan to further investigate known hosts and any potential ghost hosts the ping scan may or may not have uncovered. For this, simply remove the -sn option from the command above: nmap 192.168.1-255. Here's the output of the default nmap scan on the same network as above:


Nmap has returned much more information. It found three open ports on the router at 192.168.1.1, as well as an open web server port on host 192.168.1.2.  All scanned ports on the remaining hosts were closed.

You can also use nmap to further investigate known hosts. The -A option in nmap enables operating system detection and version detection. Pick out a couple of the hosts discovered by your nmap scans, for which you already know the operating system type and version. Now scan these hosts with nmap for OS and verstion detection by adding them to your host address target list, separated by commas.  For example, if I would scan the router and web server discovered above for OS and version detection with the command: nmap -A 192.168.1.1,2. This will return more information, if any is determined, on those hosts.

You can obviously also run an OS and version detection scan over the whole network with the command: nmap -A 192.168.1.1-255. Depending on the number of hosts on your network, this scan could take a couple minutes to complete. If you press <Enter> while the scan is running, it will give you an update on its progress.

If there are more and a handful of hosts on your network, the output can be hard to parse in the terminal. You could send the output to a file with:  nmap -A 192.168.1.1-255 > fileName.txt. Or you could use one of nmap's own built-in file output options.

But this is also where Zenmap comes in quite handy. Open up Zenmap from Applications->Kali Linux->Information Gathering->Network Scanners. If you are running as an administrator and not root, as you should be, you will get a message stating that not all of nmap's functionality can be accessed without root privileges. Root is not necessary for basic scans. However, you can run Zenmap as root by opening a terminal and typing: sudo zenmap. The Zenmap interface:


The Zenmap interface is pretty straightforward. Enter the target ip address or address range into the target field. Changing the scan profile from the drop down menu changes the scan command. You can also manually enter or edit commands in the command field. After you run a scan, Zenmap also helpfully breaks down the results for you, providing host details, port lists, network topology graphics and more.

Play around with the various built-in scan types. Can you identify all the hosts on your home network with a ping scan? a regular scan? an intense scan? Can you identify all the open ports on those hosts? If you have a laptop or another device that you frequently use to connect to the internet over public wi-fi hotspots, you can also do intensive scans of those devices to determine if there are any open ports that would represent a potential security vulnerability. Identifying open ports is important for vulnerability assessment, because these represent potential reconnaissance or attack vectors.


Network Traffic Capture and Analysis with Wireshark
Nmap scans a network and probes hosts by sending out ip packets to, and inspecting the replies from, its target at a given address. With 255 addresses to scan along with 1000 ports on all discovered hosts in the default scan of the subnet above, that's a lot of network traffic! What does the packet traffic generated by a scan look like on the network?

To answer this question, we can use Wireshark and dumpcap. Dumpcap, as its name implies, is a command line tool that dumps captured network traffic. Wireshark provides a graphical user interface to analyze these sorts of dump files, which are collections of all the network traffic to which the given network interface was privy.

If run with the proper privileges, Wireshark can capture live network traffic as well. In Kali, you can find Wireshark under: Applications->Kali Linux->Top 10 Security Tools. Unless you have already configured Wireshark with the appropriate settings, when you open it for the first time you will be informed by the "Capture" panel that "No interface can be used for capturing in this system with the current configuration."


In its documentation, Wireshark recommends appropriate settings to enable capture privileges. This also suggests confirming that Wireshark can also be run as root. To run Wireshark as root, you can log in as root, or run sudo wireshark in a terminal. When you run Wireshark as root, you will first be given a usage warning and provided with sources for how to set up proper privileges. This forum post on AskUbuntu boils the process down to three simple steps.

Now that you've enabled live captures in Wireshark, let's run one! Click "Interface List" in the Capture panel of the default view. Choose the interface that is connected to the network (it will indicate your ip address on that network), and click Start.

This will immediately begin a live capture of all the packets on the network to which the interface has access. At the very least, it will detect: 1) packets it sends out, 2) packets it receives directly, 3) packets it receives indirectly if they are broadcast to all the hosts on the network.

If you have never viewed a network packet capture before, you may be surprised what you can see, and what information is simply being broadcast over the network. You'll probably find messages from your router, you'll see internet traffic packets if you are viewing a webpage in a Kali browser, or on Kali's host computer (depending on whether or not Promiscuous Mode is enabled in the VirtualBox advanced network settings for your Kali machine). You might find that one device is especially chatty for no good reason. There might be devices pathetically sending out calls to other devices that have been removed from the network, such as a laptop searching for a printer that has been turned off, and so on.

The default Wireshark packet capture interface numbers each packet it captures, and then notes the time after the capture began that it received the packet, the ip address of the source of the packet, the ip address of the destination of the packet, the protocol, the packet's length and some info. You can double click an individual packet to inspect it more closely.

If you ping your router (which you should have been able to identify via nmap analysis) from Kali, you'll see all the requests and replies, obviously, since the Wireshark capture and the ping are running on the same machine. But the Kali guest shares its interface with the host machine. If you enable promiscuous mode in the advanced network settings inside VirtualBox for your Kali instance, when you ping your router from the host machine itself, the Wireshark capture will similarly allow you to see all requests and replies, they're going over the same interface! If you disable Promiscuous Mode, on this other hand, this will not be the case. In this case, packets to and from the host computer will not be picked up, as if it were a completely separate physical machine. Similarly, if you ping your router from a different computer, you will not see the request/reply traffic at all, though perhaps you might pick up an ARP if the requester does not already know the (hardware) address of the request's intended recipient.

After getting a feel for what the base level network traffic looks like on your network, start a new capture, and then run a simple scan from nmap or Zenmap, and watch the result in Wireshark. When the scan is finished, stop the capture and save the file. Capturing the simple nmap ping scan from above on my network resulted in a file with over 800 packets! Now you can analyze the network traffic generated by the scan itself. You'll probably want to play around with Wireshark for a bit to get a sense of what it offers. There are tons of menus and options in Wireshark that can be tweaked and optimized for your own ends.

Well, that's it for this article. In part three of our hack lab tutorial series, we'll install our victim machine, an instance of Metasploitable2, in VirtualBox and set up a completely virtual lab network to explore some more tools that are bundled in Kali. As always, comments, questions, corrections and the like are welcome below.