How would I go about writing a simple PHP bot? - php

How would I go about writing a simple PHP bot that could login in and recieve all the cookies sent by the server? ... and then send them back when required?
Any suggestions would be appreciated.

First of all, your question is too broad and lacking in detail to really answer effectively. That said, I'll give it a try.
Not knowing what exactly you mean by "log in", I assume you want the script to be able to post some data to another script via an HTTP request. The CURL Library is good for that. It is able to post data and handle cookies.
Edit: Got ninja'd by Zed. ;)

If for some reason you cannot use the curl extension on your server (extension not installed), you can use a class such as Snoopy which will still allow you to either use the curl binaries or use sockets to retrieve the information.
Snoopy handles cookies.
As for the writing the bot itself, it's just a question of sending the proper requests. Here is an example with Snoopy:
$snoopy = new Snoopy;
// The following needs to reflect the form configuration of the site
$login = array('usr' => 'hi', 'pwd' => 'hello');
if($snoopy->submit('http://example.com/login', $login) === false) {
// output the response code
die($snoopy->response_code . ':' . $snoopy->error);
}
//Request succeeded (doesn't mean we are logged in)
// output the results
echo $snoopy->results;
// Check the results to see if you are logged in and
// Continue using $snoopy.
// It will pass the proper cookies for the next requests.

With the help of the cURL library?

Related

PHP: help secure / filter ajax calls

I am trying to find a way to filter ajax calls in order to add a fine layer of security to my applications. Does the code bellow make any sense?
function is_ajax(){//Help Secure Ajax Calls
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']=='XMLHttpRequest') return;
else die;//no ajax
}
My dream is only let a file inside my server (htm or php) to access another php file via ajax.
I wonder if the code bellow would not do better:
if(strpos($_SERVER['REQUEST_URI'],'http://')) die;//Help Secure From URL Include Attacks
Thanks.
Since the AJAX call is always made from the browser, the request is not coming from your own server, but the client machine. Even if you set custom headers, these can easily be manipulated on the client side.
If your goal is to only allow your own scripts to access the script containing the ajax content, I'd recommend generating a token string that is only valid for a certain requested url and a specified time.
Quick and dirty example:
Script requesting the AJAX resource:
$secret ="ABC1232";
$item = array(
"time"=>time(),
"token_id"=>"<page_url>"
);
$signed = base64_encode(hash_hmac("sha256",json_encode($item),$secret));
$item = base64_encode(json_encode($item));
$ajax_url = "myscript.php?signed=$signed&item=$item";
AJAX Resource, check the token is valid
$item = json_decode(base64_decode($_REQUEST["item"]));
$timeout = 3600;
if($item->time < (time()-$timeout)){
die("Invalid token - timeout");
}
if($item->token_id !== "<page_url>"){
die("Invalid token - page url");
}
$secret ="ABC1232";
$valid = ($_REQUEST["signed"] === base64_encode(hash_hmac("sha256",json_encode($item),$secret));
if(!$valid){
die("Invalid token");
}
Your Ajax is as secure as your application layer. Ajax is just client side code accessing server side code. There is probably no way in securing it the way you want since anyone can emulate Ajax calls from within any language by just modifying the request headers. One more thing most ajaxified frameworks do include HTTP_X_REQUESTED_WITH but it's not 100% reliable.
Just secure your server code and your good to go. If you really want to at least let your server code know that it's receiving an ajax call, use a parameter on the request.
Assume that anything that can be requested by AJAX will also be accessed directly and you will be in a much safer place. You really should consider why you would only ever want something to be accessed via AJAX in the first place. The HTTP_X_REQUESTED_WITH header is unreliable and easily spoofed so it provides no real security anyway.
I think for a little more security you could decode your secret string after you encode it. then echo than decoded string in php and then copy it.
then on the the $valid variable
$valid = (base64_decode($_REQUEST["signed"]) === "blahblahblah that you copied from php");

Posting and executing a string as PHP?

I'm building an application that's self-hosted, and I'd like to have some form of licensing to minimize fraudulent downloads/distribution.
Of course, I'm well aware that being self-hosted someone could simply rip out all license features from the source-code, but the con's of using a compiler like Zend Guard or ionCube far outweigh the pro's in my opinion - nonetheless I'd like to have some basic form of license security.
What I originally had in mind to do was: user logs in with license on app -> app posts license to my server -> server sends a response via a HTTP GET request -> app evaluates response, and if license is valid sets a value in a session variable (A), if invalid returns to login screen with an error.
The problem with this is, the evaluation of response/session setting is readily available in a application file, so if the user knows a little PHP and checks in on that source code, they'll realize all they'll need to do is set a session themselves with a particular $_SESSION['_valid_license'] value, and they'll be good to go.
What I was considering doing to make it a little less easy was (if possible) to post PHP back as a response, and then have the application file execute it, for example:
My original code:
$response = $_GET['response'];
if($response == "fjdkuf9") {
start_session();
$_SESSION['_valid_license'] = "YES";
header("Location:" . $rp . "/admin/");
} else {
header("Location:" . $rp . "/login/?err=1");
}
My new concept:
$response = $_POST['response'];
str_replace("\", "", $response);
With the following being posted as response:
start_session();
\$_SESSION[\'_valid_license\'] = \"YES\";
header(\"Location:\" . \$rp . \"/admin/\");
Would that execute $response as actual PHP code after str_replace()? If possible, this would be great, as it would mean evaluation would be done on my server rather than within the self-hosted app itself.
Your second solution is just as insecure as the first. here's what I would do:
Your application POSTS to your server a serial number or some other identifying information.
Your server validates the serial number against the user's account or whatever and returns a unique response.
If that response is successful, you allow the user to continue. Obviously you'd want to implement some sort of caching mechanism here so you're not having to hit you server on every page view.
Putting the responsibility of validation on your server instead of self-hosted code is much more secure. You would need to encrypt the data that is sent BTW so that someone couldn't simply emulate the success response, but you get the idea.

php curl for facebook post tweet

I want post tweets into facebook using php curl , this is my snippet I used for posting tweet into FB - FB CURL SNIPPET
But i am not find any updated tweet in my facebook,
am not sure but i thing somthing goes wrong,
Can you tell me, snippet is correct one or not?
Thanks
This calls for debugging.
First port of call: It could be that the cookies are not saved: Check whether the script actually generates a my_cookies.txt file. If it doesn't, create an empty one and do a chmod 777 on it.
Second port of call: curl_error().
Replace every curl_exec() call in the snippet by this:
$success = curl_exec(....... your options .....);
if (!$success) echo "CURL Error: ".curl_error();
this might give you some pointers as to what goes wrong.
However, seeing as the script tries to imitate a browser instead of using an API, it could be that the structure of the submission form has changed on Facebooks's side, in which case you'll have to parse the output cURL gives you and see what goes wrong.
All in all, if there is any way to do this cleanly through an API - I don't know whether there is - it would be much preferable to this.

How to retrieve http page from another host server with php and detect redirect

Let's say I have a server at www.myhost.com. From there by using php I want to retrieve the html document that the php file www.anotherhost.com/somefile.php produces. I also want to use php to do this. anotherhost is not on the same server as myhost.
I know that functions such as fopen, f_get_contents and file can do this by simply executing e.g.
$fp = fopen ("http://www.anotherhost.com/somefile.php")
and from there fp can be used as any other file pointer to read the contents.
BUT, for some reason I also want to know if somefile.php at anotherhost ordered a client-side redirect when I tried to retrieve somefile.php´s resulting html document. somefile.php can do this by
header ("Location: http://www.anotherhost.com/extrafile.php")
Now fopen will retrieve the html document that extrafile.php produces, without detecting that a client-side redirect has been performed.
Is there some functionality in PHP that enables you to retrieve html documents from other servers AND notifies you if a redirect has taken place? It is acceptable if I must follow the redirect by myself (not done automatically), as long as I'm told what the new URL is.
Executing arbitrary commands with the function system is not preferred.
PS. If you are going to suggest fsockopen, then please explain why i get the error "Unable to find the socket transport "http" - did you forget to enable it when you configured PHP?" when I try to execute
fsockopen ("http://localhost")
and I also get "Failed to parse address "localhost" when I do
fsockopen ("localhost")
Thanks for reading. Help would be greatly appreciated.
You can use the Zend_Http_Client from Zend Framework. It has methods for retrieving the number of redirects as well as setting a limit to the number of redirects to follow etc. If you just want to know how it's done, then you can look into the source code and try to figure it out. Shouldn't be too hard I think.
I would use cURL for this. If the redirect is specified in the header, instead of apache mod_rewrite for example, then you should be able to detect if a redirect is present by grabbing all of the headers sent by the response.
Optionally, there is a setting to automatically follow the redirect (http://us.php.net/manual/en/function.curl-setopt.php).
As of php 5.2 you can use the stream api and a stream_notification_callback
e.g.
function notification($code, $severity, $message, $mcode, $transferred, $max) {
if ( STREAM_NOTIFY_REDIRECTED===$code ) {
echo 'redirected to ', $message, "\n";
}
}
$ctx = stream_context_create(null, array('notification' => 'notification'));
$c = file_get_contents("http://spiegel.de", false, $ctx);
echo 'len=', strlen($c);
prints
redirected to http://www.spiegel.de/
len=144446
You probably want a full HTTP client, not stream wrappers and fopen()/file_get_contents(). I think its possible to do what you want with stream wrappers using stream_get_meta_data() but you would be better off with a fuller implementation.
If you don't want to go down the Zend or stream route, you could always use the cURL functions. These will let you return the headers, hence you could analyse these to ascertain whether any re-directs are being issued.
(You can also use the 'CURLOPT_MAXREDIRS' option to specify that it shouldn't follow re-directs.)

PHP CLI script to login an application

I am trying to write a script to log in to a web application using a PHP CLI script:
<?php
$post_data = array(
'user_name' => 'abc',
'user_password'=>'XYZ##11',
);
$url ='http://www.myapplication.com?action=Login&module=Users';
$hat = new HttpRequest($url,HTTP_METH_POST);
$hat->setPostFields($post_data);
$hat->send();
$res = $hat->getResponseData();
print'<pre>'; print_r($res); print '</pre>';
?>
I want to post the username and password to this page and try to log in to the application.
I dont know if this is the right way to do this?
Please suggest how to go about this.
You could use the cURL library to create a POST request.
POST data manipulation using php and CURL
Using cURL and libcurl with PHP
If the page you are accessing uses HTTP Basic authentication, take a look at HttpRequest::setOptions and set the httpauth and httpauthtype options on your request. You'll need something like this:
$options=array();
$options['httpauth']="abc:XYZ##11";
$options['httpauthtype']=HTTP_AUTH_BASIC;
$hat->setOptions($options);
Looks fine - I don't know much about HttpRequest but you may need to do some work to maintain cookie data, so you stay logged in

Categories