What is the significance of including a "sleep" function in order to achieve a successful constant time attack?

On the webpage , the author provides an explanation of what a constant time attack is and how to protect against it.

However, when looking at the code created by the author:

# secret.py
from time import sleep # Used to exaggerate time difference.
from sys import argv   # Used to read user input.

def is_equal(a,b):
    """Custom `==` operator"""
    # Fail if the strings aren't the right length
    if len(a) != len(b):
        return False

    for i in range(len(a)):
        # Short-circuit if the strings don't match
        if a[i] != b[i]:
            return False

        sleep(0.15) # This exaggerates it just enough for our purposes

    return True

# Hard-coded secret globals FOR DEMONSTRATIONS ONLY
secret = 'l33t'

# This is python for "If someone uses you as a script, do this"
if __name__ == '__main__':

    try:
        // The user got it right!
        if is_equal(str(argv[1]), secret):
            print('You got the secret!')

        # The user got it wrong
        else:
            print('Try again!')

    # The user forgot to enter a guess.
    except IndexError:
        print('Usage: python secret.py yourguess\n' \
             +'The secret may consist of characters in [a-z0-9] '\
             +'and is {} characters long.'.format(len(secret)))

I am confused about the necessity of adding the following line to ensure the success of the constant time attack:

sleep(0.15) # This exaggerates it just enough for our purposes

The author of the website mentions that:

this exaggerates the time it takes to evaluate the is_equal function.

After running some tests, it appears that a "sleep" function is necessary for the successful execution of this attack. What could be the reason behind needing to delay the process? Is it only used for demonstration purposes?

Answer №1

Update 1:

Why is it necessary to exaggerate the time?

The reason for exaggerating the time is to highlight the difference in timing when two characters match versus when they don't. In this scenario, if the first character of strings a and b match, the code will pause briefly before checking the next character. If there is a mismatch at any point, the function will return immediately. This intentional delay helps demonstrate that matching characters take longer to process compared to non-matching ones.

To avoid this timing vulnerability, the is_equal function should be designed so that its response time remains consistent regardless of input.

In your provided example:

def is_equal(a,b):
    _is_equal = True

    if len(a) != len(b):
        return False

    for i in range(len(a)):
        if a[i] != b[i]:
            _is_equal = False

    return _is_equal

Alternatively, you can utilize the built-in secrets module function compare_digest() which addresses this issue.

Answer №2

When navigating through the "match" loop, there are two distinct paths that can be taken:

for i in range(len(a)):
    # Check if the strings do not match and exit if they don't
    if a[i] != b[i]:
        return False

    sleep(0.15) # Intentionally exaggerating for our purpose
    return True
  1. If a[i] != b[i] results in True, indicating no match, the function exits.
  2. If a[i] != b[i] results in False, indicating a match, it proceeds to Sleep(0.15) before exiting the function.

The deliberate delay of Sleep(0.15) when characters match introduces a significant time gap between these two paths. This allows for the simple use of the maximum timing of all attempts to determine the correct character of the secret. Without this intentional delay, one would need to search for statistically significant differences in matching times.

The author noted this insight as follows:

Most crucially [for the author], there is no requirement to employ advanced statistical methods to decipher the secret by evaluating each input multiple times and analyzing the timing data. It naturally takes approximately ten times longer to evaluate a matching letter than a non-matching letter.

To observe the disparity in timings with and without the sleep command, utilize debug lines.

# Uncomment the following line for debugging output
print('max {} min {}'.format(max(guess_times), min(guess_times)))

# Include this line to view the full guess_times list    
print(['{:.2f}'.format(elem) for elem in guess_times])

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

My locale NUXT JavaScript files are being blocked by Content Security Policy

I've been working on implementing CSP headers for my website to ensure data is loaded from trusted sources. However, I'm facing an issue where CSP is blocking my local JS files. Here's a snippet from my nuxt.config.js: const self = 'lo ...

Invoke a Python function from JavaScript

As I ask this question, I acknowledge that it may have been asked many times before. If I missed the answers due to my ignorance, I apologize. I have a hosting plan that restricts me from installing Django, which provided a convenient way to set up a REST ...

Implementing CSRF token for the current window's location

Is there a way to add a CSRF token to all instances where window.location.href is used in my Javascript code? It's not possible to override the window.location object and its properties like window.location.href. Creating a universal function to inc ...

NodeJS guide: Enabling cross-domain access for web services

Currently, I am developing a nodejs server and facing the challenge of needing to access additional services through ajax from a different domain. Can anyone provide guidance on how to bypass the cross-domain restriction within nodejs code? Please note th ...

Is JavaScript still running despite not displaying insecure items due to IE 8 security warning?

After a user completes a transaction on my site, the confirmation page displays Google conversion tracking code in a small JavaScript snippet. This code is located on my Wordpay callback page, which pulls data from the regular site (HTTP) to the Worldpay s ...

Error message stating that there is no property 'collection' in Firestore when using Firebase v9 modular syntax in Firebase Firestore

Working on a React application that makes use of Firebase Firestore for handling database operations, I recently upgraded to Firebase version 9 and adopted the modular syntax for importing Firebase services. Nevertheless, when attempting to utilize the co ...

Button click event is not being triggered by Ajax rendering

I am facing an issue with my Django template that showcases scheduled classes for our training department. Each item in the list has a roster button which, when clicked, should display the class roster in a div. This functionality works perfectly. However, ...

How can I protect my jQuery script from being accessed by "FIREBUG"?

I was tasked with creating a jQuery script as follows: function DeleteFile(_FileID) { //ajax method to delete the file } The FileID is stored in the 'rel' attribute of the list. However, when I call "DeleteFile" from Firebug using the fileId ...

Executing a JavaScript code in a Python webdriver: A step-by-step guide

Using Selenium 2 Python webdriver: I encountered an issue where I needed to click on a hidden element due to a hover effect. In search of solutions to unhide and select the element, I came across the following examples: Example in Java: JavascriptExecut ...

Tips on securely saving passwords using Greasemonkey

Created a custom userscript that prompts users to save their login credentials in order to avoid entering them repeatedly. Familiar with using localStorage.setItem() to store key-value pairs, but concerned about storing passwords in clear text. Seeking ad ...

What's the best way to determine which of the two forms has been submitted in Django?

On my homepage, I have both a log_in and sign_up form. Initially, the log_in form is displayed by default, but when a user clicks on the Sign Up button, the sign_up form appears. These toggles switch depending on which button the user clicks. from django ...

Encountered CSRF validation error while working with a Python Django backend in conjunction with React frontend using Axios for making POST requests

I recently completed a tutorial at and now I'm attempting to add a POST functionality to it. Despite obtaining the csrf from cookies and including it in the "csrfmiddlewaretoken" variable alongside a test message in json format for the axios function ...

Exploring the capabilities of arrays within Ajax

Below is the original code I wrote in JavaScript: var wt_val = []; for (i = 0; i<human_wt.length; i++){ var mult; mult = data_list[basket_list[button_port_name][i]].map(x => x*(wt[i]/100)); wt_val.push(mult); ...

What is the reason behind Angular not allowing users to define @Output events that begin with 'on'?

While developing a component, I defined an output EventEmitter named onUploaded. However, Angular flagged an error instructing me to use (uploaded) instead. This restriction is due to security concerns, as bindings starting with 'ono' pose risks. ...

Learn how to retrieve values from a .json file in real-time and then perform comparisons with user input using Python

I have a JSON file structured like this: [ { "name": { "common": "Aruba", "official": "Aruba", "native": { "nld": { "official ...

Flask does not provide a direct boolean value for checkboxes

After struggling for a week, I am still lost on where to make changes in my code. I need the checkbox to return a boolean value in my Flask application. Below are snippets of the relevant code: mycode.py import os, sqlite3 from flask import Flask, flash ...

Can anyone suggest a method to block the execution of Javascript commands in the console?

Regarding the inquiry mentioned in the question title. Is it possible to prevent individuals from executing functions on my webpage using the console, even though it is not necessary? I have experimented with various methods, and the code below represent ...