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

The Movie Hollywood (And My Wife) Doesn't Want You To See: Weekend at Jacko's The Movie Hollywood (And My Wife) Doesn't Want You To See: Weekend at Jacko's
Sysi: the ultimate administrators toolkit Sysi: the ultimate administrators toolkit
Movie: Priest Academy Movie: Priest Academy
Inspirational Rat Story Inspirational Rat Story
A face-melting DSL that allows programming ON the iPhone (and iPad) A face-melting DSL that allows programming ON the iPhone (and iPad)
The secretGeek Disaster Recovery plan The secretGeek Disaster Recovery plan
Save KNVTn! Before it's too late Save KNVTn! Before it's too late
The Ultimate Agent of WERF Destruction The Ultimate Agent of WERF Destruction
The new prisoner's dilemma The new prisoner's dilemma
Original Premise for a road movie Original Premise for a road movie
What's a better game than Devshop? What's a better game than Devshop?
DevShop: The Cool Game that Makes Development Look Fun DevShop: The Cool Game that Makes Development Look Fun
Should be purple Should be purple
Kitchen Agile Kitchen Agile
Perhaps Perhaps "Go" is the new Visual Basic
zen-coding: turn those CSS selectors upside down zen-coding: turn those CSS selectors upside down
Debugging: It's all about finding Albuquerque. Debugging: It's all about finding Albuquerque.
The Real-Time online JQuery Editor The Real-Time online JQuery Editor
HTML5, a 3 minute guide HTML5, a 3 minute guide
Developer Codpieces Developer Codpieces
Agile for one: The Personal Story 'Wall' In Action Agile for one: The Personal Story 'Wall' In Action
Never work with thick people. Never work with thick people.
Cosmo: project status panel Cosmo: project status panel
Windows Search in Japan Windows Search in Japan
Project Management Zen Project Management Zen
Continuous Integration, Plugins and Going Too Far Continuous Integration, Plugins and Going Too Far
The Rules of Stand Up The Rules of Stand Up
Sydney International Airport: Stupid, Criminal, or Criminally Stupid? Sydney International Airport: Stupid, Criminal, or Criminally Stupid?
God No! ...The ReBuilder God No! ...The ReBuilder
Matt, The Office Mortar Matt, The Office Mortar
'Outlook style' rules for Subversion 'Outlook style' rules for Subversion
Really deep linking: Url + regex Really deep linking: Url + regex
hExcel -- A Hexagonal Spreadsheet hExcel -- A Hexagonal Spreadsheet
Is the remote control a thing of the past? Is the remote control a thing of the past?
The Utterly Thorough Guide To Awesome Application Compatibility on Windows 7. The Utterly Thorough Guide To Awesome Application Compatibility on Windows 7.
Astounding Hyperlinked Noticeboard Astounding Hyperlinked Noticeboard
Three Questions About Each Bug You Find Three Questions About Each Bug You Find
Recursing over the Pareto Principle... Recursing over the Pareto Principle...
Sometimes, The Better You Program, The Worse You Communicate. Sometimes, The Better You Program, The Worse You Communicate.

Archives .: secretGeek :: Complete Archives
TimeSnapper -- Automated Screenshot Journal TimeSnapper.com    
Version 3.3: true productivity boost

Next Action NextAction
Managing the top of your mind

World's Simplest Code Generator (html edition) World's Simplest Code Generator

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
Universal Troubleshooting checklist Universal Troubleshooting Checklist
Top 10 SecretGeek articles Top 10 SecretGeek articles
ShinyPower (help with Powershell) ShinyPower
Now at CodePlex

Realtime CSS Editor, in a browser RealTime Online CSS Editor
Gradient Maker -- a tool for making background images that blend from one colour to another. Forget photoshop, this is the bomb. Gradient Maker


[powered by Google] 


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
Rhys Parry
Joel Pobar
OJ Reeves
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