Defensive Programming

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 String, ByVal psClientIP As String) As 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 own bank account and full payment 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 String, ByVal psPassword As String) As 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.

 

Privacy Policy

I do not rent, sell, or share personal information about you with other people or companies. I keep your information secure, so that no known viruses, worms, spiders or other nasties can steal your email adress or other information.

I abhor spam.

I gather traffic information on an anonymous basis and exclusively use this for analysing the effectiveness of my site. I don't make this information available to anyone else. I don't use 'Web Bugs' or other tricks.

The site now contains advertisements. In particular there are 'google ads' down the right hand side of the page. In future I might put these ads in a more prominent location, since you slackers don't seem to click on them often enough. A contract with google prevents me from disclosing how much money I make from the ads. I think it's okay for me to admit this much though: to date it's not enough to cover hosting costs.

I also use the 'Amazon Referer' program in a futile attempt to make serious money. When I mention a book I sometimes provide a link to "Amazon.com." If such a link contains the word 'secretGeek' then you can be certain I'm out to make a few bucks on the quick. I only recommend books that I actually like, though, so if I say "Go and buy this book" then it's motivated by one part greed and one part honesty. If I were a little less greedy I would say "Go and borrow this book from a library." I like libraries and I think more people should use them.

Also, publishers send me books, gratis, and I review them here. I only publish review for book that I like, or that I find interesting. This is an offshoot of my general philosophy: If you can't think of anything nice to say, then shut the f*ck up. You should know that at least a small part of my honesty in these reviews must be affected by my bibliophilic wish to keep getting free books. Still, I'm proud to encourage people to read books. Books are better than web sites. Go read one now.

If you wish, you may request a copy of any personal information which I hold about you at any time. If you are aware of any inaccuracies in such personal information then I will take any steps necessary to correct those inaccuracies. I can destroy any private information I hold about you, If you so choose.

If you have any concerns about this privacy policy, please contact me.

 

Lessons From Bill Gates

The following quote from Bill Gates got me thinking:

"Every now and then i like to pick up a copy of TIME magazine and read every article from beginning to end, not just the articles that interest me most. That way you can be certain to learn something you didnt know previously."

Bill is a smart man, so I did what he said.

I picked up a magazine and I read every article in there, from beginning to end. I read the letters to the editors and I pored over every advertisement.

But I didn't stop there, I also looked at the layout, the use of fonts and the wording used in the headings.

I analyzed every photograph, taking into account the composure, the use of colour, and the size of the photos.

I surveyed the use of illustrations, the way that the images interplayed with the text, the way that certain quotes were brought out for emphasis.

I read the copyright notices and the page footers. I thought very hard about the editorial and i memorised the names of the people who had worked on the magazine.

Then I studied the paper itself. I noticed how glossy it was, how the tiny pixels of colour were indistinguishable if i held the page ten centimetres from my face, but how under a maginifying glass I could clearly detect the intricate pattern of coloured points.

I inhaled the sweet chemical aroma of the pages and I dreamt of the distant lands where the papers had been milled from the pulp of trees. I thought of the hard work of the men who cut down those trees and the noble work of those who planted new trees.

I ran my tongue over a page and noticed the tangy taste of the inks and how it differed between the pages that contained images and those that contained only words. I tore off a corner and began to chew silently on the paper when the newsagent barrel-tackled me and threw me out.

Thank you Bill.

 

Cultural Ignorance Comes at a Price

Don't have the time to write Culturally Aware applications?

Now Culturally Ignorant applications are easier than ever, thanks to a new CulturallyOffensive webservice from racist.epithets.net.

Language is a remarkably fluid thing. And what's offensive to one minority today, may be quite acceptable tomorrow.

You want your racist slurs to remain cutting edge - but you don't want to re-deploy your entire offensive desktop application each time an insult changes.

Satellite Assemblies

It's always been best practice to avoid hard coding your prejudices into an application. Smart system architects using ".Net" technology will have already identified their volatile material and embedded it into a resource file in a satellite assembly. That way you can redeploy your insults and misconceptions on a site by site basis, targetting the specific prejudicial needs of the local users.

Enter the Internet...

But in an ever more connected world, your applications need to be culturally offensive on a global scale, and managing the changing insults of ignorant users the world over can become an intolerably difficult task.

For seriously connected applications, where cultural offense is as often changing as the moods of Allah, you need the power of a webservice. That's where racist.epithets.net step in, with their new CulturallyOffensive webservice.

The web service provides generic objects for handling all your culturally ignorant needs:

  • CulturallyOffensive.StereoTypes
  • CulturallyOffensive.Prejudices
  • CulturallyOffensive.CommonMisconceptions
  • CulturallyOffensive.ExtendedInsults
  • CulturallyOffensive.QuickInsults
  • CulturallyOffensive.BadTranslater

Noteable features

QuickInsults, is a handy subset of ExtendedInsults, optimized for speed, where each insult is no more than two syllables in length. Even the most backward redneck user should have no trouble annunciating these little gems.

What's the Catch?

You can subscribe to the basic functionality for free but the namespace extensions come at a price. If you want to use the HateCrime manifest and its LynchMob collection, you'll have to pay for the privelege. Payment is in American Dollars only.

Breast of luck

Danford.

Danford C Meridius is a guest columnist. His opinions are not those of the Secret Geek website. His advice is provided for satirical purposes and should not be followed.

 

The Lost Art of Batch Programming

No matter what other interesting skills you acquire, an ability to write DOS batch files is a skill that you will cherish throughout your life. And should you survive to a hundred and five, batch programs may be the one thing that remains unchanged.

Piping, Pinging, setting the path, echoing.... all the good stuff...

Here's an example of using a batch program to stop an application (CALC.exe in this case) from being run twice on the one machine.


@ECHO Off
IF EXIST C:\%COMPUTERNAME%.txt GOTO RUNNING
ipconfig > C:\%COMPUTERNAME%.txt
ECHO PROGRAM STARTED...
CALC.EXE
ECHO PROGRAM FINISHED
IF EXIST C:\%COMPUTERNAME%.txt DEL C:\%COMPUTERNAME%.txt
GOTO END
:RUNNING
ECHO FILE IS ALREADY RUNNING
:END

This example used the following:

  • @
  • ECHO
  • ENVIRONMENT VARIABLES (%COMPUTERNAME%)
  • IF
  • EXIST
  • GOTO
  • REDIRECTION (>)
  • DEL
  • LABELS (:)
 

Future Articles

Articles I'd like to write one day

  • Formatting Code for the web
    • the hard way
    • the easy way
    • the good way
  • About RSS
  • Release Procedures
  • Quotes I Hate
  • Quotes I Like
  • Manuscript Revision
  • Web Content Writing
  • Application Development Framework
  • "Generic" Applications
  • Recommended elements for a web page
  • Recommended elements for an intranet
  • Assessing a web design company
  • benefits of a web site
  • Groupthink
  • Prototyping for Feedback
  • BugAnxiety and GeekGuilt (BugGuilt)
  • UI Comes first
  • Feedback Fear
  • Perils of the 'Ultimate' Project
  • Project Burnout
  • Post Project Anxiety
  • Procrastinology
  • Project Guttenberg
  • Confessions of a ListManiac
 

GeekBlock

2017 Update:
Now available as an interactive flowchart!
Productivity Flowchart

Just as writers are prone to writer's block, programmers are prone to GeekBlock.

Maybe we can't find the cause of a particular bug,or maybe we just can't stop surfing the web when we know there's things we should be doing.

Having found myself in the clutches of GeekBlock more than once, I've put together some notes from the inside.

I can think of three different situations which can give rise to the dreaded GeekBlock

  1. You are stuck by a specific problem
  2. You lack motivation
  3. You are procrastinating

In each of these situations you might feel that there is no way of moving forward, or that any technique of moving forward is extreemly slow. But all of them can be overcome, if you are willing to deal directly with the problem.

Notes on each situation are included below.


You are stuck by a specific problem top

You've been handed a bug to resolve - but you're not making any headway. Or you're developing a component for a large project, but one small part of it has got you beat.

Some ways you might want to deal with this situation include:

  1. Tear your hair out
  2. Tell your manager that it cannot be done
  3. procrastinate
  4. Quit your job

Since these methods are not particularly rewarding in the long term, you might prefer to consider some more sustainable techniques for problem solving.

Take the time to analyze around the problem. Ask the following questions - and don't settle for simple answers.

  1. What's the problem
  2. Do you lack knowledge about the problem?
  3. Do you lack Technical Knowledge?
  4. Can you work around the problem?

Identify the problem

  1. List making
  2. brain storming
  3. talk it out

(if need be, talk it out very very slowly)

Do you Lack knowledge about the problem?

(eg, a bug that can't be reproduced)

  1. Find the people who raised it
  2. Talk to anyone who knows more about it
  3. If it's a bug - can you reproduce it?

Lack of Technical Knowledge?

  1. Acquaintances
    1. Colleagues
    2. Friends, old colleagues
  2. Web
    1. Google
    2. product speicifc sites (eg: MSDN for microsoft products)
    3. Your Personal Favourites
    4. Other people online who've had the same problem (write to them)
  3. Books
    1. Office library
    2. Personal library
    3. State/Government libraries
    4. Bookshops

Can you Work around the problem

Can it be solved through another means?

What's the underlying business problem?


You lack motivation! top

  1. The task is mind numbingly dull!
  2. The task is too big.
  3. I just don't feel like working on it.

I just don't feel like working on it.

Maybe you are depressed, even clinically-depressed. You can get treatment for that - so go for it.

  1. Take a break
  2. Take control
  3. List making
  4. brain dumping
  5. talk it out

Take a break

Sometimes the brain is just exhausted. Sometimes the spine has been in the same position for far too long. If you've sat staring at a problem, or staring in to thin air, for twenty minutes or more with no success then you're entering paraletic brain shut down and you need to step away from the keyboard.

Drink some coffee, read a magazine, look at the sky. If you work from home then go out and dig in the garden. If you work in an office then go outside and dig in the corporate rose bush. You never know what you'll unearth.

Take Control

When true procrastination sets in, you're mind can travel far away from the problem. If you've lost your focus then it may be time to sit down and try to work out exactly what the problem is.

List Making

Making a list, revising a list and expanding on an existing list are my preferred ways of approaching particularly difficult conundrums.

Brain Dumping

Sometimes there is other junk knocking around in your brain that clouds your critical faculties. When I start to feel that way I try to list each of the separate topics I am concerned with - not in any detail, not neatly - just quickly and thoroughly. Sometimes this can reveal extraordinary things about where your real concerns lie.

Talk It Out


Suffering from "Super Procrastination" top

Procrastination, or hesitation, can be an immensely enjoyable exercise, particularly when you are facing looming deadlines. SOme of the best activities to perform while procrastinating include:

  1. Surfing the web
  2. Ripping CDs into MP3s
  3. Drawing
  4. Emailing/chatting
  5. Cleaning your keyboard
  1. Little steps
  2. List making