Skip to content

Lesson 2 of 2

Error handling

Listen to an AI summary of Error handling

0:00 / 0:37

Every program meets errors, such as a missing file or text where the code expects a number. Error handling is the code that decides what a program does after an error.

A door that unlocks in a power cut

The front door of a sports centre has an electric lock. In a power cut one kind of door unlocks, and anyone can walk in. Another kind of door stays locked until the power returns.

In software the lock is a check, and the power cut is an error in the check. Failing open (CWE-636) is treating an error in a check as a pass. Failing closed is treating the error as a refusal. A security check must fail closed.

What is an exception

An exception is the signal a program raises when an error happens, which stops the normal flow of the code. Python raises an exception when the function int gets text that is not a number. With no code to catch the exception, the program stops.

A catch block is the code that runs when an exception happens in the lines the block covers. In Python a catch block is written with the words try and except. The picture labels a catch block in a small program.

  1. try:# The catch block covers the lines under try.
  2. quantity = int(text)# int raises an exception when text holds abc.
  3. except ValueError:# The catch block starts here. ValueError is the kind of exception.
  4. print("Type a whole number")# The catch block runs only after an exception.
A catch block in Python. JavaScript uses the word catch in place of except.

After a catch block runs, the program carries on with the line after the block.

The ownership check in the sports shop

Each order of the sports shop has a number. The ownership check confirms an order belongs to the signed-in customer.

The server runs the function in the picture for each request for an order page. Look at lines 7, 8 and 9.

  1. def show_order():
  2. order_id = request.args["id"]# reads the order number from the request
  3. try:
  4. owner = find_owner(order_id)# asks the database who owns the order
  5. if owner != session["customer_id"]:# tests whether the owner is a different customer
  6. return not_found_page()# refuses a customer who is not the owner
  7. except Exception:# starts a catch block for every kind of exception
  8. log_error("ownership check failed")# writes the error to the log
  9. return order_page(order_id)# sends the order page
session holds what the server remembers about the signed-in customer, and != means is not equal to.

Sam, a customer, is signed in and asks for order 1043, which belongs to Priya. Line 4 finds that Priya is the owner, so line 6 sends Sam a page that says not found.

Sam asks again when the database is too busy to answer. Line 4 raises an exception. Python skips lines 5 and 6 and runs the catch block. Line 8 writes the error to a log.

The catch block ends, and the program carries on with line 9. Sam sees Priya's order.

  1. Pass. The order belongs to Sam.sends the order page
  2. Fail. The order belongs to Priya.sends a page that says not found
  3. Error. The database does not answer.sends the order page
The error leads to the same line as the pass, so the order page fails open.

An attacker can cause the error with many requests sent together (Limits on what a request can use).

The safer catch block

The safer function adds one line to the catch block, the third line of the four:

    except Exception:
        log_error("ownership check failed")
        return error_page()
    return order_page(order_id)

The new line sends an error page and ends the function, so the last line never runs after an exception. An error now leads to a refusal, the same as a fail, and the order page fails closed.

Reading a catch block

A reviewer reads each catch block and asks what the program does next.

An empty catch block
The program carries on, and nothing records the error.
A catch block that writes to the log and carries on
The lines after the block use a value that was never set, or a check that never finished.
A catch block for every kind of exception
except Exception treats text that is not a number and a server with no memory left in the same way.

Some functions report an error by returning a value such as False. Code that never reads the returned value hides the error as well (Rules the code must enforce).

What is an error handler

A catch block does not cover every line of a program. The sports shop uses a framework named Flask. An error handler is one piece of code that receives every exception the rest of the code did not catch.

A stack trace lists the functions that were running when an error happened, with file names and line numbers. Look at what line 3 sends to the customer.

  1. @app.errorhandler(Exception)# tells Flask to run the function for every exception that no catch block caught
  2. def handle_error(error):# The parameter error holds the exception.
  3. return error_page(str(error) + traceback.format_exc())# sends the customer the message of the exception and the stack trace
str(error) is the message of the exception, and traceback.format_exc() is the stack trace.

A verbose error message shows a customer details of the code, such as a stack trace. The weakness is named generation of an error message containing sensitive information (CWE-209). An attacker causes an error on purpose, and the message can name the files, tables and queries the code uses.

The safer error handler

The safer error handler sends the details to the log and a fixed message to the customer. Look at lines 3, 4 and 5.

@app.errorhandler(Exception)
def handle_error(error):
    reference = new_reference()
    log_error(reference, error, request.path)
    return error_page("Something went wrong. Reference " + reference)

Line 3 makes a short random code called a reference. Line 4 writes the reference and the exception to the log, with request.path, the page the customer asked for. Line 5 sends the customer a fixed message and the reference.

  1. Something went wrong. Reference 8K2Q.the message the customer sees
  2. the three lines under the gap are the entry in the log
  3. ERROR reference=8K2Q path=/orderthe same reference, and the page
  4. TimeoutError: the database did not answerthe kind of exception and the message of the exception
  5. File "/srv/shop/orders.py", line 4, in show_orderthe stack trace
The customer gives the reference to the shop's staff, and the staff find the entry in the log.

Examples of what never goes to the customer

  • The kind of exception and the message of the exception, which can name a file, a table or a query.
  • A stack trace.
  • The names and IP addresses of the shop's own servers.
  • A different message for each cause of a failed sign-in, such as No account with that username and Wrong password. The two messages tell an attacker which usernames are real (Signing in).

An application with no error handler uses the error page of the framework. In debug mode, the framework's page shows the stack trace (Framework configuration).

Examples of what to look for

  • A catch block around a sign-in check or an ownership check, with no line that ends the request.
  • A catch block that is empty, or that writes to the log and carries on.
  • A message to the customer built from an exception, such as str(error) in Python or err.stack, the stack trace in JavaScript.
  • An application with no error handler, where debug mode can be on in production.
  • A different error message for each cause on a sign-in page.
  • A function that returns False for an error, and code that never reads the returned value.
  • A JavaScript promise whose error no code catches.

Check your understanding

  1. Name two things that an error message to a customer never contains.

    Show the answer

    A stack trace and the message of the exception. The names and IP addresses of the shop's own servers also count.

  2. The database does not answer line 4 of show_order. Which lines let Sam's request carry on to Priya's order?

    Show the answer

    Lines 7 and 8, the catch block. The catch block writes to the log and does not end the request, so line 9 sends the order page.

  3. Give one reason why a security check must fail closed.

    Show the answer

    A check that fails open treats an error as a pass. An attacker who can cause an error then gets past the check.

Practise it

Challenges with a weakness this lesson teaches.