Skip to content
Race condition Write-up Intermediate

Is Math.random() Safe? from missing rate limit to bypass 2fa and possible sqli

The OTP generation endpoint lacked rate limiting and used Math.random() to generate codes, allowing an attacker to send many concurrent requests and receive duplicate OTPs. The phone number parameter was also vulnerable to SQL injection, potentially exposing OTPs for any user.

Yasser Mohammed Follow

Published on neroli.medium.com

First of all i wanted to thank you all for sharing my last write-up and I got a lot of positive responses so I decided to write about another nice finding that i found lately.

Yasser Ali (@n3r0li), on neroli.medium.com

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 6 min read.

Context

I was testing a mobile application written in React-Native for a private program on HackerOne about five months before writing this up. The feature in question is the OTP confirmation flow: the application asks the user to confirm a one-time code that has been sent to their phone number. The same endpoint was responsible for all the OTP generation in the whole application, so it covered 2FA, number confirmation, reset password and similar flows.

Server-side testing did not turn up a lot of functions. The thread that led to the finding came from my own work on a similar application as a school project, where I ran into synchronisation problems. That made me look at the 2FA functionality with a specific question in mind: what happens to the back end if we send a lot of requests?

Setup

The testing was done against the private HackerOne program's mobile application. The tools used were Burp Suite with the Intruder, and later Turbo Intruder with the race condition script from the Turbo Intruder examples. The OTPs were sent to my own phone number.

Finding it

Using the Intruder I sent a lot of requests and waited for the corresponding messages to fill my phone with many OTPs. I got a lot of confirmation codes back. On its own this is a missing rate limit, and I would not have submitted it without a higher impact scenario.

What turned the missing rate limit into something more interesting was a memory from my own development work: I had used Math.random() to generate these codes. That raised the question of whether the codes are really that random.

Pseudo-randoms

We cannot generate pure random numbers, since many factors affect the randomisation process and can make it predictable. That is what is called pseudo-random: unpredictable, but not impossible, because it depends on something called a seed. If two duplicate seeds are inserted into Math.random, the same sequence comes out.

So if I could use the seed and send the request at the same time, I would be able to guess the OTP. That is very hard to implement, because it depends on the system clock on the server and on my own system clock.

Synchronous vs asynchronous

The server was using asynchronous functions to handle our requests. In short, synchronous code runs in order. Given this code:

JavaScript
const second = () => {  console.log('Hello there!');}const first = () => {  console.log('Hi there!');  second();  console.log('The End');}first();

the output is:

Text
Hi there!Hello there!The End

because the call stack executes function first and stops until the code in function second has executed, then goes back to execute the rest of function first. In asynchronous code, two functions can be executed in parallel with no blocking.

Exploitation

The answer here is a race condition. Using Turbo Intruder in Burp with the race condition script, I could send multiple requests at the same time so that they would be executed on the server at the same time. That calls Math.random() many times, which can give a duplicate result if the length of the result is not too long.

A sample of vulnerable code written in nodejs:

JavaScript
var http = require("http");async function asyncCall() {var x = Math.floor(Math.random() * 1000).toString();return x;}http.createServer(function (request, response) {response.writeHead(200, {'Content-Type': 'text/plain'});asyncCall().then((value) =>{console.log(value);response.end(value);});}).listen(8081);

With this sample Turbo Intruder script:

Python
def queueRequests(target, wordlists):    engine = RequestEngine(endpoint=target.endpoint,                           concurrentConnections=30,                           requestsPerConnection=100,                           pipeline=False                           )    for i in range(30):        engine.queue(target.req, "", gate='race1')    engine.openGate('race1')engine.complete(timeout=60)def handleResponse(req, interesting):    table.add(req)

we will notice that we got duplicate numbers.

Step by step against the target

  1. Send a large number of OTP confirmation requests with the Intruder to observe the missing rate limit and collect the codes that arrive on the phone.
  2. Switch to Turbo Intruder with the race condition script, so that the requests are queued behind a gate and released together. The concurrentConnections=30, requestsPerConnection=100 and pipeline=False settings in the sample script control how the requests are spread, and engine.openGate('race1') releases the queued requests at once.
  3. Because the requests are handled by asynchronous functions on the server, they execute in parallel, and Math.random() is called many times in a short window. With a short enough result, duplicate values appear.

Applying these steps on the target exposed the generated OTP code. The reason we got a valid code is that the query inserts our user_id, which is the primary key in this case, so we got a valid OTP.

From the original on neroli.medium.com
SQL error

SQL error

I also noticed that the phone number was not being validated well, which led to SQL injection.

Or watch on YouTube
From the original on neroli.medium.com

Root cause

Two weaknesses combine. First, the OTP endpoint had no effective rate limit, so an attacker can drive as many OTP generations as they like. Second, the codes were generated with Math.random(), a pseudo-random generator, and the server handled requests asynchronously, so a burst of concurrent requests can call the generator many times and produce duplicate codes. The race condition script turns the missing rate limit into the ability to call the generator many times within the same window.

The SQL injection comes from the phone number not being validated well before it reaches the query. The endpoint was responsible for all OTP generation in the application, so the same input path is shared by 2FA, number confirmation and reset password.

Impact

The race exposed a valid OTP for the flow, which matters because the same endpoint backs 2FA, phone number confirmation and password reset. The SQL injection from the poorly validated phone number gives a second path into the same endpoint. The report does not give a bounty figure or a severity rating.

The attack depends on several things: the length of the OTP, internet connection speed, the number of requests, the number of concurrent connections and the back-end framework. The OWASP slide on concurrency vulnerabilities is useful for understanding the attack further.

Fix

The report does not describe a fix that was applied. What the finding calls for is rate limiting on OTP generation and confirmation, a cryptographically secure random source instead of Math.random(), and proper validation of the phone number before it reaches the query.

Variants to test

  • OTP endpoints with no rate limit: send a burst and see whether the same code arrives more than once for the same account.
  • OTP generation built on Math.random() with a short code length: run the race script against the generation endpoint and look for duplicate codes in the responses.
  • Asynchronous back ends: check whether the framework handles requests in parallel, since that is the precondition for the race to produce duplicates.
  • Phone number or identifier fields that reach a query: submit malformed values and watch for SQL errors in the response.
  • Shared OTP endpoints: if one endpoint serves 2FA, confirmation and reset, test each flow, since a weakness in the shared path affects all of them.

References

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 12 min read.

What happened, in plain words

A security researcher was testing a mobile app for a private bug bounty program on HackerOne. The app was built with React-Native, a framework for writing phone apps in JavaScript. The feature he looked at was the one-time code (OTP) that the app sends to your phone so you can prove the phone is yours. The same piece of server code produced the codes for every flow in the app: two-factor login, confirming a phone number, resetting a password.

He sent a large number of requests to that code and his phone filled up with codes. On its own, that is a missing rate limit: the server does not stop you asking for codes again and again. He would not have reported just that. But he remembered that when he built a similar app for a school project he had used Math.random(), a JavaScript function for producing random-looking numbers, to make the codes. That function is not truly random. If the server calls it many times in the same instant, it can hand out the same number twice. So he used a tool that fires many requests at exactly the same moment (a race condition) and got a valid OTP. He also found that the phone number field was not checked properly, which led to a SQL injection, a way of slipping database commands into a form field.

This article walks through the same story from zero: what each term means, what he did, and why.

The target and the feature

The app was a mobile application written in React-Native, tested for a private program on HackerOne about five months before the write-up. A private program is a bounty program you can only join by invitation, so the details stay closed.

The feature is the OTP confirmation flow. OTP stands for one-time password: a short code, usually a few digits, that the server sends to your phone by SMS and that you type back into the app. It proves you hold the phone number. The important detail is that one endpoint served all OTP generation in the whole application, covering 2FA (two-factor authentication, the second step at login), phone number confirmation, password reset and similar flows. An endpoint is simply a URL on the server that the app talks to; think of it as a service window in a building, where you hand over a form and get an answer back.

Server-side testing (testing the server directly rather than through the app's screens) did not turn up many functions. The idea that led to the finding came from the researcher's own school project, where he had run into synchronisation problems. That made him ask a specific question about the 2FA feature: what happens to the back end if we send a lot of requests?

Setup

The testing was done against the private program's mobile application. The tools were Burp Suite with the Intruder, and later Turbo Intruder with the race condition script from the Turbo Intruder examples. Burp Suite is a program that sits between your browser or phone and the server, so you can see and change every request. The Intruder is the part of Burp that repeats a request many times, with variations. Turbo Intruder is an extension built for sending very large numbers of requests very fast. The OTPs were sent to his own phone number.

Finding it

The app asked him to confirm the OTP that had been sent to his phone number. Using the Intruder he sent a lot of requests and waited for the messages to fill his phone with many OTPs. He got a lot of confirmation codes back. On its own this is a missing rate limit, and he would not have submitted it without a higher impact scenario. A rate limit is a cap on how often you may do something, like a ticket machine that only sells you one ticket per minute; without it, you can ask as often as you like.

What made the missing rate limit more interesting was a memory from his own development work: he had used Math.random() to generate these codes. That raised the question of whether the codes are really that random.

Pseudo-randoms

We cannot generate pure random numbers, because many factors affect the randomisation process and can make it predictable. That is what is called pseudo-random: unpredictable, but not impossible, because it depends on something called a seed. A seed is the starting value a random generator is fed; the same seed produces the same sequence of numbers, like a recipe that always gives the same cake if you start with the same ingredients. If two duplicate seeds are inserted into Math.random, the same sequence comes out.

So if he could use the seed and send the request at the same time, he would be able to guess the OTP. That is very hard to implement, because it depends on the system clock on the server and on his own system clock. The attack depends on the system clock on the server and on his own system clock.

Synchronous vs asynchronous

The server was using asynchronous functions to handle requests. In short, synchronous code runs in order. Given this code:

JavaScript
const second = () => {  console.log('Hello there!');}const first = () => {  console.log('Hi there!');  second();  console.log('The End');}first();

Line by line: const second = () => { ... } defines a small function named second that prints Hello there!. const first = () => { ... } defines a function named first that prints Hi there!, then calls second(), then prints The End. The final first(); runs first. Because the code is synchronous, the call to second() must finish before the next line of first runs, so the output is:

Text
Hi there!Hello there!The End

In other words, the call stack (the list of functions currently running) executes function first and stops until the code in function second has executed, then goes back to execute the rest of function first. In asynchronous code, two functions can be executed in parallel with no blocking. Think of a single shop assistant serving customers one at a time (synchronous) versus several assistants serving at once (asynchronous).

Exploitation

The answer here is a race condition. A race condition is when two things happen at the same moment and the result depends on which one gets there first, like two people grabbing the last seat on a train. Using Turbo Intruder in Burp with the race condition script, he could send multiple requests at the same time so that they would be executed on the server at the same time. That calls Math.random() many times, which can give a duplicate result if the length of the result is not too long. A short code has fewer possible values, so two calls are more likely to land on the same one.

A sample of vulnerable code written in nodejs:

JavaScript
var http = require("http");async function asyncCall() {var x = Math.floor(Math.random() * 1000).toString();return x;}http.createServer(function (request, response) {response.writeHead(200, {'Content-Type': 'text/plain'});asyncCall().then((value) =>{console.log(value);response.end(value);});}).listen(8081);

Line by line: var http = require("http"); loads Node's built-in web server module. async function asyncCall() { ... } declares an asynchronous function. Inside it, var x = Math.floor(Math.random() * 1000).toString(); takes a random number between 0 and 1, multiplies it by 1000, rounds it down to a whole number, and turns it into text. return x; hands that value back. http.createServer(function (request, response) { ... }) creates a server that runs the inner function for every incoming request. response.writeHead(200, {'Content-Type': 'text/plain'}); sets the reply status to 200 (OK) and says the body is plain text. asyncCall().then((value) =>{ ... }); calls the async function and, when it finishes, runs the arrow function with the result. Inside that, console.log(value); prints the value on the server console and response.end(value); sends it back to the caller. Finally .listen(8081); makes the server listen on port 8081. The point of the sample is that the code is asynchronous and the random value is short, so many simultaneous requests can produce the same value.

With this sample Turbo Intruder script:

Python
def queueRequests(target, wordlists):    engine = RequestEngine(endpoint=target.endpoint,                           concurrentConnections=30,                           requestsPerConnection=100,                           pipeline=False                           )    for i in range(30):        engine.queue(target.req, "", gate='race1')    engine.openGate('race1')engine.complete(timeout=60)def handleResponse(req, interesting):    table.add(req)

Line by line: def queueRequests(target, wordlists): defines the function Turbo Intruder calls to prepare the attack. engine = RequestEngine(...) creates the engine that will send the requests. endpoint=target.endpoint points it at the target URL. concurrentConnections=30 says to open 30 connections at once. requestsPerConnection=100 says to send up to 100 requests on each connection. pipeline=False turns off HTTP pipelining, a technique of sending several requests without waiting for replies. for i in range(30): loops 30 times. engine.queue(target.req, "", gate='race1') puts the request into a queue behind a gate named race1; nothing is sent yet. engine.openGate('race1') opens the gate, releasing all queued requests together. engine.complete(timeout=60) waits up to 60 seconds for everything to finish. def handleResponse(req, interesting): defines what to do with each reply, and table.add(req) adds it to the results table. The gate is the trick: it holds the requests back so they all leave at the same instant.

With this, we will notice that we got duplicate numbers.

Step by step against the target

  1. Send a large number of OTP confirmation requests with the Intruder to observe the missing rate limit and collect the codes that arrive on the phone.
  2. Switch to Turbo Intruder with the race condition script, so that the requests are queued behind a gate and released together. The concurrentConnections=30, requestsPerConnection=100 and pipeline=False settings in the sample script control how the requests are spread, and engine.openGate('race1') releases the queued requests at once.
  3. Because the requests are handled by asynchronous functions on the server, they execute in parallel, and Math.random() is called many times in a short window. With a short enough result, duplicate values appear.

Applying these steps on the target exposed the generated OTP code. The reason we got a valid code is that the query inserts our user_id, which is the primary key in this case, so we got a valid OTP. A primary key is the column in a database table that uniquely identifies a row, like a student number; if the code is tied to your own user_id, the code that comes back is valid for your account.

From the original on neroli.medium.com
SQL error

SQL error

He also noticed that the phone number was not being validated well, which led to SQL injection. SQL injection means putting database commands into a field the server trusts, so the database runs them.

Or watch on YouTube
From the original on neroli.medium.com

Root cause

Two weaknesses combine. First, the OTP endpoint had no effective rate limit, so an attacker can drive as many OTP generations as they like. Second, the codes were generated with Math.random(), a pseudo-random generator, and the server handled requests asynchronously, so a burst of concurrent requests can call the generator many times and produce duplicate codes. The race condition script turns the missing rate limit into the ability to call the generator many times within the same window.

The SQL injection comes from the phone number not being validated well before it reaches the query. The endpoint was responsible for all OTP generation in the application, so the same input path is shared by 2FA, number confirmation and reset password.

Impact

The race exposed a valid OTP for the flow, which matters because the same endpoint backs 2FA, phone number confirmation and password reset. The SQL injection from the poorly validated phone number gives a second path into the same endpoint. The report does not give a bounty figure or a severity rating.

The attack depends on several things: the length of the OTP, internet connection speed, the number of requests, the number of concurrent connections and the back-end framework. The OWASP slide on concurrency vulnerabilities is useful for understanding the attack further.

Fix

The report does not describe a fix that was applied. What the finding calls for is rate limiting on OTP generation and confirmation, a cryptographically secure random source instead of Math.random(), and proper validation of the phone number before it reaches the query.

Variants to test

  • OTP endpoints with no rate limit: send a burst and see whether the same code arrives more than once for the same account.
  • OTP generation built on Math.random() with a short code length: run the race script against the generation endpoint and look for duplicate codes in the responses.
  • Asynchronous back ends: check whether the framework handles requests in parallel, since that is the precondition for the race to produce duplicates.
  • Phone number or identifier fields that reach a query: submit malformed values and watch for SQL errors in the response.
  • Shared OTP endpoints: if one endpoint serves 2FA, confirmation and reset, test each flow, since a weakness in the shared path affects all of them.

References

Glossary

  • API: a set of URLs on a server that an app talks to, like a service counter where you hand over a request and get an answer.
  • Asynchronous: code that can run several tasks in parallel without waiting for each to finish, like several shop assistants serving at once.
  • Burp Suite: a tool that sits between your browser or phone and the server so you can see and change requests.
  • Call stack: the list of functions a program is currently running, in order.
  • Concurrent connections: several network connections open at the same time.
  • Endpoint: a specific URL on a server that handles one kind of request.
  • Gate: a Turbo Intruder feature that holds requests back until released, so they all leave together.
  • HackerOne: a platform where companies run bug bounty programs and researchers report vulnerabilities.
  • Intruder: the part of Burp Suite that repeats a request many times, with variations.
  • Math.random(): a JavaScript function that returns a pseudo-random number between 0 and 1.
  • Missing rate limit: no cap on how often a user may perform an action, so they can repeat it as much as they like.
  • Node.js: a way of running JavaScript on a server.
  • OTP: one-time password, a short code sent to your phone that you type back to prove you hold the number.
  • Pipelining: sending several HTTP requests on one connection without waiting for each reply.
  • Primary key: the column in a database table that uniquely identifies each row.
  • Private program: a bug bounty program you can only join by invitation.
  • Pseudo-random: numbers that look random but come from a repeatable process, so the same seed gives the same sequence.
  • Race condition: when two actions happen at the same moment and the result depends on which gets there first.
  • React-Native: a framework for writing mobile apps in JavaScript.
  • Seed: the starting value fed to a random generator; the same seed produces the same sequence.
  • SQL injection: slipping database commands into a field the server trusts, so the database runs them.
  • Synchronous: code that runs in order, one step finishing before the next starts.
  • Turbo Intruder: a Burp Suite extension for sending very large numbers of requests very fast.
  • Two-factor authentication (2FA): a second step at login, such as a code sent to your phone.

More by Yasser Mohammed

View all

3 more disclosed reports, best first.

Similar reports

View all

Same bug class and techniques, clearest first.

Race conditions

The lesson behind this report.

Parallel requests reach a state the code assumed could not happen: a coupon used twice, a limit overrun, a check skipped.