Sunday, 27 March 2016

Encrypted Storage Model

SSL/SSH protects data travelling from the client to the server: SSL/SSH does not protect persistent data stored in a database. SSL is an on-the-wire protocol.
Once an attacker gains access to your database directly (bypassing the webserver), stored sensitive data may be exposed or misused, unless the information is protected by the database itself. Encrypting the data is a good way to mitigate this threat, but very few databases offer this type of data encryption.
The easiest way to work around this problem is to first create your own encryption package, and then use it from within your PHP scripts. PHP can assist you in this with several extensions, such as Mcrypt and Mhash, covering a wide variety of encryption algorithms. The script encrypts the data before inserting it into the database, and decrypts it when retrieving. See the references for further examples of how encryption works.

Hashing ¶

In the case of truly hidden data, if its raw representation is not needed (i.e. will not be displayed), hashing should be taken into consideration. The well-known example for hashing is storing the cryptographic hash of a password in a database, instead of the password itself.
In PHP 5.5 or newer password functions provide convinient way to hash sensitive data and work with these hashes. In PHP 5.3.7+ »  password_compat library can also be used.
password_hash() is used to hash given string using strongest algorithm currently available and password_verify()checks whether given password matches the hash stored in database.
Example #1 Hashing password field
<?php
// storing password hash$query  sprintf("INSERT INTO users(name,pwd) VALUES('%s','%s');",
            
pg_escape_string($username),
            
password_hash($passwordPASSWORD_DEFAULT));$result pg_query($connection$query);
// querying if user submitted the right password$query sprintf("SELECT pwd FROM users WHERE name='%s';",
            
pg_escape_string($username));$row pg_fetch_assoc(pg_query($connection$query));

if (
$row && password_verify($password$row['pwd'])) {
    echo 
'Welcome, ' htmlspecialchars($username) . '!';
} else {
    echo 
'Authentication failed for ' htmlspecialchars($username) . '.';
}
?>
In older versions of PHP this can be achieved using crypt() function.
Example #2 Hashing password using crypt()s
<?php
// storing password hash
// $random_chars retrieved e.g. using /dev/random
$query  sprintf("INSERT INTO users(name,pwd) VALUES('%s','%s');",
            
pg_escape_string($username),
            
pg_escape_string(crypt($password'$2a$07$' $random_chars '$')));$result pg_query($connection$query);
// querying if user submitted the right password$query sprintf("SELECT pwd FROM users WHERE name='%s';",
            
pg_escape_string($username));$row pg_fetch_assoc(pg_query($connection$query));

if (
$row && crypt($password$row['pwd']) == $row['pwd']) {
    echo 
'Welcome, ' htmlspecialchars($username) . '!';
} else {
    echo 
'Authentication failed for ' htmlspecialchars($username) . '.';
}
?>

Designing Databases

The first step is always to create the database, unless you want to use one from a third party. When a database is created, it is assigned to an owner, who executed the creation statement. Usually, only the owner (or a superuser) can do anything with the objects in that database, and in order to allow other users to use it, privileges must be granted.
Applications should never connect to the database as its owner or a superuser, because these users can execute any query at will, for example, modifying the schema (e.g. dropping tables) or deleting its entire content.
You may create different database users for every aspect of your application with very limited rights to database objects. The most required privileges should be granted only, and avoid that the same user can interact with the database in different use cases. This means that if intruders gain access to your database using your applications credentials, they can only effect as many changes as your application can.
You are encouraged not to implement all the business logic in the web application (i.e. your script), instead do it in the database schema using views, triggers or rules. If the system evolves, new ports will be intended to open to the database, and you have to re-implement the logic in each separate database client. Over and above, triggers can be used to transparently and automatically handle fields, which often provides insight when debugging problems with your application or tracing back transactions.

SQL Injection

Many web developers are unaware of how SQL queries can be tampered with, and assume that an SQL query is a trusted command. It means that SQL queries are able to circumvent access controls, thereby bypassing standard authentication and authorization checks, and sometimes SQL queries even may allow access to host operating system level commands.
Direct SQL Command Injection is a technique where an attacker creates or alters existing SQL commands to expose hidden data, or to override valuable ones, or even to execute dangerous system level commands on the database host. This is accomplished by the application taking user input and combining it with static parameters to build an SQL query. The following examples are based on true stories, unfortunately.
Owing to the lack of input validation and connecting to the database on behalf of a superuser or the one who can create users, the attacker may create a superuser in your database.
Example #1 Splitting the result set into pages ... and making superusers (PostgreSQL)
<?php

$offset = $argv[0]; // beware, no input validation!
$query  = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
$result = pg_query($conn, $query);

?>
Normal users click on the 'next', 'prev' links where the $offset is encoded into the URL. The script expects that the incoming $offset is a decimal number. However, what if someone tries to break in by appending a urlencode()'d form of the following to the URL
0;
insert into pg_shadow(usename,usesysid,usesuper,usecatupd,passwd)
    select 'crack', usesysid, 't','t','crack'
    from pg_shadow where usename='postgres';
--
If it happened, then the script would present a superuser access to him. Note that 0; is to supply a valid offset to the original query and to terminate it.
Note:
It is common technique to force the SQL parser to ignore the rest of the query written by the developer with --which is the comment sign in SQL.
A feasible way to gain passwords is to circumvent your search result pages. The only thing the attacker needs to do is to see if there are any submitted variables used in SQL statements which are not handled properly. These filters can be set commonly in a preceding form to customize WHERE, ORDER BY, LIMIT and OFFSET clauses inSELECT statements. If your database supports the UNION construct, the attacker may try to append an entire query to the original one to list passwords from an arbitrary table. Using encrypted password fields is strongly encouraged.
Example #2 Listing out articles ... and some passwords (any database server)
<?php

$query  = "SELECT id, name, inserted, size FROM products
           WHERE size = '$size'";
$result = odbc_exec($conn, $query);

?>
The static part of the query can be combined with another SELECT statement which reveals all passwords:
'
union select '1', concat(uname||'-'||passwd) as name, '1971-01-01', '0' from usertable;
--
If this query (playing with the ' and --) were assigned to one of the variables used in $query, the query beast awakened.
SQL UPDATE's are also susceptible to attack. These queries are also threatened by chopping and appending an entirely new query to it. But the attacker might fiddle with the SET clause. In this case some schema information must be possessed to manipulate the query successfully. This can be acquired by examining the form variable names, or just simply brute forcing. There are not so many naming conventions for fields storing passwords or usernames.
Example #3 From resetting a password ... to gaining more privileges (any database server)
<?php
$query = "UPDATE usertable SET pwd='$pwd' WHERE uid='$uid';";
?>
But a malicious user sumbits the value ' or uid like'%admin% to $uid to change the admin's password, or simply sets $pwd to hehehe', trusted=100, admin='yes to gain more privileges. Then, the query will be twisted:
<?php

// $uid: ' or uid like '%admin%
$query = "UPDATE usertable SET pwd='...' WHERE uid='' or uid like '%admin%';";

// $pwd: hehehe', trusted=100, admin='yes
$query = "UPDATE usertable SET pwd='hehehe', trusted=100, admin='yes' WHERE
...;";

?>
A frightening example how operating system level commands can be accessed on some database hosts.
Example #4 Attacking the database hosts operating system (MSSQL Server)
<?php

$query  = "SELECT * FROM products WHERE id LIKE '%$prod%'";
$result = mssql_query($query);

?>
If attacker submits the value a%' exec master..xp_cmdshell 'net user test testpass /ADD' -- to $prod, then the$query will be:
<?php

$query  = "SELECT * FROM products
           WHERE id LIKE '%a%'
           exec master..xp_cmdshell 'net user test testpass /ADD' --%'";
$result = mssql_query($query);

?>
MSSQL Server executes the SQL statements in the batch including a command to add a new user to the local accounts database. If this application were running as sa and the MSSQLSERVER service is running with sufficient privileges, the attacker would now have an account with which to access this machine.
Note:
Some of the examples above is tied to a specific database server. This does not mean that a similar attack is impossible against other products. Your database server may be similarly vulnerable in another manner.
A worked example of the issues regarding SQL Injection
Image courtesy of » xkcd

Avoidance Techniques ¶

While it remains obvious that an attacker must possess at least some knowledge of the database architecture in order to conduct a successful attack, obtaining this information is often very simple. For example, if the database is part of an open source or other publicly-available software package with a default installation, this information is completely open and available. This information may also be divulged by closed-source code - even if it's encoded, obfuscated, or compiled - and even by your very own code through the display of error messages. Other methods include the user of common table and column names. For example, a login form that uses a 'users' table with column names 'id', 'username', and 'password'.
These attacks are mainly based on exploiting the code not being written with security in mind. Never trust any kind of input, especially that which comes from the client side, even though it comes from a select box, a hidden input field or a cookie. The first example shows that such a blameless query can cause disasters.
  • Never connect to the database as a superuser or as the database owner. Use always customized users with very limited privileges.
  • Use prepared statements with bound variables. They are provided by PDOby MySQLi and by other libraries.
  • Check if the given input has the expected data type. PHP has a wide range of input validating functions, from the simplest ones found in Variable Functions and in Character Type Functions (e.g. is_numeric()ctype_digit()respectively) and onwards to the Perl compatible Regular Expressions support.
  • If the application waits for numerical input, consider verifying data with ctype_digit(), or silently change its type using settype(), or use its numeric representation by sprintf().
    Example #5 A more secure way to compose a query for paging
    <?php

    settype($offset, 'integer');
    $query = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";

    // please note %d in the format string, using %s would be meaningless
    $query = sprintf("SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET %d;",
                     $offset);

    ?>
  • If the database layer doesn't support binding variables then quote each non numeric user supplied value that is passed to the database with the database-specific string escape function (e.g. mysql_real_escape_string(),sqlite_escape_string(), etc.). Generic functions like addslashes() are useful only in a very specific environment (e.g. MySQL in a single-byte character set with disabled NO_BACKSLASH_ESCAPES) so it is better to avoid them.
  • Do not print out any database specific information, especially about the schema, by fair means or foul. See also Error Reporting and Error Handling and Logging Functions.
  • You may use stored procedures and previously defined cursors to abstract data access so that users do not directly access tables or views, but this solution has another impacts.
Besides these, you benefit from logging queries either within your script or by the database itself, if it supports logging. Obviously, the logging is unable to prevent any harmful attempt, but it can be helpful to trace back which application has been circumvented. The log is not useful by itself, but through the information it contains. More detail is generally better than less

Easy Backtrack 5 Tutorial Designed For Total Beginners

When it comes to learning how to perform penetration testing with Backtrack 5, you probably know how tough it looks. Hopefully, with this Backtrack 5 Tutorial, we’re going to change that for you. What if you don’t even know what penetration testing is? Well, before we get started, we’re going to tell you. In a nutshell, penetration testing is a way for an individual (or company) to test the security of a network. It sounds a lot like hacking, doesn’t it? Don’t worry! It’s perfectly legal as long as you are using it with good intentions such as exploiting your own network and using the tool to make your network more secure.
Believe us when we say this, there is a big demand for this. After all, if you can get into a company’s network then that means that someone else probably can to. You’ll also hear of penetration testing referred to as ethical hacking or white hat hacking. Either way, it’s all the same. In the Backtrack 5 Tutorial below, we’re going to walk you through the 4 basic steps of penetration testing and teach you what you need to know in order to perform it yourself. Are you ready to get started? Great! Scroll down.

Step 1 – Surveillance

Before we get going with the actual penetration testing, we want to install a free program called “HTTrack” via the Backtrack 5 console. To do this, open Backtrack 5 and enter “sudo apt=get install httrack” and get ready for the next step. Once that’s done, go ahead and type in “httrack” into the console to pull it up. Now, in case you’re wondering, this program will allow us to index all of the pages on a given site before we start the actual penetration testing process. This means that you won’t have to be digging around through some site live and wasting precious time. You also don’t assume the risk of getting kicked off of the server before you get what you need. If that were to happen, you’d need to install this tool anyways so it’s best to play it safe and use it from the beginning.
Next, you will give your path a name (you can leave it blank if you want) and you will enter a website to copy. Once you do that and hit enter, you’ll be given a list of options. To copy the entire website, you’ll simply hit “1” on your keyboard. Give it a few minutes and you’ll have duplicates of the entire site’s contents downloaded.
There are also tools available for download that will let you repeat this process but for sub-domains and emails. We aren’t going to cover that here in this lesson but that’s because it is more of a convenience and isn’t completely necessary. With that being said, it’s about time we move on to Step 2!

Step 2 – Scan The Site

Step 2 forgetting hacking practice is also our favorite step. It’s the actual scanning process and quite frankly, it’s the least complicated step (or one of them). So, the first way to scan the site in question is with a Ping Sweep. To do this, you’ll want to enter the following code into the terminal and wait for the results.
The code: fping –a –g  123.12.12.1 321.32.21.1>hosts.txt
Now, in that code, you’ll notice something strange. There are random numbers in there. Okay, those are sample IP addresses. They aren’t real IP addresses to real sites so you’ll want to replace those with the IP address of a real site (the site you are performing penetration testing on). Essentially, what the Ping Sweet does is it sweeps and scans all the IP addresses from IP address A to IP address B. Make sense?
Once you have these results, we recommend running a vulnerability scan. To do this, enter this code:
“root@bt:~# apt-get install nessus”
Once you have this installed, you can run it by doing the following: Click Applications, Backtrack, Vulnerability Assessment, Vulnerability Scanner, Nessus, and finally, Nessus Start. Then, you wait.
Before you move on to Step 3, we have an additional recommendation that isn’t necessary but it will help. You can easily catalog both email addresses and sub-domains that are associated with the website in question as well with a simple, easy to use Python script called “The Harvester.” To get this on your Backtrack 5 system, you will simply need to type in the following code into your console to get going:
root@bt:~# cd /pentest/enumeration/theharvester
root@bt:~# ./the Harvester.py –d (your site here) -1 10 –b google.com
Now, you see where we entered Google’s web url? You can literally use any search engine that you want there whether it’s Yahoo, Bing, or MSN. Basically what this function does is searches a public resource (a search engine) for emails and sub-domains associated with the address you enter in the code above. Again, this isn’t necessary but it will give you additional information on the site and additional resources that will come in handy when it comes time to start the exploitation process. Now, ready to move on?

Step 3 – Exploit The Site In Question

Now we’re at the stage in the game where we’re going to attempt to exploit the site which is probably what most of you have been waiting for. In other words, it’s crunch time! So, the first thing that you need to do is ensure that you have Medusa installed. Backtrack 5 comes with Medusa pre-installed but just in case it isn’t, here is what you can do. Open your console and type “apt-get update.” Once you’ve done that then you’ll also want to type in “apt-get install medusa.” That should take care of it for you.
Now, before we move on, keep one thing in mind. Some networks will lock you out if you have too many guesses as to what the password is. In order to better your chances and hopefully avoid this, type in the following: /pentest/passwords/wordlists. This is basically a word list that you can use when you run the Medusa program to guess passwords. To get started, enter the code listed below to exploit the server.
“medusa –h target ip –u username –P path to password dictionary –M service to attack”
To make better sense of what you’re reading above, we’re going to explain it and break it down for you. The –h is used to target the IP of the site or its host (many people use Shared IP addresses now).
The –u is for usernames that will be used in attempts to log in. The –P is going to specify an entire list of possible passwords and the –M is going to be used to target a specific service that will be attacked. While this may sound pretty complicated to those of you who have never used Backtrack 5 and are coming to this tutorial with no experience whatsoever, it really isn’t that complicated. It will take a little practice but after a few attempts (hopefully you’re using your own website), you’ll get it down. Now, once you’ve messed with this some and have at least got familiar with it, move on to Step 4.

Step 4 – Compile Results

Now that you’ve went through the first 3 basic steps from Surveillance to Exploiting the Site, you’re ready to start compiling basic information and results. Were you able to access the server or website in question? Were you locked out because of too many password attempts? Were you able to get around that? These are all questions that you should ask yourself when using Backtrack 5. As mentioned above, this will take a little practice and some getting used to but it’s not a hard piece of software to master.
Best of all, it’s a very valuable piece of software that could potentially save you or your business a lot of money later on down the road. If you can access your own website or server with Backtrack 5 then that means you’re at high risk of being hacked. If you store credit card numbers or secretive information on your site, you definitely don’t want this to happen. While this is only a basic Backtrack 5 tutorial that just outlines the bare essentials of using the software, there is still a lot to learn. Whether you decide to seek outquality backtrack 5 lesson or learn yourself, you’ll find it to be a very rewarding, challenging, and technical experience. On top of that, you’ll also learn logical security practices that will enable you to keep your sites and networks safe from hackers. Now, what are you waiting for? It’s time to start mastering Backtrack 5 today!

Bonus Step

We know that we said we’d let you go but we wanted to give you a bonus step that you can use in order to ensure that you have the best Backtrack 5 experience possible. Not manypaid Backtrack 5 tutorials  are going to give you this information because it’s not something that many people think is that serious but we definitely do. What is it? Well, we recommend regularly updating Backtrack 5. Sometimes, you may find that you literally have to update your software multiple times a week but it’s well worth it. It’s also very easy. All you need to do is type in the following command: apt-get. From there, you’ll always have the latest updates to keep you in the know so you can always learn new wireless hacking and security info. Yep, that’s it! If that doesn’t work then you can always try a more in depth approach by typing the lengthy command below.
root@bt:~# apt-get update && apt-get upgrade && apt-get dist-upgrade
This will ensure that you have all the necessary updates and you’re ready to go the next time you use the software. Many people overlook this step but just like we said above, we think it’s a pretty serious step to take. The updates are absolutely free and there’s literally no good excuse not to take advantage of them. They could come in handy later on down the road and you never know what new updates that will be coming out for Backtrack 5. Since the updates are based on Ubuntu updates, you’ll find that they do come out pretty often. As mentioned above, you may want to do this multiple times a week but for the most part, these updates are quick.
So, with that being said, put in that command before each session of Backtrack 5. This may not get you the updates as soon as they come out but it will ensure that you’re up to date before you use the software. Sound simple enough? That’s because it most definitely is! Now, all that’s left to do is polish your skills, keep your software updated, and go get to work!