Menu

Defensive Design

Authentication

Authentication means confirming the identity of a user. It must happen before the user is allowed to use the program or reach the data it holds, so that a stranger cannot open someone else's saved work or change their scores. Without it, everything in the program is open to anyone who runs it.

Simple authentication

Simple authentication asks for a username and a password and compares each one with the details the program has stored. Both must match: a correct username with the wrong password must still be refused.

When a login fails, the message should not reveal which part was wrong. Telling someone 'that password is incorrect' confirms the username is real, so they only have to keep guessing passwords. One plain message such as 'login unsuccessful' gives nothing away.

Details enteredMessage shown
Correct username and correct passwordAccess granted
Correct username, wrong passwordLogin unsuccessful
Unknown username, any passwordLogin unsuccessful

Limiting failed attempts

A login that can be tried for ever can be beaten by guesswork, so the program should count failed attempts and stop after a set number. Access is then refused, or the account is locked until someone unlocks it. The program keeps a counter, and a condition-controlled loop stops as soon as the count runs out.

# stored details would come from a file in a real system
correct_user = "artclub7"
correct_pass = "paint42"
tries_left = 4
signed_in = False

while tries_left > 0 and signed_in == False:
    user = input("Enter username: ")
    password = input("Enter password: ")
    if user == correct_user and password == correct_pass:
        signed_in = True
    else:
        tries_left = tries_left - 1
        print("Login unsuccessful")

if signed_in == True:
    print("Gallery open")
else:
    print("Account locked - ask the club leader")

Output when the user types artclub7, blue11, artfan, paint42, artclub7, paint42:

Enter username: artclub7
Enter password: blue11
Login unsuccessful
Enter username: artfan
Enter password: paint42
Login unsuccessful
Enter username: artclub7
Enter password: paint42
Gallery open

Four tries are allowed here. Each failed pair of entries takes one off the counter, the loop ends when no tries are left, and every failure gives the same message, which tells an attacker nothing.

Strong passwords and stored details

Authentication is only as good as the passwords it accepts, so the program should require strong passwords, reasonably long and mixing letters, digits and symbols. A rule in the program can reject anything shorter than a set length, and a sensible program refuses to create an account without one.

In a real system, the stored usernames and passwords live in a file or database rather than being written into the program code. Anyone who reads the code would then know every password, and changing one would mean editing and redistributing the program itself.

Practise this