Defensive Programming
secretGeek .:dotnuts about dotnet:.
home .: about .: sign up .: sitemap

Defensive Programming

Part 1 - Login Validation

A guide to using the latest defensive programming techniques in your code.

Security breaches not only occur because of buffer overruns and system backdoors. Some of the simplest security mistakes are made by allowing potentially malicious users to access your system.

Login validation should be coded defensively to prevent unauthorised user access.

The following syntax is recommended.

Listing 1
Public Function ValidateLogin(byval psUserName as string, byval psPassword as string) as Boolean
  Return False
End Function

The most immediate benefit of the above code is that users will no longer be able to login to the system.

Numerous other positives will flow from this simple fact. Due to decreased server loads, the most resource hungry portions of your code will now execute much faster. And less often.

The help desk will thank you, as they spend less time dealing with the petty gripes of users, now that there are no actual users to speak of. They may find they are bugged but the occassional complaint about login troubles.

With no new data being created, incremental backups will be done in a flash. System administrators can get on with their preferred task of designing ever more complex network diagrams in visio.

However, it is possible, even likely that your manager won't understand the complex issues of defensive programming. Once you've implemented the above login validation technqiue he may jump up and down screaming until his ears have gone a rich shade of purple. Amongst his ranting you may be able to decipher a suggestion that users are occasionally granted login permission to the application.

To accomodate his clearly socialistic point of view, implement the code provided in listing 2.

Listing 2

Public Function ValidateLogin(byval psUserName as string, byval psPassword as string) as Boolean
  Return True
End Function

This will doubtlessly please him, and users will be quite happy too, as now all attempts to gain access to the system will be successful. The number of calls to the help desk regarding failed logins will be at an all time low, but now that users are actually using the application, users will doubtless find other reasons to trouble the helpdesk.

Inform the helpdesk that any new issues will only be addressed if they are logged via your own custom made Issue Logging software. Ensure that the Issue Logging software has a Login Validation routine of its own, similar to that provided in listing 1.

You may find that when your manager realises how succesful the application now is at accepting login requests, he may again employ his up and down jumping tactics.

Amongst his ranting he will probably insist that you don't let 'just anyone' log in to your system, and he may specifically say that we doesn't want to grant access to 'hackers' and 'terrorists'.

To accomodate these requests, i provide a third listing. You'll need to add a reference to the System.Web.dll.

Listing 3
Public Function ValidateLogin(ByVal psUserName As String, _
      ByVal psPassword As StringByVal psClientIP As StringAs Boolean

    If psUserName.ToUpper.IndexOf("KEVIN") <> -1 And _
          psUserName.ToUpper.IndexOf("MITNICK") <> -1 Then
      MessageBox.Show("Hello Kevin Mitnick. You are the notorious  " & _
                "hacker once known as 'Americas Most Wanted  " & _
                "Computer Outlaw'. You're not getting access  " & _
                "to our system. You have to get up pretty early " & _
                "in the morning to pull the wool over my boss's eyes. " & _
                "Login denied, sucker!")
      Return False
    End If
    If psUserName.ToUpper.IndexOf("OSAMA") <> -1 Then
      MessageBox.Show("I don't know how common the name 'Osama' is " & _
                " in the muslim world, but just to be on the  " & _
                "safe side, we'd rather not let you in right now. " & _
                "But please wait by the computer for a short while.")

      Dim email As New System.Web.Mail.MailMessage()
      System.Web.Mail.SmtpMail.SmtpServer = "MailServer"
      With email
        .To = "webmaster@fbi.gov.au"        
        .Subject = "suspected leader of Al Qaeda located."
        .Priority = Web.Mail.MailPriority.High 
        .Body = "A suspect answering to the name 'Osama' is " & _
                "behaving suspiciously at a computer terminal" & _
                "on our network with ip address " & psClientIp & " " & _
                "Please apprehend him immediately. " & _
                "I'd be careful about approaching him, though. " & _
                "He looks irritable because an application he is " & _
                "using won't validate his login anymore. " & vbCrLf & _
                "A reward should be forwarded to  " & vbCrLf & _
                "LeonBambrick@hotmail.com." & _
                "Cheers, lb."
        System.Web.Mail.SmtpMail.Send(email)
      End With
      Return False
   End If
   
   If psPassword.Length = 0 Or psPassword.ToUpper.Trim = "PASSWORD" Then
     Messagebox.Show("Login Denied. Your stupidity represents a security threat.")
     Return False
   End If
   
   'Allow all other users
   Return True
   
 End Function

What do you do if it's still not good enough?

It has to be said that some managers are very hard to please. I once met a manager who felt that when generating invoices through our billing system, we ought to include full details of our company's bank account so that customers could pay us accordingly. He added further that he wasn't happy with the habit my code had of substituting in my bank account details and my full details. He even pulled a face and if memory serves, yes that's right, he fired my arse.

So if you've given Listing 3 a try and the manager still isn't happy then sit him down and listen very carefully to what he has to say. Ultimately it's his decision who gets validated, so put the choice in his hands:

Listing 4

Public Function ValidateLogin(ByVal psUserName As StringByVal psPassword As StringAs Boolean
    Dim email As New System.Web.Mail.MailMessage()
    System.Web.Mail.SmtpMail.SmtpServer = "MailServer"
    With email
      .To = "YourManager@YourEmployer.com"
      .Priority = Web.Mail.MailPriority.High
      .Subject = "Intrusion Attempt Detected!"
      .Body = "An intruder with login name " & psUserName & _
              " (password: " & psPassword & ") " & _
              "is attempting to gain access to the system. " & _
              "Please attach a debugger to the relevant " & _
              "Application Process, pause execution of the code" & _
              "and manually move the Program Pointer to either the " & _
              "'Return False' or the 'Return True' line below, " & _
              "depending on whether you wish to Deny or Allow Access. " & _
              "The choice is yours fathead."
      System.Web.Mail.SmtpMail.Send(email)
    End With
    System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite)
    Return False 'Deny Access
    Return True 'Allow access

End Function

Remember to include debugging symbols in the new build so that the attach will work. Deploy the application, and invite a representative from Human Resources to come and see you at your desk.

You manager will arrive first, and he will have that intersting purple faced look he sometimes acquires. Show him the printed copy you have of the pornographic url's he's been viewing through his company internet connection. Just as the Human Resources representative arrives, ask your manager if there's anything he wishes to discuss.

If done correctly, the process will ensure your manager provides you with a vastly upgraded computer and anything else you ask for.


Add or view comments about this page

Articles

Do they store the code for TFS in TFS? Do they store the code for TFS in TFS?
Sudden TimeSnapper Discount! Sudden TimeSnapper Discount!
How Can Microsoft Beat Google? How Can Microsoft Beat Google?
TimeSnapper 3.1: Attack of the the Red/Green Stripes TimeSnapper 3.1: Attack of the the Red/Green Stripes
21 tools used in our MicroISV 21 tools used in our MicroISV
Lost Treasures of the DOS World: tree! Lost Treasures of the DOS World: tree!
The Virtual Machine Machine and the Virtual Virtual Machine The Virtual Machine Machine and the Virtual Virtual Machine
Should Linq To Sql Go Should Linq To Sql Go "Open Source"?
Redux: New Synchronisation Idea Overlooked By Microsoft Redux: New Synchronisation Idea Overlooked By Microsoft
New Synchronisation Idea Overlooked By Microsoft Live team New Synchronisation Idea Overlooked By Microsoft Live team
Visual Studio UX Taskforce, Office UX Taskforce... etc. Visual Studio UX Taskforce, Office UX Taskforce... etc.
How to be Jeff Atwood How to be Jeff Atwood

Archives .: secretGeek :: Complete Archives :.
25 steps for building a Micro-ISV 25 steps for building a Micro-ISV
3 minute guides -- babysteps in new technologies: powershell, JSON, watir, F# 3 Minute Guide Series
Top 10 SecretGeek articles Top 10 SecretGeek articles

Downloads

TimeSnapper -- Automated Screenshot Journal TimeSnapper.com    
Version 3.1: instant productivity profiles

ShinyPower (help with Powershell) ShinyPower
Now at CodePlex

Next Action NextAction
Managing the top of your mind



[powered by Google] 


Thai Erawan, Brisbane Restaurant, delicious thai food in paddington Thai Erawan, Brisbane Restaurant
World's Simplest Code Generator (html edition) World's Simplest Code Generator
Gradient Maker -- a tool for making background images that blend from one colour to another. Forget photoshop, this is the bomb. Gradient Maker
How to be depressed How to be depressed
You are not inadequate.



Recommended Reading

The Best Software Writing I
The Business Of Software (Eric Sink)

Recommended blogs

Jeff Atwood
Reginald Braithwaite
Joseph Cooney
Phil Haack
Scott Hanselman
Julia Lerman
Joel Pobar
Eric Sink
Joel Spolsky
Des Traynor

Aggregated Links

programming.reddit.com
dzone
dot net kicks

Human Link Machines

interesting finds
a continuous learner's weblog
arjan's world
n links today
new and notable
morning coffee
learning .net
weekly link post
(my del.icio.us account)

LinkedIn profile
home .: about .: sign up .: sitemap .: © Leon Bambrick 2003 .: privacy

home .: about .: sign up .: sitemap .: © Leon Bambrick 2003 .: privacy