Archive for the ‘Uni Work’ Category

ASP.NET Database connection strings in web.config

Sunday, May 17th, 2009

The Connection string contains sensitive data like username, password, IP address of the server. When we place this sensitive data in an .aspx file for a web application or visual basic or C# files, we run the risk of exposing this data to a hacker.

So, we place this code in the web configuration file. Configuration files are used to store information about application settings.

These files are also referred to as Application Configuration Files and provide security to the data contained in them.

We place the connection string in App.config file for windows applications and web.config file for web applications.
-web.config is created automatically by VS.NET when you create any web project.

-When you compile the web application, web.config is NOT renamed or copied to the BIN folder.

-web.config has several default entries in it to support web/IIS configuration & security.

-You can add the <appSettings>section in the web.config and add your key/value pairs in that section.

-You can have separate web.config files for each directory in your web application, in addition to the one in the root. For each web page, by default, system will look for a web.config in the same folder as the page and if not found, then looks in the parent folder. The web.config file with the connection string will have the following content.

  < ?xml version="1.0"?>
  < configuration>
	< appSettings>
		< add key="DatabasePath"
		  value="server=localhost;
		database=FinAccounting;
		Integrated Security=true;"/>
	< /appSettings>
  < /configuration>

For the web.config file to be read, place the following code in your web application as shown below.

  Imports System.Configuration
  Imports System.Data.SqlClient

  Partial Class _Default
    Inherits System.Web.UI.Page

    Dim dbpath As String
	 = ConfigurationSettings.AppSettings("DatabasePath")
    Dim str_sql_user_select As String
	 = "SELECT * FROM AccountsTable"
    Dim comUserSelect As SqlCommand
    Dim myreader As SqlDataReader

    Protected Sub Page_Load
	(ByVal sender As Object, ByVal e As System.EventArgs)
	  Handles Me.Load

        Dim myConnection As SqlConnection
		 = New SqlConnection(dbpath)
        comUserSelect = New
		 SqlCommand(str_sql_user_select, myConnection)
        TextBox1.Text = ""
        TextBox2.Text = ""
        myConnection.Open()
        myreader = comUserSelect.ExecuteReader
        If (myreader.Read = True) Then
            TextBox1.Text = myreader(0)
            TextBox2.Text = myreader(1)
        Else
            MsgBox("You have reached eof")
        End If

    End Sub
  End Class

PHP Login and password hashing.

Friday, February 13th, 2009

PHP Login and password hashing.

If you build websites that require users to register it’s your responsibility to keep their passwords safe. And if you’re storing the passwords in plain text then you’re not doing your job properly. What happens if your database is stolen? It’s not just your site that is compromised. Since most users use the same password on multiple sites, all those sites have also been compromised.

No data is entirely secure, and if anyone else has access to your webserver (the company managing the server for you?) or your database (the company storing the backups?) then you don’t have total control over the security anyway. So there’s always a chance your database could be stolen. So, the simple rule is to hash your passwords.

Hashing

A hash is a string derived from the original password via a one-way algorithm. In other words, it’s easy to create the hash from the original, but harder (when used for security, ideally impossible) to create the original from the hash. You store the hash in the database, and when the user signs-in you hash the password they sign-in with and compare it to the hash in the database. Something like this

$userPasswordHash == sha1( $_POST['password'] )

That way, you never store the user’s password.

There are a number of hashing algorithms in PHP, of which md5 and sha1 are the most commonly used. Unfortunately, neither is as secure as they were once thought to be. It would be better to use a more secure hash, and if you have the Hash engine in your PHP installation (included by default since PHP 5.1.2) then you have access to many more algorithms. So a better example would be

The Code Bit

 $userPassWordhash == hash( 'whirlpool', $_POST['password'] )

To see a full lis of hashing algorithms in PHP use this code:

<?PHP
$algos = hash_algos();
$word="hash me!";

foreach($algos as $algo)
{
    echo "Algorithm: ".$algo.": "."<br>";
    echo "Hash: ".hash($algo, $word)."<br>";
    echo "String Length: ".strlen(hash($algo, $word))."<br>";
    echo "<hr>";
}
?>

Sample output:

Algorithm: md5:
Hash: 88a568e86f4ffbb458bb4ebfe3df6e2e
String Length: 32
Algorithm: sha1:
Hash: 0195580447ce25847a2954422de4b5f7d01bc143
String Length: 40
Algorithm: whirlpool:
Hash: a4718a7a9ec6eb2bb8b4813961fd8ab0104a23a3f3ec677
4117dd67b8665a27eaea998bc85b69cfb74ac2cdb49a92b
f36d9beb22ece6fd934b315e40267195d7
String Length: 128

How to use the in checking password script:

<?php
session_start();
//connect to server and select database
//Host , User, Password, Database Name
$mysqli = mysqli_connect("localhost", "user", "dbpassword", "dbname");

$username = stripslashes(trim($_POST["username"]));
$password = stripslashes(hash('whirlpool',$_POST[password]));

//create and issue the query
$sql = "SELECT username FROM users WHERE username = '".$username."' AND password = '".$password."'";
$result = mysqli_query($mysqli, $sql) or die(mysqli_error($mysqli));
.
.
.
?>

Rainbow tables

But there’s another problem. Once your database is stolen, the thief has plenty of time to crack the passwords using a simple Rainbow Table attack. This involves creating a large selection of hashes based on likely passwords (e.g. every word in the dictionary) and then comparing the hashes with the hashes in your database. Within an day or so, half the passwords in your database will probably have been cracked.

To prevent this you should salt each password by adding a random string to it (called a salt or nonce). The time consuming part of a rainbow table attack is building the dictionary of hashes. Adding a random salt to the password means the thief has to build a whole new dictionary of hashes for each salt, making a rainbow table attack too time consuming to be viable. Each password should have a different salt, and the salt doesn’t even need to be secret.

The Code bit

The code below demonstrate hone way you can add salt to a password hash. Copy code between <?php … ?> tags to paste in to a new php file to try.

<?php
// get a new salt - 8 hexadecimal characters long
// current PHP installations should not exceed 8 characters
// on dechex( mt_rand() )
// but we future proof it anyway with substr()
function getPasswordSalt()
{
    return substr( str_pad( dechex( mt_rand() ), 8, '0', STR_PAD_LEFT ), -8 );
}
// calculate the hash from a salt and a password
function getSaltedPasswordHash( $salt, $password )
{
    return $salt . ( hash( 'whirlpool', $salt.$password.$salt ) );
}

$salt = getPasswordSalt();
$password="Hash me!";
$standardHash = hash('whirlpool',$password);
$saltedHash=getSaltedPasswordHash( $salt, $password );

echo "Password: ".$password."<br/>";
echo "Salt: ".$salt."<br/>";

echo "Standard Hash: ".$standardHash."<br/>";
echo " Salted Hash : ".$saltedHash."<br/>";

?>

So, for secure passwords use

// get a new salt - 8 hexadecimal characters long
// current PHP installations should not exceed 8 characters
// on dechex( mt_rand() )
// but we future proof it anyway with substr()
function getPasswordSalt()
{
    return substr( str_pad( dechex( mt_rand() ), 8, '0', STR_PAD_LEFT ), -8 );
}

// calculate the hash from a salt and a password
function getPasswordHash( $salt, $password )
{
    return $salt . ( hash( 'whirlpool', $salt . $password ) );
}

// compare a password to a hash
function comparePassword( $password, $hash )
{
    $salt = substr( $hash, 0, 8 );
    return $hash == getPasswordHash( $salt, $password );
}

// get a new hash for a password
$hash = getPasswordHash( getPasswordSalt(), $password );

You don’t have to attach the salt to the hash, you can instead store them separately within the database, but I like keeping them together in a single string. Equally, the salt needn’t be in hexadecimal, but I like the symmetry with the hexadecimal hash.

Finally, as Thomas Ptacek points out, you don’t want the fastest hash algorithm in the world for this – a fast algorithm is more useful to an attacker than it is to you.

10 Second film assigment

Sunday, January 6th, 2008

Speed

Wednesday, November 14th, 2007

Photos

Creative Tech Workshops Restoring Photos

Sunday, October 28th, 2007

Before and after shots of photo fixes.

blur-backgound_2up

hue-saturation_done_2up

color-balance_done_2up

repair04_done_2up