Skip to content

Instantly share code, notes, and snippets.

@Mikulas
Last active December 16, 2015 22:49
Show Gist options
  • Save Mikulas/5509496 to your computer and use it in GitHub Desktop.
Save Mikulas/5509496 to your computer and use it in GitHub Desktop.
PHP bruteforce
<?php
require __DIR__ . '/permute.php';
define('CONCURRENCY', 20);
$descriptors = [
0 => ["pipe", "r"],
1 => ["pipe", "w"],
2 => ["pipe", "w"],
];
$queue = [];
$last_pass = $charset[0];
for ($i = 0; $i < CONCURRENCY; ++$i) {
addWorker();
}
while (TRUE) {
foreach ($queue as $i => $node) {
list($proc, $stream, $pass) = $node;
if ($res = fread($stream, 1)) {
if ($res === '1') {
file_put_contents('password_' . time(), "$pass\n");
echo "PASSWORD FOUND: `$pass`\n";
die;
}
proc_close($proc);
unset($queue[$i]);
//echo "worker ended, add new one\n";
addWorker();
}
}
//echo "pool contains " . count($queue) . " workers\n";
}
function addWorker()
{
global $last_pass;
global $queue;
$next = nexts($last_pass);
var_dump("Adding worker for $last_pass");
$queue[] = testPassword($next);
$last_pass = $next;
}
function testPassword($pass)
{
global $descriptors;
$pipes = [];
$proc = proc_open("php test_pass.php $pass", $descriptors, $pipes);
stream_set_blocking($pipes[0], 0);
stream_set_blocking($pipes[1], 0);
stream_set_blocking($pipes[2], 0);
return [$proc, $pipes[1], $pass];
}
<?php
$charset = str_split("abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
test('a', 'b');
test('Z', 'aa');
test('aZ', 'ba');
test('ZZ', 'aaa');
$str = $charset[0];
for ($i = 0; $i < 1e10; $i++) {
echo "$str\n";
$str = nexts($str);
}
function nexts($string)
{
global $charset;
$l = strlen($string);
$moved = FALSE;
foreach (array_reverse(str_split($string)) as $i => $char) {
if ($char === end($charset)) {
$string[$l - $i - 1] = $charset[0];
} else {
$string[$l - $i - 1] = nextChar($string[$l - $i - 1]);
$moved = TRUE;
break;
}
}
if (!$moved) {
$string = str_repeat($charset[0], strlen($string) + 1);
}
return $string;
}
function nextChar($c)
{
global $charset;
return $charset[array_search($c, $charset) + 1];
}
function test($a, $b)
{
if ($o = nexts($a) !== $b) {
throw new Exception("next('$a') !== '$b' ('$o' returned)");
}
}
<?php
$pass = $argv[1];
// compute
sleep(mt_rand(1, 2));
$valid = mt_rand(1, 1000) === 500;
// end compute
// output
echo $valid ? "1\n" : "n\n";
@Mikulas
Copy link
Author

Mikulas commented May 3, 2013

Permutes $charset from length 1.

a, b, …, Z, aa, ab, …, aZ, ba, bb, …

Has constant memory usage (depending on current $str length). Lookup time of next permutation has O(n), n being the length of string permuted.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment