PHP Паровой бот - Как войти на страницу с помощью RSA


Я пытался создать простого бота Steam для отправки объявлений в группу Steam, войдя на страницу Steam, а затем отправив уведомление. Я застрял при входе в систему. Вот что у меня есть:

include('Math/BigInteger.php');    
include('Crypt/RSA.php');
$url = 'http://store.steampowered.com/login/getrsakey/';    // here I get public key
$data = array('username' => 'user');         // I'm sending username by POST method

$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data),
    ),
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$result = json_decode($result)

// And this is part that don't work:

$rsa = new Crypt_RSA();
$key = array(
    'n' => new Math_BigInteger($result->publickey_mod,16),
    'e' => new Math_BigInteger($result->publickey_exp,2)
);
$rsa->loadKey($key);
$password = $rsa->encrypt("password");    // encrypting password
$data = array(
    'username' => 'user',
    'password' => $password,
    'twofactorcode'=> "",
    'emailauth'=> "", 
    'loginfriendlyname'=> "", 
    'captchagid'=> "", 
    'captcha_text'=> "", 
    'emailsteamid'=> "", 
    'rsatimestamp'=> $result->timestamp, 
    'remember_login'=> "false" 
);
$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data),
    ),
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

И результат:

{"success":false}

Проблема в том, что зашифрованный пароль выглядит не так, как когда я зашифровал его с помощью функций javascript, которые используются Steam. Поэтому я попытался зашифровать пароль в javascript, а затем просто вставить его в PHP-код, но это не сработало либо.

Буду признателен за любую помощь.

Author: neubert, 2014-11-23

1 answers

Первоначально я пришел сюда, чтобы найти ответы на свои собственные вопросы, но я был разочарован, увидев, что НИКТО официально не дал ответа на этот вопрос. Итак, после использования приведенной здесь информации, чтобы указать себе правильное направление, я работал над этим около часа и, наконец, заставил это работать на себя.

Для того, чтобы это сработало, все, что вам нужно сделать, это загрузить zip-файл здесь: https://github.com/phpseclib/phpseclib . Извлеките его на свой сервер/ каталог приложений и используйте следующий код ниже.

<?php
include('Math/BigInteger.php');    
include('Crypt/RSA.php');
define('CRYPT_RSA_PKCS15_COMPAT', true);  // May not be necessary, but never hurts to be sure.

$url_rsa = 'https://steamcommunity.com/login/getrsakey/?username=';
$username = "";  // Insert bot's username here.
$password = "";  // Insert bot's password here.


// Skip the extra work of POST'ing the data, just GET'ing the url works fine and saves space
$result = file_get_contents($url_rsa . $username);
$result = json_decode($result);

/*if ($result->success){
    echo "Got Info!<br/><br/>";
} else if (!$result->success){            // Remove comment markers during testing
    echo "Unable to grab Info<br/><br/>"; // You can also use this to log errors to a database or email you if needed.
}*/

//echo var_dump($result);
// More testing code, just to help you see what's going on.
//echo "<br/><br/>";

$rsa = new Crypt_RSA();
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$key = array(
    'n' => new Math_BigInteger($result->publickey_mod,16),
    'e' => new Math_BigInteger($result->publickey_exp,16) // Fixed base :)
);
$rsa->loadKey($key);
$password = base64_encode($rsa->encrypt($password)); // Steam uses Base64_Encode()

//echo "Password Encrypted: " . $password . "<br/><br/>";
// Should look like numbers and letters, any 'weird' characters shouldn't be here

$data = array(
    'username' => $username,
    'password' => $password,
    'twofactorcode'=> "",
    'emailauth'=> "", 
    'loginfriendlyname'=> "", 
    'captchagid'=> "",         // If all goes well, you shouldn't need to worry
    'captcha_text'=> "",       // about Captcha.
    'emailsteamid'=> "", 
    'rsatimestamp'=> $result->timestamp, 
    'remember_login'=> "false" 
);
$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data),
    ),
);

$url="https://steamcommunity.com/login/dologin/";

$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
$result = json_decode($result);

//echo var_dump($result);
// Hopefully everything went O.K. and you should be able pull out tokens
// for usage in your application.
?>

Результаты должны быть примерно такими:

{
    "success":true,
    "requires_twofactor":false,
    "login_complete":true,
    "transfer_urls":["https:\/\/store.steampowered.com\/login\/transfer","https:\/\/help.steampowered.com\/login\/transfer"],
    "transfer_parameters":{
        "steamid":"XXXXXXXXXXXXXXXXX",
        "token":"Combination of Letters and Numbers",
        "auth":"Looks like a Hash Here",
        "remember_login":false,
        "token_secure":"More Letters and Numbers"
    }
}

При создании бота, особенно такого, которому можно доверить хранение ценных предметов людей (как и большинству ботов), рекомендуется использовать очень безопасный пароль.

Хорошим форматом для использования был бы пароль длиной около 20 символов, содержащий цифры, буквы и некоторые символы. Хорошим сайтом, который генерирует пароли НА СТОРОНЕ КЛИЕНТА, является http://passwordsgenerator.net . Следуйте рекомендациям, перечисленным на веб-сайте, чтобы обеспечить безопасность ваших учетных записей.

 1
Author: Mick Ashton, 2016-03-12 02:51:27