How do I get information for Twitter accounts?

Asked

Viewed 263 times

0

Yesterday I did this question here in the Sopt, I am now following what the Inkeliz Said:

Cookies will only be obtained if you make the request using login/password. To do this just enter the Twitter page see what is the URL called (ie F12 > Network) and request using Curl, it is able to send the same information to the browser. The official Twitter API does not use cookies, because getting other people’s login/password is not safe, so there is Oauth, officially made available by Twitter.

The question is, how can I do this? Could I do it using Twitteroauth?

Someone would give an example of how to make this request, using F12 > Tetwork?

My authentication code is this:

<?php

class Auth {

    public function signedIn() {

        if (isset($_SESSION['twitter_access_token'])) {
            $access_token = $_SESSION['twitter_access_token'];

            $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);

            $user = $connection->get('account/verify_credentials');

            return $user;
        }

        return false;
    }

    public function getAuthUrl() {

        $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);

        $request_token = $connection->getRequestToken(OAUTH_CALLBACK);

        if($request_token){
            $token = $request_token['oauth_token'];

            $_SESSION['oauth_token'] = $token ;
            $_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];

            $auth_url = $connection->getAuthorizeURL($token);
        }

        return $auth_url;
    }

    public function getAccessToken() {

        $request_token = [];
        $request_token['oauth_token']           = $_SESSION['oauth_token'];
        $request_token['oauth_token_secret']    = $_SESSION['oauth_token_secret'];

        if (isset($_GET['oauth_token']) && $request_token['oauth_token'] !== $_GET['oauth_token']) {
            die('Error: Something went wrong...');
        }

        $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $request_token['oauth_token'], $request_token['oauth_token_secret']);

        $access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);

        if (empty($access_token)) {
            die('Error: Invalid access token...');
        }

        return $access_token;
    }

    public function logout() {
        session_destroy();
        header('Location:' . URL_BASE);
    }

}

The question now is as follows, how to obtain the data by comparing user = oauth_token and password = oauth_token_secret and confirm on the form?

<form method="post">
  <div class="form-group">
    <input type="text" name="ttrUsername" placeholder="Usuário do Twitter" class="form-control">
  </div>
  <div class="form-group">
    <input type="password" name="ttrPassword" placeholder="Senha do Twitter" class="form-control">
  </div>

  <button type="submit" name="ttrSignin" class="btn btn-primary btn-block">
    <i class="fa fa-twitter"></i> Entrar agora
  </button>
</form>

This is my form:

inserir a descrição da imagem aqui

I got the following cURL

curl "https://twitter.com/"
-H "accept-encoding: gzip, deflate, br"

-H "accept-language: pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4"

-H "upgrade-insecure-requests: 1"

-H "user-agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36"

-H "accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"

-H "cache-control: max-age=0"

-H "authority: twitter.com"

-H "cookie: guest_id=v1^%^3A149848156157534036; privacy_2017=1; lang=pt; eu_cn=1; ct0=3dae64dcfd1d4e31e6b9f749eaff5f1c; _gat=1; ads_prefs=^\^"HBERAAA=^\^"; kdt=6F5z2H1dYzkK2dxVkhDommOOBWmYJiXTdCCbRZGE; remember_checked_on=1; twid=^\^"u=866687457990979584^\^"; auth_token=115ba1614d21781e601769c512a48bccc7bda89b; _ga=GA1.2.1124081759.1498481564; _gid=GA1.2.126286429.1498481564; _twitter_sess=BAh7CiIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNo^%^250ASGFzaHsABjoKQHVzZWR7ADoPY3JlYXRlZF9hdGwrCOgPduRcAToMY3NyZl9p^%^250AZCIlZWM4NWI1ZTZiMDk5Yzg4MDZmM2NhNGE4MTA5MGZmODY6B2lkIiVlM2I4^%^250AMTRmNDA4NTZlYTkyYzI1Y2Y3NDE1NTE2ZjYwYjoJdXNlcmwrCQCw1rCmFwcM--b7e62a94a232a36015e8959d2391af44b9b2b753"

-H "referer: https://twitter.com/login/error?redirect_after_login=^%^2F" --compressed

I made the following scheme, and is returning the twitter login page:

<?php

# First call gets hidden form field authenticity_token
# and session cookie
$ch = curl_init();
$sTarget = "https://twitter.com/";
curl_setopt($ch, CURLOPT_URL, $sTarget);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/cookie.txt");
curl_setopt($ch, CURLOPT_REFERER, "https://twitter.com/");
$html = curl_exec($ch);

# parse authenticity_token out of html response
preg_match('/<input type="hidden" value="([a-zA-Z0-9]*)" name="authenticity_token"\/>/', $html, $match);
$authenticity_token = $match[1];



$username = "[email protected]";
$password = "password";

# set post data
$sPost = "session[username_or_email]=$username&session[password]=$password&return_to_ssl=true&scribe_log=&redirect_after_login=%2F&authenticity_token=$authenticity_token";

# second call is a post and performs login
$sTarget = "https://twitter.com/sessions";
curl_setopt($ch, CURLOPT_URL, $sTarget);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $sPost);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/x-www-form-urlencoded"));

# display server response
curl_exec($ch);
curl_close($ch);
?>
  • 2

    I think my comment answers all the questions. First, what I mean by "F12 > Network" is that you see how the request is made, then redo it on Curl, including Chrome allows you to copy to "Copy All as Curl". You can also use Burp Suite... Oauth does not use login/password, instead uses a "token". Well, I believe your problem is that you don’t understand the basics of how HTTP requests work. Besides, if you knew what Oauth was, you’d know he was was made not to use login/password.

  • 1

    Well, I understand the basics and yes, I know it was done not to use login/password. I just wanted to know a way, how to do it... an example of code... simple as...

  • 1

    Vish this screen is the biggest fishery! You can not ask the credentials for the user, this is phishing (for example this would give you the power to access your users' account). Log in to a website via twitter to understand - you type your credentials in the twitter.com popup and never on the site you belong to. See the Twitter documentation for this. https://dev.twitter.com/web/sign-in/implementing

  • @rodorgas see, I edited the topic with the Curl that I picked with the tip of Inkeliz

  • 1

    Puts... changes your password bro, your twitter has been compromised. Do not put session cookie, this is secret. Seriously, read the charts, security is an area of computing that you can’t improvise.

  • Rlx, this account is released for general use... I created it on purpose. I made it to test...

  • edited the topic.

  • @rodorgas, would be able to inform me, how to use these cookies to post as they did in my account?

  • Because he posted his session cookie, whoever uses that cookie will hijack his session. See https://pt.wikipedia.org/wiki/Session_hijacking. You can change your session cookie in your browser settings.

  • @rodorgas I got, it is possible to make some script to follow the cookies and sessions saved in my database?

Show 5 more comments

1 answer

0


This answer is before editing, based on commenting.

If you want an example, then suppose you have website X, which uses this code:

<?php
/**
 * NÃO UTILIZE ESTE CÓDIGO EM PRODUÇÃO!
 */

session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    if (isset($_POST['nome'], $_POST['senha'], $_POST['csrf'], $_SESSION['csrf'])
        && hash_equals($_POST['csrf'], $_SESSION['csrf'])
    ) {

        if (hash_equals($_POST['senha'], '123456789')) {
            $_SESSION['nome'] = $_POST['nome'];
        }

    }

}


if ($_SERVER['REQUEST_METHOD'] === 'GET') {

    $_SESSION['csrf'] = $_SESSION['csrf'] ?? base64_encode(random_bytes(64));

    if (isset($_SESSION['nome'])) {

        echo 'Você está logado usando o nome de ', $_SESSION['nome'];

    } else {


        echo '<form method="post">';

        echo '<input name="nome" type="text" placeholder="Nome">';
        echo '<br>';
        echo '<input name="senha" type="password" placeholder="Senha">';
        echo '<br>';
        echo '<input name="csrf" type="hidden" value="' . $_SESSION['CSRF'] . '">';
        echo '<input name="enviar" type="submit">';

        echo '</form>';

    }

}

So he has three things:

  1. If it is POST and the correct login: sets the session.
  2. If it’s GET:

    1. Is connected (there is a session containing the Nome): shows your name.
    2. Disconnected: shows the form.

Assuming you know the basics of how HTTP works and that you understand Curl minimizing, then:

curl -X GET http://127.0.0.1/login.php -v

Will return the same result as when we access via browser, the most important in this case are two things:

< Set-Cookie: PHPSESSID=3qsmtd817pof4ucngd3f9tjf1e; path=/

This is cookie sent by the server to the client, then we have the input that contain the csrf-token, in:

<input name="csrf" type="hidden" value="6kYwBSjY8lfKcXefUau3r6apgcY3fsjEbEhiPjlt1lxZwXuwDzJeYh6F1WyW4q/kycj4/YczxHxXC0t0YtUmhg==">

But we still need to see where the data is sent, ignoring the html form, in the "Network" console when clicking "Send" it is shown which page is called and which method and which headers.

So we do the same in CURL:

curl ^
-X POST ^
-d "nome=Inkeliz&senha=123456789&csrf=6kYwBSjY8lfKcXefUau3r6apgcY3fsjEbEhiPjlt1lxZwXuwDzJeYh6F1WyW4q/kycj4/YczxHxXC0t0YtUmhg==" ^
-H "Cookie: PHPSESSID=3qsmtd817pof4ucngd3f9tjf1e" ^
http://127.0.0.1/login.php -v

Meanings:

  • -X defines the method (is redundant in this case!).
  • -d defines the "body" of the request, in this case it is a x-www-form-urlencoded.
  • -H sets the header, in the case of the previously obtained cookie.
  • -v displays the entire send and reply header and other information, such as Handshake in the case of HTTPS.

Now since we use the same cookie:

curl ^
-X GET ^
-H "Cookie: PHPSESSID=3qsmtd817pof4ucngd3f9tjf1e" ^
http://127.0.0.1/login.php

We will get:

Você está logado usando o nome de Inkeliz

How to do this in PHP there are two steps.

First we need to get the CSRF-Token (and the cookie, which has direct relation to the CSRF-Token):

$cookie = '';
$csrf = '';

$PegarCSRFToken = curl_init('http://127.0.0.1/login.php');

curl_setopt_array($PegarCSRFToken, [
        CURLOPT_CUSTOMREQUEST => 'GET',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HEADERFUNCTION => function($curl, $cabeçalho) use (&$cookie){

            if(stripos($cabeçalho, 'Set-Cookie:') === 0){
                if(preg_match('/Set-Cookie:\s?(.*?);/i', $cabeçalho, $matches)) {
                    $cookie .= $matches[1] . '; ';
                }
            }

            return strlen($cabeçalho);
        }
    ]
);

$PegarCSRFToken = curl_exec($PegarCSRFToken);

if(preg_match('/name="csrf".*?value="(.*?)"/', $PegarCSRFToken, $matches)){

    $csrf = $matches[1];

}

I believe he’s easy to understand, of course he can be improved, but the point is:

  1. It obtains the cookie and stores in $cookie using the CURLOPT_HEADERFUNCTION, extracting using preg_match in the Set-Cookie: sent by server.

  2. It obtains the CSRF-Token using the preg_match in the page output, in the HTML itself.

Now, with both contents in hand we can log in:

$EnviarLoginSenha = curl_init('http://127.0.0.1/login.php');

curl_setopt_array($EnviarLoginSenha, [
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POSTFIELDS => [
            'nome' => 'inkeliz',
            'senha' => '123456789',
            'csrf' => $csrf,
        ],
        CURLOPT_HTTPHEADER => [
            'Cookie: '.$cookie
        ]
]);

curl_exec($EnviarLoginSenha);

The CURLOPT_HTTPHEADER is equivalent to -H and the CURLOPT_POSTFIELDS when informed an array is equivalent to -d. Then we can do any action as if you were logged in, based on cookies, so:

$AcessarLogado = curl_init('http://127.0.0.1/login.php');

curl_setopt_array($AcessarLogado, [
    CURLOPT_CUSTOMREQUEST => 'GET',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'Cookie: '.$cookie
    ]
]);

echo curl_exec($AcessarLogado);

Will return:

Você está logado usando o nome de inkeliz

The basic concept is this, can be applied in any case. It is obvious that other validations can be made, such as having to inform a valid UA and the like.

  • I believe there will be no more answers, so I marked as solved I will study these concepts you mentioned in the answer, only one question you are part of the Twitter team?

  • I took the test, with php 7, does not load, and informs that the variable $curl is undefined.

  • The $curl only used within the CURLOPT_HEADERFUNCTION and it is never used. You need to have a minimally updated version of Curl, in case I used PHP 7.1 and Curl 7.50.3, the latest version is 7.54.1. If you are using a very old version it is expected that it will not work.

  • I’m using version 7.0.10

  • a doubt, what should I put in these fields ? $cookie = '';&#xA;$csrf = ''; ?

  • So far I haven’t been able to use this @Inkeliz

  • see http://prntscr.com/fpbmbf/direct am using correctly?

  • @Inkeliz, tested I did not get any error, as Willbb reported what I should put in the variables $cookie = ''; $csrf = ''; $curl e $cabecalho ?

  • @Guilhermealves this code is an example code, if you know about HTTP you can adjust to any situation. These variables were created to avoid "Notice:" errors, in addition to the $cookie is used as a reference &$cookie within the function of CURLOPT_HEADERFUNCTION, then for the reference to work as expected you need to set the variable before. The first code, where there is $PegarCSRFToken = I think the name is suggestive, it is who defines both variables. For the code to work you need to have an updated Curl ( 7.50+) and PHP 7.1+.

  • Yes, I gave a var_dump on before the return and gave me 200 OK, but ta giving me indefinite variable $Matches[1], don’t know why @Inkeliz

  • @Inkeliz I’ll open another question based on this ok ta then you try to help me?

  • @Inkeliz veja https://answall.com/questions/217256/curl-returnant-offset-undefined

  • The question is about Oauth/Twitter. This answer explains how to log into a site simulating a user in a browser, ie, is a webcrawler.

  • @rodorgas Oauth does not use login/password, including this I said in the comment that was used for this question at the beginning of his post. What he wants in "This is my form:" is precisely that the user enters the login and password, as a consequence do not use Oauth. If you do not want to use Oauth you will have to use the Twitter login/password, which will fall on the same principle of this example.

  • Yes, the AP is confused about Oauth and seeks clarification. Logging into twitter using the user credentials remains a bad idea...

Show 10 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.