Creating TreeView For MVC 5 Using my open source TreeView component

Here, in this article, we’re going to extend JS Tree from JS to MVC and we’ll render the HTML tags from the database using custom development in the model.

Basically, we’ll create a sample DB that contains main/sub categories with self referencing; then we’ll add support for Razor like (@HTML.TreeView); and after, we’ll render the HTML tags (<ul> <li>) based on our relations in the database.

Let’s get started.

We will proceed with the following sections.

  1. Getting Started
  2. Creating the (Code First) model
  3. Creating TreeView Component
  4. Representing Data

Read the Full Article on Csharp Corner Including the Source files


Network Attacks

Network Attack Types

There are 2 types of  attacks in general, either they  are passive, meaning information is being screened and monitored ; other attacks are active, which means that the information is altered with the  intent to modify or destroy the data or the network itself.

Without protecting your computer and system, your data might be go under to an attack.

Your networks and data are vulnerable to any of these attacks if you have no protection and security plan:

1. Password-Based Attacks

Password-based access control is a common factor of most operating system and network security plans. This means your access rights to a computer and network resources are determined by your user name and your password.

Older applications do not always protect identity information as it is passed through the network for validation. This might allow an “eavesdropper” to gain access to the network by posing as a valid user.

2. Eavesdropping

In general, the majority of network communications occur in an unsecured or “clear text” format, which allows an attacker who has gained access to data paths in your network to “listen in” or interpret (read) the traffic.

When an attacker is eavesdropping on your communications, it is referred to as “sniffing” or “snooping”. In an enterprise, the ability of an eavesdropper to monitor the network is generally the biggest security problem that administrators face.

Without strong encryption services that are based on cryptography, your data can be read by others easily as it traverses the network.

3. Data Modification

After an attacker has seen and read your data, the next logical step he will most probably take is altering it.

An attacker can modify the data without the knowledge of the sender or receiver. Even if you do not require confidentiality for all communications, you do not want any of your messages to be modified in transit. For example, if you are exchanging purchase requisitions, you do not want the items, amounts, or billing information to be modified.

4. Identity Spoofing (IP Address Spoofing)

Most networks and operating systems use the IP address of a computer to identify a valid entity. In certain cases, it is possible for an IP address to be falsely assumed— identity spoofing. An attacker might also use special programs to construct IP packets that appear to originate from valid addresses inside the corporate intranet.

When an attacker gains access to the network with a valid IP address, he can modify, reroute, or delete your data and conduct other types of attacks.

When an attacker uses valid user account, the attacker acts as the real user. Therefore, if the user has administrator-level rights, the attacker also can create accounts for subsequent access at a later time.

An attacker can do any of the following after gaining access to your network:

• Modify, reroute, or delete your data.

• Obtain lists of valid user and computer names and network information.

• Modify access controls and routing tables.

• Changes server and network configurations.

5. Compromised-Key Attack

A key is a secret code or number that is needed to interpret secured information.

Although obtaining a key is a difficult and resource-intensive process for an attacker, it is possible.

After an attacker obtains a key, that key is referred to as a “compromised key”.

An attacker uses the compromised key to gain access and attack a secured communication channel without the sender or receiver being aware.

With the compromised key, the attacker can decrypt or modify data, and try to use the compromised key to compute additional keys, which might allow the attacker access to other secured communications.

6. Denial-of-Service Attack

The denial-of-service attack prevents normal use of your computer or network by valid users which is different from a password-based attack.

The attacker can do any of the following after gaining access to your network:

• Block the traffic, resulting in a loss of access to the network by authorized users.

• Send invalid data to applications or network services causing unexpected behavior of the applications or services.

• Flood a computer or the entire network with traffic until an overload happens causing shutdown.

• Randomize the attention of your internal Information Systems staff so that they do not see the intrusion immediately, which allows the attacker to make more attacks during the diversion.

7. Man-in-the-Middle Attack

A man-in-the-middle attack occurs when someone between you and the person with whom you are communicating is actively monitoring, capturing, and controlling your communication transparently.

When computers are communicating at low levels of the network layer, the computers might not be able to determine with whom they are exchanging data exactly.

For example, the attacker can re-route a data exchange.

Man-in-the-middle attacks are like someone assuming your identity in order to read your communications. The person on the other end may believe it is you because the attacker might be actively replying as you to keep the exchange going and get the desired information.

This attack is capable of the same damage as an application-layer attack.

8. Application-Layer Attack

An application-layer attack targets application servers by causing a fault in a server’s operating system or applications.

The attacker gains the ability to bypass normal access controls. The attacker takes advantage of this situation, gaining control of your application, system, or network, and can do the following:

• Read, add, delete, or modify your data or operating system.

• Introduce a sniffer program that analyzes your network and gains information that can be used to crash or to corrupt your network and systems.

• Introduce a virus program that uses your computers and software applications to copy viruses throughout your network.

• Disable other security controls to enable future attacks.

• Abnormally terminate your operating systems and data applications.

9. Sniffer Attack

A sniffer is an application or device that can read, monitor, and capture network data exchanges and read network packets.

A sniffer provides a full view of the data inside the packet.

Even If the packets are not encrypted, encapsulated packets can be broken open and read unless they are encrypted and the attacker does not have access to the key.

Using a sniffer, an attacker can do any of the following:

• Read your communications.

• Analyze your network and gain information to cause your network to crash and become corrupted.

Now this was the general interview about network attack types,

Let’s get started about how hackers or cyber criminals executes these attacks.

To simplify things, most of network attackers use a powerful tools to gain access the data on a network:

1.Metasploit Framework – an open source tool for exploit development and penetration testing Metasploit is well known in the security community. Metasploit has exploits for both server and client based attacks; with feature packed communication modules (meterpreter) that make pwning systems fun! The framework now includes Armitage for point and click network exploitation. This is the go to tool if you want to break into a network or computer system.

Defending against Metasploit:

  • Keep all software updated with the latest security patches.
  • Use strong passwords on all systems.
  • Deploy network services with secure configurations.

2.Ettercap – a suite of tools for man in the middle attacks (MITM). Once you have initiated a man in the middle attack with Ettercap use the modules and scripting capabilities to manipulate or inject traffic on the fly. Sniffing data and passwords are just the beginning; inject to exploit FTW!

Defending against Ettercap:

  • Understand that ARP poisoning is not difficult in a typical switched network.
  • Lock down network ports.
  • Use secure switch configurations and NAC if risk is sufficient.

3.sslstrip – using HTTPS makes people feel warm, fuzzy and secure. Using sslstrip this security can be attacked, reducing the connection to an unencrypted HTTP session, whereby all the traffic is readable. Banking details, passwords and emails from your boss all in the clear. Even includes a nifty feature where the favicon on the unencrypted connection is replaced with a padlock just to make the user keep that warm and fuzzy feeling.

Defending against sslstrip:

  • Be aware of the possibility of MITM attacks (arp, proxies / gateway, wireless).
  • Look for sudden protocol changes in browser bar. Not really a technical mitigation!

4.evilgrade – another man in the middle attack. Everyone knows that keeping software updated is the way to stay secure. This little utility fakes the upgrade and provides the user with a not so good update. Can exploit the upgrade functionality on around 63 pieces of software including Opera, Notepad++, VMware, Virtualbox, itunes, quicktime and winamp! It really whips the llamas ass!

Defending against evilgrade:

  • Be aware of the possibility of MITM attacks (arp attacks, proxy / gateway, wireless).
  • Only perform updates to your system or applications on a trusted network.

5.Social Engineer Toolkit – makes creating a social engineered client side attack way too easy. Creates the spear phish, sends the email and serves the malicious exploit. SET is the open source client side attack weapon of choice.

Defending against SET:

  • User awareness training around spear phishing attacks.
  • Strong Email and Web filtering controls.

6.sqlmap – SQL Injection is an attack vector that has been around for over 10 years. Yet it is still the easiest way to get dumps of entire databases of information. Sqlmap is not only a highly accurate tool for detecting sql injection; but also has the capability to dump information from the database and to even launch attacks that can result in operating system shell access on the vulnerable system.

Defending against sqlmap:

  • Filter all input on dynamic websites (secure the web applications).
  • Use mod_proxy or other web based filtering controls to help block malicious injection attacks (not ideal as often able to bypass these web application firewalls (WAF).

7.aircrack-ng – breaking holes in wireless networks for fun and profit. A suite of tools that enables all manner of wireless network attacks.

Defending against aircrack-ng:

  • Never use WEP
  • When using WPA2 with pre-shared keys, ensure passwords are strong (10+ characters non-dictionary based passwords).

8.oclHashcat – Need to get some passwords from the hashes you grabbed with sqlmap? Use this tool to bust them open. Over 48 different hashing algorithms supported. Will use the GPU (if supported) on your graphics card to find those hashes many times faster than your clunky old CPU.

Defending against oclHashcat:

  • Passwords are the weakest link. Enforce password complexity.
  • Protect the hashed passwords.
  • Salt the hashes.

9.ncrack – Brute force network passwords with this tool from Fyodor the creator of Nmap. Passwords are the weakest link and Ncrack makes it easy to brute force passwords for RDP, SSH, http(s), SMB, pop3(s), VNC, FTP, and telnet.

Defending against ncrack:

  • Use strong passwords everywhere.
  • Implement time based lockouts on network service password failures.

10.Cain and Abel – Cracking passwords, sniffing VOIP and Man in the Middle (MITM) attacks against RDP are just a few examples of the many features of this Windows only tool.

Defending against Cain and Abel:

  • Be aware of the possibility of MITM attacks (arp attacks, untrusted proxy / gateway, wireless).
  • Use strong passwords everywhere.

11.Tor – push your traffic through this onion network that is designed to provide anonymity to the user. Note your traffic from the exit node is not encrypted or secured. Make sure you understand what it does before using it, Tor provides anonymity not encrypted communication.

Breaking down whatsapp encryption EXPLOIT

Breaking Down Whatsapp encryption EXPOIT.

In this article am going to explain in depth how you can decrypt Whatsapp messages.

First let’s talk about how Whatsapp store messages into your mobile device:

Your chats are being saved on your phone and not on the Whatsapp server. The only moment Whatsapp saves your message is the moment you send it. The message is being saved on Whatsapp servers until it can be delivered to the recieving phone. This might take a while when that phone is out reach of internet or is turned off.

If the message is on the Whatsapp server for more than 30 days it will be deleted from the server.

And Whatsapp store the messages inside (SD card>Whatsapp>Database folder)

msgstore.db.crypt12 -> this file contains all of your messages but it’s encrypted 🙂

Let’s get started into the fun stuff:

You can decrypt WhatsApp message backup file i.e. msgstore.db.crypt12. You can also decrypt the previous backup file with format crypt7, crypt5 etc….

Database file with name msgstore.db.crypt12. You can find this file in your Device storage.

Path:  Device Storage/WhatsApp/Databases/msgstore.db.crypt12

It is required to root your phone to find key otherwise you will get empty folder.

Key: Key file contains a decryption key which is essential to decrypt an encrypted file. Since WhatsApp saves this key in your system storage so you can find that file on following location. To open system folder you can use ES File Explorer. ES File Explorer File Manager – Android Apps on Google Play

WhatsApp backup conversation files are now saved with the .crypt12 extension. From crypt9, they seem to be using a modified version of Spongy Castle – a cryptography API library for Android.

All the findings below are based on reverse engineering work done on WhatCrypt and Omni-Crypt. I would like to highlight that IGLogger proved to be a very useful tool when it came to smali code debugging.

Extract Key File

To decrypt the crypt12 files, you will first need the key file. The key file stores the encryption key, K. WhatsApp stores the key file in a secure location: /data/data/com.whatsapp/files/key.

If your phone is rooted, extracting this file is easy. If your phone is not rooted, refer to instructions from WhatCrypt and Omni-Crypt for details on extracting the key file. The idea is to install an older version of WhatsApp, where Android ADB backup was still working and extract the key file from the backup.

Extract crypt12 Backup File

Pull the encrypted WhatsApp messages file from your phone using ADB.

$ adb pull /sdcard/WhatsApp/Databases/msgstore.db.crypt12

Decryption Keys

This section is just for your information and you can skip this section.

The encryption method being used is AES with a key (K) length of 256 bits and an initialization vector (IV) size of 128 bits. The 256-bit AES key is saved from offset 0x7E till 0x9D in the file. Offsets start from 0x00. You can extract the AES key with hexdump and assign the value to variable $k.

$ k=$(hexdump -ve '2/1 "%02x"' key | cut -b 253-316)

The $k variable will hold a 64-digit hexadecimal value in ASCII that is actually 256 bits in length.

The IV or the initialisation vector is saved from offset 0x33 till 0x42 in the crypt12 file. The IV value will be different for every crypt12 file.

$ iv=$(hexdump -n 67 -ve '2/1 "%02x"' msgstore.db.crypt12 | cut -b 103-134)

The K and IV extraction method is similar to what we have done for crypt8 files before.

Strip Header / Footer in crypt12 File

Again, this section is just for your information and you can skip this section.

Before we start the decryption process, we will need to strip the 67 byte header and 20 byte footer from the crypt12 file.

$ dd if=msgstore.db.crypt12 of=msgstore.db.crypt12.enc ibs=67 skip=1

$ truncate -s -20 msgstore.db.crypt12.enc

The above dd command will strip the the first 67 bytes from the crypt12 file and save it to a file with extension crypt12.enc. The truncate command will strip the last 20 bytes from the crypt12 file.

Decrypt THE crypt12 File

As the WhatsApp AES cryptography API library seems to be a modified version, we will no longer be able to use openssl to decrypt the crypt12 file. I have yet to determine what has been modified.

To decrypt crypt12 files, I have written a simple Java program that will use the modified cryptography API library instead. For the cryptography API library, I have extracted the modified Spongy Castle cryptography class files from the Omni-Crypt APK file using dex2jar. You can find the Java program and crypto library over here at GitHub.

The Java program will create 3 output files:

  • msgstore.db.crypt12.enc – encrypted file with header and footer stripped.
  • msgstore.db.zlib – decrypted file in zlib format.
  • msgstore.db – decrypted sqlite3 database file.

Below is how you can compile and run the Java program.

$ git clone
$ cd WhatsappDecryption/
$ javac -classpath "lib/whatsapp_spongycastle.jar:."
$ cp ../ .
$ cp ../ .
$ java -cp "lib/whatsapp_spongycastle.jar:." WTDecrypt



creating encrypted file with header/footer stripped: msgstore.db.crypt12.enc

creating zlib output file: msgstore.db.zlib

creating sqlite3 output file: msgstore.db

$ ls -l

total 136724

-rw-r--r-- 1 Jameel ************* WTDecrypt.class

-rw-r--r-- 1 Jameel *************

-rw-r--r-- 1 Jameel ************* key

drwxr-xr-x 2 Jameel ************* lib

-rw-r--r-- 1 Jameel ************* LICENSE

-rw-r--r-- 1 Jameel ************* msgstore.db

-rw-r--r-- 1 Jameel ************* msgstore.db.crypt12

-rw-r--r-- 1 Jameel *************  msgstore.db.crypt12.enc

-rw-r--r-- 1 Jameel ************* msgstore.db.zlib

-rw-r--r-- 1 Jameel *************

$ file *

WTDecrypt.class:           compiled Java class data, version 52.0 (Java 1.8)            C source, ASCII text

key:                     Java serialization data, version 5

lib:                     directory

msgstore.db:             SQLite 3.x database, user version 1

msgstore.db.crypt12:     raw G3 data, byte-padded

msgstore.db.crypt12.enc: data

msgstore.db.zlib:        zlib compressed data

Final Words

To use the Java decryption tool, you will need to use OpenJDK. Oracle require JCE Provider libraries to be signed. OpenJDK does not have this requirement. If you try running the Java program on Oracle JDK, you will most likely get the following exception.


Have fun 🙂

WordPress security

The most popular and widely used blogging platform is WordPress .

It supports websites ranging from a simple blog to a full-featured business website.

Nearly twenty-six percent of all websites globally use WordPress. As a result of this, hackers and spammers interest in breaking the security of WP-operated sites has risen.

This post will offer you some of the best WordPress security plugins that can help reduce the risk of your website being hacked. These security plugins offer several options to make your WordPress blog secure from known vulnerabilities. It contains plugins for access control, login security, spam protection, content theft protection, backup tools, file integrity monitoring, email protection, firewall and much more.

Here is a list of some of the top security plugins that can be used to keep your WordPress site secured:


WordFence is one of the most popular WordPress security plugins. It covers login security, IP blocking, security scanning, and WordPress firewall and monitoring.

WordFence starts by checking if the site is already infected. It does a deep server scan of the site’s source code and compares it to the Official WordPress repository for core, themes and plugins.

The plugin is great for beginners and pro users alike.

You can also try the premium version of this plugin If you want to secure your website with some more features, which includes country blocking, two-step authentication, scheduled scanning and more.


iThemes Security is a WordPress security plugin that claims to provide more than 30 ways to secure and protect your WordPress website from attacks

It strengthens user credentials by fixing common vulnerabilities and automated attacks. The plugin is available in both free and premium versions.

iThemes includes all of the following:

  • Two-factor authentication
  • Brute force protection
  • Monitoring core files for any changes
  • Locking out users for multiple incorrect credential attempts
  • Forcing the use of secure passwords for specific user roles and file permissions
  • Logging user actions
  • Ticketed support (for pro users)




Sucuri offers a free plugin that is available in the WordPress repository.

This plugin offers various security features like:

  • Malware scanning
  • Security activity auditing
  • Blacklist monitoring
  • Effective security hardening
  • File integrity monitoring
  • Website firewall.

It is a security suite meant to complement your existing security posture.

The Sucuri plugin tracks all activities on your site.

This includes when users log in or when changes are made to your site. This way, if there is a breach in security, you’ll be able to review the activity logs and find out what happened.


“All In One WP Security & Firewall” is also among the most popular WordPress security plugins.

For those who are not familiar with advanced security settings, it has a user-friendly interface. This plugin protects your website by checking vulnerabilities and implementing the latest techniques and security measures.

A useful feature of “All in One WP Security & Firewall” is a meter on your dashboard that gives your site a score of how secure it is. By adding additional security options, you can increase your score.

It also has a security scanner that keeps track of files and notifies you about each change in your WordPress system. It can also detect malicious code in your WordPress website.


BulletProof Security is another popular plugin that helps to secure your WordPress website is. This plugin provides a single click security solution. It secures your website against RFI, XSS, CRLF, SQL injection, and code injection hackings.

Here are a few features that are part of a long list:

  • An easy single-click setup
    • A record of the number of login attempts
    • File monitoring and quarantining of uploaded files
    • Email alerts for a variety of user actions
    • Alerts when suspected malicious activity affects your site

It also has a pro version that offers some advanced features to improve the security of your website.


As a quick advice, with an increasing number of hacking attacks, it is necessary to have security in your WordPress website. The security plugins mentioned above will help you with that. For users who don’t code a lot, plugins are the best ways to secure your blog. Most of them are free, safe and easily usable.

Hope this information has given you a valuable insight on how to protect your website with the available tools and plugins.

How to configure burp suite for web application penetration testing

Burp Suite is an integrated platform for performing security testing of web applications. Its various tools work seamlessly together to support the entire testing process, from initial mapping and analysis of an application’s attack surface, through to finding and exploiting security vulnerabilities.
Burp Suite allows you to combine manual and automated techniques to enumerate, analyses, scan, attack and exploit web applications. The various Burp tools work together effectively to share information and allow findings identified within one tool to form the basis of an attack using another.
BurpSuite allow us to forward all of the web traffic from your browser through BurpSuite so that you can see each HTTP Request and Response and manipulate it to your heart’s content. We will configure burp suite with firefox or Iceweasel in Kali Linux or Backtrack.

Let’s get started into the steps of configuring Burp Suite:

1. Open Firefox or Iceweasel and Click on Edit then Preference

2. Preference Window will be open Now go to Advance → Network → Setting  2

3. Select Manual Proxy then write localhost or in HTTP Proxy area and port should be 8080. Use this proxy server for all protocols by checking the box. Clear the No Proxy field then Finally Click OK.

4. Now open burp suite
    A. GUI Method
         Application → Kali Linux → Web Application → Web Vulnerability Scanners → burpsuite
B. Open Terminal and type burpsuite.jar and Press Enter
  1. If you are running burpsuite first time in your Kali Linux you will see this window Click on I Accept.


6. Burp Suit has been opened. Now Click on Proxy Tab then Click on Option Subtab and watch carefully local host interface running box should be check in Proxy Listeners.

7. Scroll down in the same tab (Proxy Tab → Option subtab)
Intercept Client Requests
    → Select URL Match type and keep Clicking UP button till URL Match type reach at the top.
    → Check Box ‘Intercept requests based on the following rules.’
  1. As we can see URL match type now at the top. Now select ‘File Extension’ and click on Edit.


9. Edit Window will be open. Here we will add ‘jpeg’ file extension. You can add or remove file extension as per your need. So, Write code and click on OK.
10. Scroll Down in the same tab (Proxy Tab → Option subtab)
Intercept Client Responses
       → Check Box ‘Intercept Responses based on the following rules.’
       → Select URL Match type and keep Clicking UP button till URL Match type reach at the top.


  1. Click on Add – we are going to add a new rule.


12. We will Add file extension match type according to below details:
      Boolean Operator : And
      Match type : File Extension
      Match relationship : Does not match
      Match condition: (^gif$|^jpg$|^png$|^css$|^js$|^ico$|^jpeg$)


  1. Select ‘File extension’  and keep Clicking UP button till ‘File extension’ reach at the 2nd top.


  1. We have organized it.


15. Now Open Your Firefox or Iceweasel and write in the web address area. You may see a message ‘This Connection is Untrusted’ if you’re using Google over HTTPS.
You can add an exception everytime this happens when you’re using a proxy, but that can be irritating. We can also set Firefox or Iceweasel to trust the burp certificate so that we don’t get this error.The Pro version of burp allows us to get the certificate easily, but in the free version we have to do little work. You can browse any https enable website for doing this. After opening https enable website Click on ‘I Understand the Risks


16. Click on Add Exception…


17. Click on View


  1. Click on Details Tab, Select PortSwigger CA then Click on Export.


  1. Choose Your Save location, (must remember the location where you are saving your certificate.) Click on Save.


  1. Open Your Browser Click on Edit then Click on Preferences.


  1. Click on Advance Tab then Click on Encryption Subtab and Click on View Certificates.


  1. Click on Authorities Tab then Click on Import.


23. Find the location where you saved your PortSwiggerCA. If you are unable to view saved file from the location, change your file type as ‘All File’. Select your PortSwiggerCA and Open It.

  1. A new window will appear, Check box ‘Trust this CA to identity websites’ then Click on OK.


  1. If you will scroll down your Certificates Name You will Notice your Added Certificate there. Click OK. Now, you should be able to navigate to any SSL site in burp without being prompted to trust the certificate.


26. Here we want to make is to disable Google Safebrowsing. Safebrowsing is enabled for a reason but it can cause unwanted traffic during tests so we will disable it. Go to Security Tab and uncheck two boxes ‘Block Reported Attack sites’ and ‘Block Reported web forgeries’ Click Close

That’s it 🙂

PHP and MySQL: Secure coding

php mysql secure coding

With all the languages out there used by websites, one of the most dynamic ones is PHP, mostly used in websites such as Amazon, Wikipedia, and Facebook.

PHP is very popular to use, generally because it is easy to learn, easy to install and does not require the user to write code.

Yet, in spite of PHP’s popularity, security is not a very popular issue among its users.

For this reason, in order to make your PHP apps more secure, I will be explaining how you can do that.

One of the solutions is creating a PHP web app that connects to a MySQL back end database.

This will create a layered security structure.

There is no definite method of blocking attacks, but using the layered security concept, we can limit our exposure to them.

Two of the attacks we will lessen are SQL Injection (SQLi) and Cross Site Scripting (XSS). Both of these attacks are performed by taking advantage of applications that do not properly handle user input.


XSS happens when an application sends the users browser back input that has not been checked for code. If an attacker were to enter something similar to the text below in a form field, it would cause the browser to execute the code and create a pop up on the screen displaying the text “XSS”.


Similarly SQLi is caused by an attacker running unplanned SQL code against the database. An example would be if an attacker were to enter the following in a form, the browser would display all the data in the user table:

;select * from users;

I will use PHP built-in methods such as htmlspecialchars(), mysqli_real_escape_strings() and use prepared statements to help prevent the attacks mentioned above.

In this training contact  list app example , the database will store the following fields:

  • First Name
  • Last Name
  • email address



As a privileged user I ran the following code to create the is attached at the end of this post as createdb.sql.

mysql -uroot -p -h mysql

CREATE DATABASE `contactsSchema` ;
USE contactsSchema;
CREATE TABLE `contactsTable` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `first` VARCHAR(40) DEFAULT NULL,
    `last` VARCHAR(64) DEFAULT NULL,
    `email` VARCHAR(256) DEFAULT NULL
    PRIMARY KEY (`id`)
CREATE USER 'contactsUser'@'localhost' identified by 'superSecretPassword';
    ON contactsSchema.contactsTable TO 'contactsUser'@'localhost';

INSERT INTO contactsTable (id, first, last, email)
values(null, 'Alexander', 'Bell', '');

For the application, I will drop the authenticated login functionality that will be discussed in a later post .

In the PHP page, which is attached at the bottom as index.php, you will see some  PHP code that makes this contacts app more secure.

1. strip_tags()

#User passed in vars
isset ( $_REQUEST['i'] ) ? $i = strip_tags($_REQUEST['i']) : $i = "";
isset ( $_REQUEST['s'] ) ? $s = strip_tags($_REQUEST['s']) : $s = "";

I am only allowing variables from the user that I am specifying. Next I am running strip_tags() on them to remove any html tags in the text. This however does not get all extra characters.

2. mysqli_real_escape_string()

$first=mysqli_real_escape_string($db, $first);

In the above code snippet, the mysqli_real_escape_string() method is used to escape any special characters.
This is used as the variable is provided by the user. Anything the user enters should be sanitized.
However mysqli_real_escape_string() does not protect against all threats.

3. Prepared Statement

if ($stmt = mysqli_prepare($db,
 "INSERT INTO contactsTable SET first=?, last=?, email=?, id=''")) {

               mysqli_stmt_bind_param($stmt, "sss", $first, $last, $email);

In this code we are using prepared statements to limit the functionality of the query.
In this example, I am only passing in variables to execute in this query,
it prevents nested queries, which are a common SQLi attack.


4. htmlspecialchars()

function displayResults($first, $last, $email) {

       echo "&lt;tr&gt; &lt;td&gt;" . htmlspecialchars($first)  . "&lt;/td&gt;";
       echo "&lt;td&gt;" . htmlspecialchars($last)  . "&lt;/td&gt;";
       echo "&lt;td&gt;" . htmlspecialchars($email)  . "&lt;/td&gt;&lt;/tr&gt;";

In the above example, I am disabling code that may be stored in the database or passed in by the end user from being rendered as executable html in the browser. The command htmlspecialchars() replaces characters like < with markup equivalent such as &LT;.


In this example application, I have applied multiple layers of security to prevent attacks such as cross site scripting and SQL injection. Clearly this is a simple application, but the code is reusable and you can build on it when you create your own applications.

Code Examples Used in Writeup:


CREATE DATABASE `contactsSchema` ;
USE contactsSchema;
CREATE TABLE `contactsTable` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `first` VARCHAR(40) DEFAULT NULL,
    `last` VARCHAR(64) DEFAULT NULL,
    `email` VARCHAR(256) DEFAULT NULL
    PRIMARY KEY (`id`)
CREATE USER 'contactsUser'@'localhost' identified by 'superSecretPassword';
    ON contactsSchema.contactsTable TO 'contactsUser'@'localhost';

INSERT INTO contactsTable (id, first, last, email)
values(null, 'Alexander', 'Bell', '');


//file: index.php 
//purpose: example contact list
//version: 1.0 
//date: 2012/08/30
#User passed in var run strip tags on input
isset ( $_REQUEST['i'] ) ? $i = strip_tags($_REQUEST['i']) : $i = "";
isset ( $_REQUEST['s'] ) ? $s = strip_tags($_REQUEST['s']) : $s = "";
isset ( $_REQUEST['st'] ) ? $st = strip_tags($_REQUEST['st']) : $st = "";
isset ( $_REQUEST['first'] ) ? $first = strip_tags($_REQUEST['first']) : $first = "";
isset ( $_REQUEST['last'] ) ? $last = strip_tags($_REQUEST['last']) : $last = "";
isset ( $_REQUEST['email'] ) ? $email = strip_tags($_REQUEST['email']) : $email = "";

#Database Connection 
function connectDB(&amp;$db){
 $db = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
 if (mysqli_connect_errno()) {
 print "&lt;br&gt; Houston we have a problem! &lt;br&gt;
 There seems to be an error connecting to the MySQL Database. 
 &lt;br&gt; The error we hit was: &lt;br&gt; " . htmlspecialchars(mysqli_connect_error()) .
 "&lt;br&gt; error code " . htmlspecialchars(mysql_errno());
//Add new entries to DB
function addContact($db, $first, $last, $email) { 
 $first=mysqli_real_escape_string($db, $first);
 $last=mysqli_real_escape_string($db, $last);
 $email=mysqli_real_escape_string($db, $email);
 if ($stmt = mysqli_prepare($db, "INSERT INTO contactsTable SET first=?, last=?, email=?, id=''")) {
 mysqli_stmt_bind_param($stmt, "sss", $first, $last, $email); 
 } else {
 echo "Error Adding Contact";
//Table Header 
function resultTableHeader() {
 echo "&lt;table width=60%&gt;
 &lt;tr&gt; &lt;td bgcolor=#D8D8D8 width=30%&gt; &lt;b&gt;&lt;u&gt; First &lt;/b&gt; &lt;/u&gt; &lt;/td&gt;
 &lt;td bgcolor=#D8D8D8 width=30%&gt; &lt;b&gt;&lt;u&gt; Last &lt;/b&gt; &lt;/u&gt; &lt;/td&gt; 
 &lt;td bgcolor=#D8D8D8 width=40%&gt; &lt;b&gt;&lt;u&gt; eMail &lt;/b&gt; &lt;/u&gt; &lt;/td&gt; &lt;/tr&gt;";
//Results Display
function displayResults($first, $last, $email) {
 echo "&lt;tr&gt; &lt;td&gt;" . htmlspecialchars($first) . "&lt;/td&gt;";
 echo "&lt;td&gt;" . htmlspecialchars($last) . "&lt;/td&gt;";
 echo "&lt;td&gt;" . htmlspecialchars($email) . "&lt;/td&gt;&lt;/tr&gt;";
//Coonect to the DB to begin
echo "
&lt;title&gt; Contacts &lt;/title&gt; 
&lt;h3&gt; Contact List &lt;/h3&gt;
&lt;table width=60%&gt; 
 &lt;td bgcolor=#D8D8D8 width=30%&gt; &lt;a href=index.php?s=1&gt;Add New &lt;/a&gt; &lt;/td&gt;
 &lt;td bgcolor=#D8D8D8 width=30%&gt; &lt;a href=index.php?s=2&gt;Search&lt;/a&gt; &lt;/td&gt;
 &lt;td bgcolor=#D8D8D8 width=40%&gt; &lt;a href=index.php&gt;Back&lt;/a&gt; &lt;/td&gt;
if ($s == Null) { //If no options, just query the whole table
 $query="SELECT first, last, email FROM contactsTable"; 
 $result=mysqli_query($db, $query); 
 while($row=mysqli_fetch_row($result)) {
 displayResults($row[0], $row[1], $row[2]);
 echo "&lt;/table&gt;";
}elseif ($s == 1) { //Add new entry
 if ($first == Null) { //If we don't have user input yet
 echo "&lt;form method=post action="index.php"&gt; ";
 echo " 
 &lt;td&gt; &lt;input type=text name="first" value=""&gt;&lt;/input&gt; &lt;/td&gt; 
 &lt;td&gt; &lt;input type=text name="last" value=""&gt;&lt;/input&gt; &lt;/td&gt; 
 &lt;td&gt; &lt;input type=text name="email" value=""&gt;&lt;/input&gt; &lt;/td&gt; 
 &lt;tr&gt; &lt;td colspan=3 align=center&gt;&lt;input type=hidden name="s" value="1"&gt;
 &lt;input type=submit name="Submit" value="Submit"&gt; &lt;/td &lt;/tr&gt;

 } elseif ($first != Null) {
 addContact($db, $first, $last, $email) ;
 echo "Added new Entry &lt;br&gt;" . 
 htmlspecialchars($first) . "&lt;br&gt;" .
 htmlspecialchars($last) . "&lt;br&gt;" . 
 htmlspecialchars($email) . "&lt;br&gt;";
}elseif( $s == 2) {
 if ($st == Null) { 
 echo "Enter Search Term: 
 &lt;form method=post action="index.php"&gt;
 &lt;input type=text name="st" value=""&gt; 
 &lt;input type=hidden name="s" value="2"&gt;
 &lt;input type=submit value="Submit" name="Submit"&gt; 
 &lt;/form&gt;" ;
 } else { 
 $st=mysqli_real_escape_string($db, $st);
 if ($stmt = mysqli_prepare($db, "SELECT first, last, email FROM contactsTable WHERE 
 first LIKE CONCAT('%', ? ,'%') or
 last LIKE CONCAT('%', ? ,'%') or
 email LIKE CONCAT('%', ? ,'%')")){
 mysqli_stmt_bind_param($stmt, "sss", $st, $st, $st); 
 mysqli_stmt_bind_result($stmt, $first, $last, $email);
 while(mysqli_stmt_fetch($stmt)) {
 displayResults($first, $last, $email);
 echo "&lt;/table&gt; ";
echo " 

Hello World

Am glad to share my experiences :),

I just finished coding my website and you welcome guys in my blog,

Here you’ll find in depth information about penetration testing and programming.