Fsockopen and proxy authentication in PHP - php

I'm trying to integrate proxy usage (with authentication) into a script that queries whois data.
What I'm trying to do is
1) Connect to the proxy IP and port
2) authenticate a username and password
3) connect to the whois server and send domain details, receiving the request in return.
I have the script working without proxies
private function whois($domeinnaam, $whoisrule)
{
list ($server, $poort, $domein, $vrij) = $whoisrule;
$domein = str_replace("{domein}", $domeinnaam, $domein);
$fp = fsockopen($server, $poort);
if($fp)
{
fputs($fp, $domein."\r\n");
$data = "";
while(!feof($fp))
{
$data .= fread($fp, 1000);
}
fclose($fp);
}
else
{
$data = "error";
}
// Cache whois data
$this->_whoisdata[$domein] = $data;
return $data;
}
But does anyone how I would integrate a proxy server and authentication into this code?

cURL has some handy CURLOPT_PROXY* options. This answer shows how to use them.

Related

How to use fsockopen (or compatible) with SOCKS proxies in PHP?

I've coded a non-evil, non-spammy IRC bot in PHP, using fsockopen and related functions. It works. However, the problem is that I need to support proxies (preferably SOCKS5, but HTTP is also OK if that is somehow easier, which I doubt). This is not supported by fsockopen.
I've gone through all search results for "PHP fsockopen proxy" and related queries. I know of all the things that don't work, so please don't link to one of them.
The PHP manual page for fsockopen mentions the function stream_socket_client() as
similar but provides a richer set of options, including non-blocking connection and the ability to provide a stream context.
This sounded promising at first, supposedly allowing me to just replace the fsockopen call with stream_socket_client and specify a proxy, maybe via a "stream context"... but it doesn't. Or does it? I'm very confused by the manual.
Please note that it must be a PHP code solution; I cannot pay for "Proxifier" or use any other external software to "wrap around" this.
All the things I've tried seem to always result in me getting a bunch of empty output from the server, and then the socket is forcefully closed. Note that the proxy I'm trying with works when I use HexChat (a normal IRC client), with the same network, so it's not the proxies themselves that are at fault.
As far as I know there is no default option to set a SOCKS or HTTP proxy for fsockopen or stream_socket_client (we could create a context and set a proxy in HTTP options, but that doesn't apply to stream_socket_client). However we can establish a connection manually.
Connecting to HTTP proxies is quite simple:
The client connects to the proxy server and submits a CONNECT request.
The server responds 200 if the request is accepted.
The server then proxies all requests between the client and destination host.
<!- -!>
function connect_to_http_proxy($host, $port, $destination) {
$fp = fsockopen($host, $port, $errno, $errstr);
if ($errno == 0) {
$connect = "CONNECT $destination HTTP/1.1\r\n\r\n";
fwrite($fp, $connect);
$rsp = fread($fp, 1024);
if (preg_match('/^HTTP\/\d\.\d 200/', $rsp) == 1) {
return $fp;
}
echo "Request denied, $rsp\n";
return false;
}
echo "Connection failed, $errno, $errstr\n";
return false;
}
This function returns a file pointer resource if the connection is successful, else FALSE. We can use that resource to communicate with the destination host.
$proxy = "138.204.48.233";
$port = 8080;
$destination = "api.ipify.org:80";
$fp = connect_to_http_proxy($proxy, $port, $destination);
if ($fp) {
fwrite($fp, "GET /?format=json HTTP/1.1\r\nHost: $destination\r\n\r\n");
echo fread($fp, 1024);
fclose($fp);
}
The communication protocol for SOCKS5 proxies is a little more complex:
The client connects to the proxy server and sends (at least) three bytes: The first byte is the SOCKS version, the second is the number of authentication methods, the next byte(s) is the authentication method(s).
The server responds with two bytes, the SOCKS version and the selected authentication method.
The client requests a connection to the destination host. The request contains the SOCKS version, followed by the command (CONNECT in this case), followed by a null byte. The fourth byte specifies the address type, and is followed by the address and port.
The server finally sends ten bytes (or seven or twenty-two, depending on the destination address type). The second byte contains the status and it should be zero, if the request is successful.
The server proxies all requests.
<!- -!>
More details: SOCKS Protocol Version 5.
function connect_to_socks5_proxy($host, $port, $destination) {
$fp = fsockopen($host, $port, $errno, $errstr);
if ($errno == 0) {
fwrite($fp, "\05\01\00");
$rsp = fread($fp, 2);
if ($rsp === "\05\00" ) {
list($host, $port) = explode(":", $destination);
$host = gethostbyname($host); //not required if $host is an IP
$req = "\05\01\00\01" . inet_pton($host) . pack("n", $port);
fwrite($fp, $req);
$rsp = fread($fp, 10);
if ($rsp[1] === "\00") {
return $fp;
}
echo "Request denied, status: " . ord($rsp[1]) . "\n";
return false;
}
echo "Request denied\n";
return false;
}
echo "Connection failed, $errno, $errstr\n";
return false;
}
This function works the same way as connect_to_http_proxy. Although both functions are tested, it would be best to use a library; the code is provided mostly for educational purposes.
SSL support and authentication.
We can't create an SSL connection with fsockopen using the ssl:// or tls:// protocol, because that would attempt to create an SSL connection with the proxy server, not the destination host. But it is possible to enable SSL with stream_socket_enable_crypto and create a secure communication channel with the destination, after the connenection with the proxy server has been established. This requires to disable peer verification, which can be done with stream_socket_client using a custom context. Note that disabling peer verification may be a security issue.
For HTTP proxies we can add authentication with the Proxy-Authenticate header. The value of this header is the authentication type, followed by the username and password, base64 encoded (Basic Authentication).
For SOCKS5 proxies the authentication process is - again - more complex. It seems we have to change the authentication code fron 0x00 (NO AUTHENTICATION REQUIRED) to 0x02 (USERNAME/PASSWORD authentication). It is not clear to me how to create a request with the authentication values, so I can not provide an example.
function connect_to_http_proxy($host, $port, $destination, $creds=null) {
$context = stream_context_create(
['ssl'=> ['verify_peer'=> false, 'verify_peer_name'=> false]]
);
$soc = stream_socket_client(
"tcp://$host:$port", $errno, $errstr, 20,
STREAM_CLIENT_CONNECT, $context
);
if ($errno == 0) {
$auth = $creds ? "Proxy-Authorization: Basic ".base64_encode($creds)."\r\n": "";
$connect = "CONNECT $destination HTTP/1.1\r\n$auth\r\n";
fwrite($soc, $connect);
$rsp = fread($soc, 1024);
if (preg_match('/^HTTP\/\d\.\d 200/', $rsp) == 1) {
return $soc;
}
echo "Request denied, $rsp\n";
return false;
}
echo "Connection failed, $errno, $errstr\n";
return false;
}
$host = "proxy IP";
$port = "proxy port";
$destination = "chat.freenode.net:6697";
$credentials = "user:pass";
$soc = connect_to_http_proxy($host, $port, $destination, $credentials);
if ($soc) {
stream_socket_enable_crypto($soc, true, STREAM_CRYPTO_METHOD_ANY_CLIENT);
fwrite($soc,"USER test\nNICK test\n");
echo fread($soc, 1024);
fclose($soc);
}

GET method causes an error

sorry for the title but I'm not reaaly sure how to call this.
I am registered to a ssm service which enables sending automatic sms with a php script.
the script basically builds an xml string with all of the sms parameters (sendername, ..).
then it uses this to send it :
$sms_host = "api.inforu.co.il"; // Application server's URL;
$sms_port = 80; // Application server's PORT;
////.... generating query
$sms_path = "/SendMessageXml.ashx"; // Application server's PATH;
$fp = fsockopen($sms_host, $sms_port, $errno, $errstr, 30); // Opens a socket to the Application server
if (!$fp){ // Verifies that the socket has been opened and sending the message;
echo "$errstr ($errno)<br />\n";
echo "no error";
} else {
$out = "GET $sms_path?$query HTTP/1.1\r\n";
$out .= "Host: $sms_host\r\n";
$out .= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
while (!feof($fp)){
echo fgets($fp, 128);
}
fclose($fp);
the query is fine if I paste this
$url = "http://api.inforu.co.il/SendMessageXml.ashx?" . $query;
directly in the browser, then the sms gets send.
so the problem is that I'm getting an error
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /SendMessageXml.ashx
You have to urlencode() your $query, if you paste it to browser, the browser will encode it for you, but when you are dealing with a socket, you have to do it yourself.

Use fsockopen with proxy

I have a simple whois script
if($conn = fsockopen ($whois_server, 43)) {
fputs($conn, $domain."\r\n");
while(!feof($conn)) {
$output .= fgets($conn, 128);
}
fclose($conn);
return $output;
}
$whois_server = whois.afilias.info; //whois server for info domains
but I want to run in through proxy. So I need to connect to proxy -> then connect to whois server -> and then make the request. Something like this?
$fp = fsockopen($ip,$port);
fputs($fp, "CONNECT $whois_server:43\r\n $domain\r\n");
But it doesn't work, I don't know if i'm making the second connection right.
Sending your request to the proxy should do what you like:
<?php
$proxy = "1.2.3.4"; // proxy
$port = 8080; // proxy port
$fp = fsockopen($proxy,$port); // connect to proxy
fputs($fp, "CONNECT $whois_server:43\r\n $domain\r\n");
$data="";
while (!feof($fp)) $data.=fgets($fp,1024);
fclose($fp);
var_dump($data);
?>
Rather than doing that I would recommend you using CURL in combination with:
curl_setopt($ch, CURLOPT_PROXY, 1.2.3.4);

Setup a TCP listener in PHP

We're using a system at the moment that takes an incoming JSON request over TCP and responds using JSON too. Currently I've set up my socket like so in PHP:
$socket = fsockopen($host, $port, $errno, $errstr, $timeout);
if(!$socket)
{
fwrite($socket, $jsonLoginRequest); // Authentication JSON
while(json_decode($loginResponse) == false) // We know we have all packets when it's valid JSON.
{
$loginResponse .= fgets($socket, 128);
}
// We are now logged in.
// Now call a test method request
fwrite($socket, $jsonMethodRequest);
while(json_decode($methodResponse) == false) // We know we have all packets when it's valid JSON.
{
$methodResponse .= fgets($socket, 128);
echo $methodResponse; // print response out
}
// Now we have the response to our method request.
fclose($socket);
}
else
{
// error with socket
}
This works at the moment, and the server responds to the method request. However, some methods will respond like this to acknowledge the call, but will also respond later on with the results I'm after. So what I really need is a TCP listener. Could anyone advise how I could write a TCP listener using fsock like I have above?
Thanks
To create a listening socket use the following functions:
socket_create_listen (this one is cool)
socket_accept
I'm not shure if fwrite()/fread() are working with those sockets otherwise you have to use the following functions:
socket_recv
socket_send
Message-loop
I have now written some function to read a single JSON responses with the assumption that multiple responses are separated by CRLF.
Here's how I would do it (assuming your php-script has unlimited execution time):
// ... your code ...
function readJson($socket) {
$readData = true;
$jsonString = '';
while(true) {
$chunk = fgets($socket, 2048);
$jsonString .= $chunk;
if(($json = json_decode($jsonString)) !== false) {
return $json;
} elseif(empty($chunk)) {
// eof
return false;
}
}
}
// ....
// Now call a test method request
fwrite($socket, $jsonMethodRequest);
$execMessageLoop = true;
while($execMessageLoop) {
$response = readJson($socket);
if($response === false) {
$execMessageLoop = false;
} else {
handleMessage($socket, $response);
}
}
function handleMessage($socket, $response) {
// do what you have to do
}
Now you could implement the "handleMessage" function which analyses the response and acts to it.

HTTPS Post Request via PHP and Cookies

I am kinda new to PHP however I used JSP a lot before (I have quite information) and everything was easier with Java classes.
So, now, I want to perform a POST request on a HTTPS page (not HTTP) and need to get returned cookies and past it to another GET request and return the final result. Aim is to make a heavy page for mobile phones more compatible to view in a mobile browser by bypassing the login page and directly taking to the pages which are also served in an ajax user interface.
I am stuck, my code does not work, it says it is Bad Request.
Bad Request
Your browser sent a request that this
server could not understand. Reason:
You're speaking plain HTTP to an
SSL-enabled server port. Instead use
the HTTPS scheme to access this URL,
please.
<?php
$content = '';
$flag = false;
$post_query = 'SOME QUERY'; // name-value pairs
$post_query = urlencode($post_query) . "\r\n";
$host = 'HOST';
$path = 'PATH';
$fp = fsockopen($host, '443');
if ($fp) {
fputs($fp, "POST $path HTTP/1.0\r\n");
fputs($fp, "Host: $host\r\n");
fputs($fp, "Content-length: ". strlen($post_query) ."\r\n\r\n");
fputs($fp, $post_query);
while (!feof($fp)) {
$line = fgets($fp, 10240);
if ($flag) {
$content .= $line;
} else {
$headers .= $line;
if (strlen(trim($line)) == 0) {
$flag = true;
}
}
}
fclose($fp);
}
echo $headers;
echo $content;
?>
From past experience, I've never used PHP's internal functions like fsocketopen() for external data posting. The best way to do these actions are using CURL, which gives much more ease and is massively more powerful for developers to leverage.
for example, look at these functions
http://php.net/curl_setopt
and look at the one with URL, POST, POSTDATA, and COOKIESFILES which is for .JAR, which you get then retrieve and that you can use file_get_contents() to send the data using GET.

Categories