Web application security: the basics

Lesson 7 of 8 · Web basics

A web application is used by many people – and some of them try to misuse it. This lesson explains the most common attacks and the basic rules of protection: HTTPS, storing passwords, checking data and why you never trust what arrives from the browser.

Before you start: required prior knowledge – the HTTP protocol, frontend and backend.
How to learn: try every example in the browser or on the command line and do the exercises from the lesson. The examples are in HTML, JavaScript and Python; for most of them a browser is enough, and for the Python examples you need Python 3 installed.

HTTPS and certificates

Without HTTPS data travels like a postcard – anyone along the way (e.g. on a public Wi-Fi network) can read it. HTTPS encrypts it with the TLS protocol and proves that the server is the real one:

  • the server has a certificate signed by a trusted authority (e.g. the free Let's Encrypt);
  • the browser checks the certificate and shows a padlock; if something is wrong – a warning over the whole page;
  • the padlock means that the connection is secure, not that the site is honest – fake sites have HTTPS too.

Passwords are not stored – a hash is

A correct application does not know your password. In the database it keeps a hash: the result of a one-way function from which the password cannot be recovered. At sign-in the hash of the typed password is compared with the saved one.

import hashlib, os

def make_hash(password, salt=None):
    salt = salt or os.urandom(16)                              # a random "salt" for every user
    h = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, 200_000)
    return salt, h

salt, saved = make_hash("secret123")           # at registration: the salt and the hash go into the database
_, check = make_hash("secret123", salt)        # at sign-in: the same procedure with the same salt
print(check == saved)                          # True – the password is correct
_, wrong = make_hash("secret124", salt)
print(wrong == saved)                          # False

The "salt" makes sure that two users with the same password have different hashes, and many repetitions (200,000) slow down an attacker who is guessing passwords. Frameworks (Django, ASP.NET Core Identity) do this by themselves – you do not need to write your own.

The most common attacks

AttackWhat the attacker doesProtection
SQL injectiontypes part of an SQL command into a form field (e.g. ' OR '1'='1) that changes the database queryparameterized queries / ORM – never join the user's text into SQL
XSS (script injection)types a <script> into a comment that runs for other users and steals their cookie"escaping" user text before showing it (templates do it automatically), the CSP header
CSRFa fake page makes your browser send a request to a site where you are signed ina CSRF token in forms, cookies with SameSite
password guessingautomatically tries thousands of passwordslimiting the number of attempts, strong passwords, two-factor sign-in
phishinga fake page that looks like the real one and asks for the passwordcheck the address, a password manager, two-factor sign-in

A list of the most important risks of web applications is regularly published by the OWASP (Top 10) organization.

Example: SQL injection and a correct query

import sqlite3

db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE users (name TEXT, password_hash TEXT)")
db.execute("INSERT INTO users VALUES ('ana', 'x1'), ('mark', 'x2')")

entry = "nonexistent' OR '1'='1"         # a malicious entry from a form

# WRONG: the user's text becomes part of the SQL command
query = f"SELECT name FROM users WHERE name = '{entry}'"
print("vulnerable:", db.execute(query).fetchall())

# CORRECT: a parameter (?) – the database treats it only as data
print("safe:", db.execute("SELECT name FROM users WHERE name = ?", (entry,)).fetchall())

The vulnerable query returned all users, because the condition became "name = 'nonexistent' OR 1 = 1", and that is always true. The parameterized query looks for a user with exactly that (strange) name – and does not find one.

Rules for every programmer

  1. Do not trust input. Everything that comes from the browser (forms, URL, cookies, headers) may have been changed – check it on the server.
  2. Least privilege. A user and a program get only as much access as they need.
  3. Secrets outside the code. Database passwords and API keys go into the server settings (environment variables), not into the code on GitHub.
  4. Update. Frameworks and libraries regularly get security patches.
  5. Use ready-made solutions. Sign-in, hashing and form protection already exist in the framework – do not invent your own.
Common mistakes and tips
  • The padlock (HTTPS) protects the connection, but it does not guarantee that the site is honest.
  • Never join user text into an SQL query or HTML without processing it.
  • Try attacks only on your own application on your own computer – on other people's sites it is forbidden and punishable.

Check your knowledge

Open the quiz

Web application security

1. What does an application keep in the database instead of the password?




2. How is SQL injection prevented?




3. What does the padlock in the address bar mean?