Aug
4
2012

Passing Parameters to a QueryString – The right way to do it, Encryption

Ok, so the other day I was browsing some asp.Net Forums, answering question when I came across this little diamond.  The question was on simply passing parameters to a querystring and this is how it was answered.

Q: How do I pass the UserId and Password to my login.aspx page?

A: Have a Hyperlink control pointing to Login.aspx and append the Text of each textbox to the querystring as parameters, see below

dim myPara as string= "?userid=" & txtUserName.text & _
 "&password=" & txtPassword.text

lnkLogin.navigateUrl = "login.aspx" & myPara

 

How to kill me

I think I had a mini heart attack when I read this.  This! This my friends is how people get hurt.  Lets read it together and dissect.

  1. First of all, this code is not validating the parameters at all before sending them to the login.aspx querystring, what would happen if either textbox was empty?
  2. There’s no validation on the data types, what would happen if I entered a bunch of 5’s for both answer, nothing catastrophic but if your expecting a string response, you should check for string before sending it to your QueryString.
  3. Now, what happens if I insert malicious code here instead of an actual username?  I won’t give an example but assuming this parameter was going to go to an SQL database, this is how injection occurs.
  4. Lastly, the user’s password is sent to another page, in open text, not hidden at all.

Shame, Shame

 

How do I fix this?

In most cases, my answer would immediately be, just use Routing (http://everymanprogrammer.com/index.php/asp-net-4-0-routing-a-simple-tutorial-that-works/), its smarter, cleaner and Search Engines dig it.  Ok, we can’t always use Routing so let’s figure another way of doing this.

The easiest smartest thing to do here would be to Encrypt the data received from the textboxes before sending it to the Login.aspx querystring and decrypt it before sending it to whatever Authentication mechanism you’re using.  I got this code off a forum, maybe 6months to a year ago and I truly appreciate it, if you recognize it, please let me know and I’ll give the author credit.

Ok, so essential the code is broken into 3 parts.  In my example I’ve place the below code into a helper.vb Class file.

 Const passphrase As String = "thisisaspecialkeyusedtohashyourcontent_changemeandmakemeunique"

Essentially this is a secret code used to Hash your content, by using a code like this, it ensures that your Hash Table is unique from other users using the same code.  Smart huh?

Now, we have 2 complex but smart functions that both Encrypt the data to send and Decrypt it for receipt.

 

*Edit – Thanks to David Harvey for pointing out I missed the Imports line*

Imports System.Security.Cryptography
  
 Public Shared Function EncryptData(Message As String) As String
        Dim Results As Byte()
        Dim UTF8 As New System.Text.UTF8Encoding()
        Dim HashProvider As New MD5CryptoServiceProvider()
        Dim TDESKey As Byte() = HashProvider.ComputeHash(UTF8.GetBytes(passphrase))
        Dim TDESAlgorithm As New TripleDESCryptoServiceProvider()
        TDESAlgorithm.Key = TDESKey
        TDESAlgorithm.Mode = CipherMode.ECB
        TDESAlgorithm.Padding = PaddingMode.PKCS7
        Dim DataToEncrypt As Byte() = UTF8.GetBytes(Message)
        Try
            Dim Encryptor As ICryptoTransform = TDESAlgorithm.CreateEncryptor()
            Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length)
        Finally
            TDESAlgorithm.Clear()
            HashProvider.Clear()
        End Try
        Return Convert.ToBase64String(Results)
    End Function

    Public Shared Function DecryptString(Message As String) As String
        Dim Results As Byte()
        Dim UTF8 As New System.Text.UTF8Encoding()
        Dim HashProvider As New MD5CryptoServiceProvider()
        Dim TDESKey As Byte() = HashProvider.ComputeHash(UTF8.GetBytes(passphrase))
        Dim TDESAlgorithm As New TripleDESCryptoServiceProvider()
        TDESAlgorithm.Key = TDESKey
        TDESAlgorithm.Mode = CipherMode.ECB
        TDESAlgorithm.Padding = PaddingMode.PKCS7
        Dim DataToDecrypt As Byte() = Convert.FromBase64String(Message)
        Try
            Dim Decryptor As ICryptoTransform = TDESAlgorithm.CreateDecryptor()
            Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length)
        Finally
            TDESAlgorithm.Clear()
            HashProvider.Clear()
        End Try
        Return UTF8.GetString(Results)
    End Function

I’m not even going to try and explain everything that’s going on here, instead, let’s just add the final 2 pieces of the puzzle, in our default.aspx page we add our controls for a login, and in our default.vb

    Private Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click

        Response.Redirect("~/login.aspx?username=" & EncryptData(txtUsername.Text) & "&password=" & EncryptData(txtPassword.Text))

    End Sub

in our login.vb

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

        Dim username = DecryptString(Request.QueryString(0))
        Dim password = DecryptString(Request.QueryString(1))

        Label1.Text = "Your username is " & username & " and your password is " & password
    End Sub

Now let’s run this baby.  Enter some text in each textbox and submit, now, pay special attention to the querystring.

http://localhost:59956/login.aspx?username=YWAt6R2TU1g=&password=JUxVGs1RMsLfjzZ5JKuTHA==

 Now that’s sexy!

Ok, maybe not, but it’s smart, and smart is sexy, right?

Wow, tough crowd.

 

Conclusion

This was just a small example of how 15lines of code and 2 functions can make or break your website.  At this point, there should still be additional checking to occur before the encryption, like Validation Controls on each textbox but you get the picture.   This is a small price to pay for security and your users will appreciate the care your are taking with the information they are storing on your website.

 

 

If you enjoyed this post, please consider leaving a comment, or sharing it by Tweeting or using the FaceBook Like button.

You may also Subscribe to this blog and receive notifications of new posts by email using the feature at the top of the page.

Please remember to visit my Sponsors (right column) as it helps me get the bills paid.

EncryptedQuerystrings
EncryptedQuerystrings
EncryptedQuerystrings.zip
Version: 1.0
64.8 KiB
52 Downloads
Details...

Comments

comments

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Visit my Sponsors

Read previous post:
Ajax Control Tookit
Using the Ajax Modal Popup as a Login Control – A Beginner`s Guide

Something I see requested quite a bit online is the ability to have a popup form appear to allow the...

Close