ZAP Penetration Testing: A simple Tutorial to Detect Vulnerabilities

http://www.toobler.com/blog/zap-penetration-testing-simple-tutorial

Penetration testing (otherwise known as pen testing, or the more general security testing) is the process of testing your applications for vulnerabilities, and answering a simple question: “What could a hacker do to harm my application, or organization, out in the real world?”

Recently I came across a tool, Zed Attack Proxy (ZAP). Its main goal is to allow easy penetration testing to find vulnerabilities in web applications. It is ideal for developers and functional testers as well as security experts. Let’s check out how ZAP penetration testing works.

Installation and configuration of ZAP:

Download Link:
https://github.com/zaproxy/zaproxy/wiki/Downloads

Step1
Adding a site to the testing scope

By telling ZAP what the target site is, ZAP can limit the scope of the scan and only scan the target site for vulnerabilities.
1. Open the web application that you want to test.
2. In Zap you will find your website/application displayed under sites.
ZAP will spider that URL, then perform an active scan and display the results.

 

blogpic1

 

Zap runs on proxy, to set up the proxy in ZAP:

Close all active Firefox browser sessions
ZAP tool -> Tools Menu -> Options -> Local Proxy -> Change Address = 127.0.0.1 Port = 8080.
Mozilla browser -> Tools Menu -> Options -> Advanced tab -> Network -> Settings -> Select Manual Proxy configuration:- HTTP Proxy = 127.0.0.1 Port = 8080.

Now try to connect to your application using your browser.
If you can’t connect to it then check your proxy settings again. You will need to check your browser’s proxy settings, and ZAP’s proxy settings. It’s also worth checking that the application that you are trying to test is running!

When you have successfully connected to your application you will see one or more lines in ZAP’s Sites and History tabs.
Note that most of ZAP’s tabs provide additional functionality that could be accessed via ‘right click’ menus.

Right click on the HTML -> Attack -> Active scan
ZAP will perform active scan on all the pages and display the results.

 

blog pic 2

 

Save the ZAP session

Once you have manually explored the application it would be a good time to save the ZAP session so that you can look at it again.
If your application has multiple roles then you should explore it with each role and save the sessions in separate files.

 

Generating a Report:

ZAP tool -> Report -> Generate HTML report (Any other options listed) -> Save and share the report.

Authentication , session and User management using ZAP

1) Context: Represents a Web application
2) Session Management Method: How are the web Sessions identified by the server and handle requests

Example: cookie based using query parameters
3) Authentication Method: How is a new session established?
It could be either Form based authentication method, HTTP based or oath methods.
4) User Management: Handling users of web application that could be used for executing actions
Example: user name/password pair

Steps to follow:

1) Set proxy in local browser/access url: https://pr-uat.iptquote.com
Now include web app in context.

Context includes:

(i)Authentication
(ii)Session management
(iii)Users management

Context: Form based authentication

(I) log-in from target url: https://pr-uat.iptquote.com/login.php

(ii) Login Request POST Data: username={%username%}&password={%password%}&proceed=login

(iii) Set params as: username =password

(iv) Include regex pattern for logged in or logged out response
Regex pattern for logged in response :- \Qa href=”https://pr-uat.iptquote.com/login.php?proceed=logout\E

 

blogpic3

Context: Session Management

blogpic4

 

Context: User management

For user management, we can add 2 users, one valid user let it be the “Existing user” here “superadmin” in our example and other is “Test User” invalid user.

 

blogpic5

 

Spider url attack applied to “Test user”

If spider url attack applied to the Test user returns get_login.php (error_message), also once spider attack completed “Test User” accesses home url only. uri’s covered: 31 is shown in the screenshot, where as only scan through https://pr-uat.iptquote.com

blogpic6

 

Spider url attack for existing valid user “Superadmin”

 

blogpic7

 

Here spider url attack applied to the Existing valid user. That is user with super admin logged in credentials. In the attached screenshots returns “POST login.php ( request _url) if selected, returns Uri’s covered 182 for the valid user. He can access all sites.

If you have any interest in application security then you should download ZAP and try it out.

Links:

OWASP https://www.owasp.org
Zed Attack Proxy, https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project

Advertisements

How to write Cordova Plugins

View story at Medium.com

How to write Cordova Plugins

Cordova Plugins are one of the dark arts of hybrid app development, helping web apps running natively access the full power of the device underneath. Their obscurity separates the haves from the have nots, with whole swaths of Cordova users relying on a relatively small group of plugin developers to build and maintain these crucial pieces of functionality for their apps (like the famous Eddy Verbruggen).

It doesn’t have to be this way. More Cordova developers can and shouldventure into Cordova plugin development, because it’s not as hard as it’s cracked up to be, and the ecosystem needs more people to step in and help out.

At Ionic, we’ve identified the Cordova plugin ecosystem as one of the most important and at-risk parts of the Cordova experience, and we’re working hard to change that through education, maintaining existing plugins, and building new plugins that expand the capabilities and features of Cordova out-of-the-box.

Let’s start at square one and walk through the process of becoming a seasoned Cordova plugin developer. I think you’ll find that it’s much less intimidating than it seems!

0. What is a Cordova plugin?

Before we get into building our first Cordova plugin, let’s take a step back and talk about what a Cordova plugin, and, by extension, Cordova is.

Cordova is a set of command line tools and a plugin bridge for building native apps for the app stores that lets us build our app in a web view, and call native code from JavaScript. When we install Cordova on our computer, we’re installing a set of tools that helps package up this web content, place it into a native app container, deploy it to a device or simulator for testing, and build binaries for final release to the app store.

Inside of that container is a relatively small bridge that transports certain JavaScript calls we make into corresponding native code to give our app the ability to do complex, native things, that aren’t baked into the standard Web APIs.

Building Cordova plugins means we are writing some JavaScript to call down to some Native (Obj-c/Swift, Java, etc.) code we also write, and returning the result to our JavaScript.

To sum it up: we build a Cordova plugin when we want to do something natively that doesn’t yet have a Web API analog, like accessing HealthKit data on iOS or using the Fingerprint scanner on Android.

1. Getting started: scaffolding our first plugin

Plugins plugins everywhere, but how do we start our own? There are two ways to do this: we can use the plugman tool to create one quickly, or we can get all mitosis on an existing plugin by cloning it.

Generally, I prefer cloning existing plugins because you get a faster start with code filled in for all the platforms you want. I’ve cloned the Cordova Device plugin as it’s rather simple, but recently we released a Cordova Plugin Template which comes pretty bare bones. Let’s git clone the template.

We see a few files and directories here, but most importantly: plugin.xml, src, and www:

plugin.xml is one of the most important files here. It’s what Cordova parses to figure out what platforms your plugin supports, preferences it has that the user can configure, source files we’ll include in our final app build, and more. It’s also a bit esoteric so generally we’ll look at other plugin.xml files and use our Computer Science background to copy and paste into ours.

Next is src. This is where our native code lives. If we peek into here we see an ios and android folder.

Finally, www is where the JavaScript code for our plugin lives. This is what gets called first and then kicks off Cordova to call our native code.

Let’s go ahead and copy all the files and directories from the template we cloned to a new directory where we are going to work on our plugin. For this tutorial, we will be creating a simple “echo” plugin, so we can create an echo-plugin directory.

2. Configuring our Plugin

Now for my favorite part: writing XML!!!1

Okay, it’s not glamorous but the plugin.xml file is where everything happens and it’s where we should start. First, we need to give our plugin a unique name and id. As far as naming conventions go, the id is usually of the form this-is-a-plugin, like cordova-plugin-device (as an example):

Next, we’ll set a reference to our JavaScript code:

At a glance, js-module specifies the JS code that will run, and <clobbers> sets what window variable the plugin will be exported under. So, in this case, our script file is www/plugin.js, and when our app runs, we’ll be able to access the plugin at window.MyCordovaPlugin.

Next, we specify the platforms we are going to support, along with references to the corresponding native code for each, starting with Android:

Inside of <config-file> we specify our Android package name and also the symbol Cordova will use to identify our plugin, in this case it’s MyCordovaPlugin. Finally, we have a reference to our main Java code inside of <source-file> which is where our native code lives.

Let’s take a look at ios:

In this snippet, we see much of the same stuff from Android. Inside of <config-file> we have a similar entry to Android just without the Java package format. Finally, we list out the source files Cordova will copy into our app before build, making sure to specify both header and source files we will include. Note: plugins can be built in Swift, but given that Cordova is still in Objective-C and there’s a little overhead to using Swift, we’re going to focus on Objective-c for now.

3. Building our plugin: JavaScript

Let’s start with the JavaScript API that we’d like to expose to the developer. In this case, our JavaScript code lives in www/plugin.js. Here’s what it looks like:

In this case, we have a simple object that has echo and getDate as functions the developer can call. When run, the developer can call this plugin by writing

window.MyCordovaPlugin.echo(‘Hello!’, function() { //callback })

The code that does the magic here is the exec function we’ve imported from cordova/exec. When called, this plugin tells Cordova’s plugin layer to find the plugin identified by PLUGIN_NAME and send the action passed in to either a function call (iOS) or a switching function (android). It’s a good practice to make sure the Cordova symbol name we give our plugin (in this case MyCordovaPlugin) matches the <clobbers target> setting from our plugin.xml, as that will be the window variable we access.

For many plugins, this is as complex as they’ll need to get on the JavaScript side, as the native code is doing all the work. However, I implore future Cordova plugin developers to strongly consider doing more of the actual grunt work in JavaScript instead of Native code. For example, avoid things like String processing, JSON encoding, etc. in Native code because you’d have more platform-specific code to maintain, and often JavaScript performs these tasks with much less mental overhead for the developer (read: string processing in Objective-C is agonizing as all hell). Here’s one of our pluginsthat does a lot of cross-platform work in the JavaScript layer, only using the Native layer to get data the JS layer can’t.

4. Building our plugin: Native iOS

Now for the fun part: writing some native iOS Objective-C code.

Let’s start with the Objective-C header file, in src/ios/MyCordovaPlugin.h:

This header file is a spec of the functions we’ll implement in our corresponding .m, MyCordovaPlugin.m:

These methods are called through Cordova when we run exec() from our JavaScript. They take a CDVInvokedUrlCommand* argument that contains the arguments we passed from JS, along with a reference to the callback the user passed. We can configure the callback to only work once, or to be called repeatedly (by using [result setKeepCallbackAsBool]).

Once in this method, we’re doing plain ol’ Objective-C. Anything you can dream of doing natively you can do here. When you’re done and want to return data back to JS, create a CDVPluginResult object and send it to the commandDelegate which dispatches the result back to JS.

In the example above, the echo method just calls NSLog to echo the string the user passes, while getDate gets a native date from iOS and then converts it into an ISO string and returns it.

This is by no means an exhaustive intro to building iOS Cordova plugins. The best way to go from here to building complex plugins is to study existing ones, like the Geolocation plugin.

5. Building our Android plugin

Building the Android part of our plugin is exactly the same conceptually, but Android plugins have slightly different semantics. Here’s what our src/android/com/example/MyCordovaPlugin.java looks like:

For Android, we have one single execute method that Cordova calls with the action we put into exec() on the JS side, along with the arguments and callback context. Thus, instead of having Cordova call our method directly, we have to check the action string against each action name we support, in this case “echo” and “getDate”. Then, we perform the action and return the result just like on the iOS Side.

Again, to see a more complex Android plugin, take a look at the Geolocation plugin source.

6. Testing plugins

Smashing our keyboard and producing code is the easy part. Now, we need to test and verify our plugin actually works.

To test a Cordova plugin, we need to have a Cordova/PhoneGap/Ionic app to run. Cordova plugins are not runnable on their own.

Assuming we have an existing Cordova app, we can add our plugin locally:

cordova plugin add --link ~/git/echo-plugin

The link flag adds our plugin as a symbolic link, meaning we can work on our code (at least the native code) and rebuild and run our app without having to add the plugin again. However, for some reason, the JavaScript side of our plugin doesn’t automatically update. As we build and modify the JS side, we have to remove the plugin quick using cordova rm my-cordova-plugin and add it back like we did before.

To test the plugin, we just run our app like normal, using our standard Cordova debugging techniques (attach browser dev tools, use IDE console, etc.).

If something ever gets wonky or out of sync, just try removing the plugin and adding it back. If that doesn’t work, remove your platform directory and make sure all references to your plugin are gone from the plugins directory. This tends to happen if you change things like the plugin id or name.

7. Where to go from here

This post was meant to lay out the basics of building a plugin. Day-to-day there isn’t much more beyond what I’ve written here, except lots more native code to do whatever fancy schmancy thing we’re trying to do.

If you’d like to dig in a bit from a slightly more practical angle, I’ve put together a Cordova Plugin Development Guide that runs through building the plugin above and the commands you’d use to add it to your project and test it, along with some advanced topics towards the end.

Whenever I build a Cordova plugin, I’m always amazed at how straightforward it is. For some reason, it always seemed like an incredibly unapproachable topic full of undocumented magic that only a few people knew. That’s not at all the case, and I hope this post encourages more people to try building their own plugins, or improving the ones that already exist out there.

Happy hacking!

Build your first Cordova plugin

https://taco.visualstudio.com/en-us/docs/createplugintutorial/

 

Build your first Cordova plugin

Step 1: Determine what you want your plugin to do

Cordova plugins are appropriate in two main cases:

  • There is a need to expose the native capabilities of a device to a Cordova app.
  • There is a need to encapsulate common functionality across a number of Cordova apps, even if that functionality does not require interaction with the native platform.

In this tutorial, we will focus on the first type of plugin. We will demonstrate the steps needed to create a plugin that accesses a user’s calendar to determine if they are about to be late for a meeting. To do this, we will use the native Calendar APIs present on Android™, iOS™, and Windows Phone ®.

Step 2: Create the plugin skeleton

Before generating the skeleton for your plugin, you should decide on the plugin’s ID and name. In particular, the ID should be unique, and should follow the convention “cordova-plugin-[your-plugin-name]”.

For the purpose of this tutorial, we will go through the process of creating a plugin that uses a device’s native services to determine if a user has an appointment within the next X minutes. The plugin ID will be “cordova-plugin-am-i-late”, and the name will be “Am I Late?”.

Now that we’ve decided on what our plugin will do and what it will be called, we’re ready to create the skeleton. While this can be done by hand, the plugman will generate the necessary folder structure and file for you. To install plugman, run npm install plugman from a command prompt.

To create the skeleton, call plugman as follows:

plugman create --name AmILate --plugin_id cordova-plugin-am-i-late --plugin_version 0.0.1

If the command succeeds, you should see no additional output to the command prompt. plugman should have created a folder structure that looks like this:

AmILate/
|- plugin.xml
|- src/
\- www/
   \- AmILate.js

At this point, you are ready to move onto the next step.

Step 3: Design the JS interface

TEXTGOESHERE

Step 4: Implement the native functionality

Now that the JS interface has been defined, it’s time to start writing the code that will execute on the individual native platforms. Each platform has a slightly different way of interacting with plugins, but we will cover Android, iOS, and Windows Phone in this tutorial.

For each platform, you will add a folder under the src folder, as well as some entries in plugin.xml. Once again, plugman simplifies this process considerably.

ANDROID™

To start, we will add the android platform:

plugman platform add --platform_name android

When the command completes, your folder structure should now look like this:

AmILate/
|- plugin.xml
|- src/
|  \- android/
|     \- AmILate.java
\- www/
   \- AmILate.js

As well, plugin.xml will include these new lines:

<platform name="android">
    <config-file parent="/*" target="res/xml/config.xml">
        <feature name="AmILate">
            <param name="android-package" value="cordova-plugin-am-i-late.AmILate" />
        </feature>
    </config-file>
    <config-file parent="/*" target="AndroidManifest.xml"></config-file>
    <source-file src="src/android/AmILate.java" target-dir="src/cordova-plugin-am-i-late/AmILate" />
</platform>

Mobile platforms often require that apps request permission from the user in order to access particular features. Part of creating a plugin is ensuring that any such permissions are specified by the plugin. For our plugin, we will need to include the “Read Calendar” permission from Android. To do so, we will add the middle line to plugin.xml:

<config-file parent="/*" target="AndroidManifest.xml">
    <uses-permission android:name="android.permission.READ_CALENDAR"/>
</config-file>

While our plugin will only need the single java source file, it is simple to add additional native files to the plugin by adding elements to plugin.xml.

To actually implement the native functionality, we will add the necessary Java code. Looking at the generated AmILate.java, you will see a number of references to “coolMethod”. Those should be replaced with getNextAppointment. As well, the argument is an integer, not a string, so that call should be changed. After updating the scaffolding, the relevant methods should look like this:

@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (action.equals("getNextAppointment")) {
        int minutes = args.getInt(0);
        this.getNextAppointment(minutes, callbackContext);
        return true;
    }
    return false;
}

private void getNextAppointment(int minutes, CallbackContext callbackContext) {
    if (minutes > 0) {
        callbackContext.success("Plugin is working");
    } else {
        callbackContext.error("minutes must be > 0");
    }
}

Before continuing, let’s look at some important features of the code:

  • The action parameter is used to distinguish between different method calls that users may make to your plugin.
  • The execute() method should return true if your plugin handles a particular action, and false otherwise. Note that this does indicate the success or failure of the handling.
  • Indicating success is failure is done by calling the appropriate method on the callbackContext. While our code only passes back a message for now, you can also pass a JSONObject or JSONArray if you need to return structured data.

Knowing that, we’re finally ready to implement the calendar functionality. The specific code needed to access the calendar is beyond the scope of this article, but the plugin plumbing code is still important. The method will look like this when completed:

private void getNextAppointment(int minutes, CallbackContext callbackContext) {
    if (minutes > 0) {
        /**
            Code to retrieve name, time of next appointment goes here
        **/
        if (foundAppointment) {
            JSONObject returnObject = new JSONObject();
            returnObject.put("title", appointmentTitle);
            returnObject.put("date", appointmentDate);
            callbackContext.success(returnObject);
        } else {
            // If no appointment was found, return an empty string.
            // Note that we used success() rather than error(), since
            // no finding an appointment is perfectly valid. Error
            // conditions should be reserved for situations where
            // the plugin was unable to complete its task at all.
            callbackContext.success("");
        }
    } else {
        callbackContext.error("minutes must be > 0");
    }
}

At this point, the plugin is ready to be consumed by a Cordova app.

IOS™

Adding the ios platform can also be done via plugman:

plugman platform add --platform_name ios

When the command completes, your folder structure should now look like this:

AmILate/
|- plugin.xml
|- src/
|  |- android/
|  |  \- AmILate.java
|  \- ios/
|     \- AmILate.m
\- www/
   \- AmILate.js

As well, plugin.xml will include these new lines:

<platform name="ios">
    <config-file parent="/*" target="config.xml">
        <feature name="AmILate">
            <param name="ios-package" value="AmILate" />
        </feature>
    </config-file>
    <source-file src="src/ios/AmILate.m" />
</platform>

Adding more source files to our plugin simply requires adding elements under the ios platform element in plugin.xml. Header files can be added in the same way using elements.

The final AmILate.m implementation, which illustrates the key plugin plumbing code, will look like this:

- (void)getNextAppointment:(CDVInvokedUrlCommand*)command
{
    CDVPluginResult* pluginResult = nil;
    int minutes = [[command.arguments objectAtIndex:0] intValue];

    if (minutes > 0) {
        /**
            Code to retrieve name, time of next appointment goes here
        **/
        if (foundAppointment) {
            NSMutableDictionary *appointment = [NSMutableDictionary dictionaryWithCapacity:2];
            [appointment setObject:appointmentName forKey:@"title"];
            [appointment setObject:appointmentDate forKey:@"date"];
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:appointment];
        } else {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@""];
        }
    } else {
        // Indicate an error result
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
    }

    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

Rather than using JSONObject/JSONArray, iOS allows plugins to return structured data by passing back an NSMutableDictionary. However, the basic structure is very similar to the android platform.

WINDOWS PHONE

The native code for Windows and Windows Phone 8.1+ is slightly different from other platforms. While it is possible to implement the functionality using C# or C++, the native APIs are actually available via JavaScript, and it is usually easiest that way.

Unfortunately, plugman does not currently support the windows platform, so the scaffolding previously created by plugman needs to be done by hand.

First, create a windows folder under the src folder, and then create an empty AmILate.js in it. Your folder structure should now look like this:

AmILate/
|- plugin.xml
|- src/
|  |- android/
|  |  \- AmILate.java
|  |- ios/
|  |  \- AmILate.m
|  \- windows/
|     \- AmILate.js
\- www/
   \- AmILate.js

Then add the following lines to plugin.xml, just below the closing tag for android:

<platform name="windows">
    <js-module src="src/windows/AmILate.js" name="AmILate">
        <runs target="" />
    </js-module>
</platform>

Next, add the following code to src/windows/AmILate.js:

module.exports.getNextAppointment = function(success, error, args) {
    if (args.length == 0 || args[0] < 0) {
        // Invalid call to the plugin, so return an error condition
        error('Invalid value for minutes argument');
        return;
    }

    /**
        Code to retrieve name, time of next appointment goes here
    **/

    if (foundAppointment) {
        result = {
                'title': appointmentTitle,
                'date' : appointmentDate
                };
        success(result);
    } else {
        // Empty string to indicate no appointment
        success('');
    }
}

Note how much simpler this was than the Java implementation. The callback methods are invoked directly, the json objects can be constructed in-place, and the arguments parameters can be accessed with sensible syntax, rather than complex method calls.

Step 5: Test the plugin

Step 6 (optional): Publish the plugin to NPM

Starting with Cordova version 5.0.0, plugins are published to and retrieved from NPM. This greatly simplifies the steps required to publish your plugin for use by others. Once your plugin is in a stable state, these steps will package and upload it to NPM.

First, use plugman to generate a package.json for your plugin:

plugman createpackagejson .

Answer the questions presented, and you will end up with a package.json that looks like this:

{
  "name": "AmILate",
  "version": "0.0.1",
  "description": "A plugin for determining if the user has an appointment coming up shortly",
  "cordova": {
    "id": "cordova-plugin-am-i-late",
    "platforms": [
      "android",
      "ios",
      "windows"
    ]
  },
  "keywords": [
    "ecosystem:cordova",
    "cordova-android",
    "cordova-ios",
    "cordova-windows"
  ],
  "author": "Microsoft",
  "license": "ISC"
}

If everything looks right, you are ready to publish! Just run the following command from a command prompt:

npm publish .