I’m using https://github.com/lemmingzshadow/php-websocket/
I can allow some domains, and I have allowed localhost and a domain which points to my local server. But I wonder if someone else which has a server on his computer can connect to my websocket (through my domain) using an script in his localhost server.
Here is the relevant code:
-> server/server.php
$server->setAllowedOrigin('localhost');
$server->setAllowedOrigin('mydomain.com');
-> server/lib/WebSocket/Connection.php
// check origin:
if($this->server->getCheckOrigin() === true)
{
$origin = (isset($headers['Sec-WebSocket-Origin'])) ? $headers['Sec-WebSocket-Origin'] : false;
$origin = (isset($headers['Origin'])) ? $headers['Origin'] : $origin;
if($origin === false)
{
$this->log('No origin provided.');
$this->sendHttpResponse(401);
stream_socket_shutdown($this->socket, STREAM_SHUT_RDWR);
$this->server->removeClientOnError($this);
return false;
}
if(empty($origin))
{
$this->log('Empty origin provided.');
$this->sendHttpResponse(401);
stream_socket_shutdown($this->socket, STREAM_SHUT_RDWR);
$this->server->removeClientOnError($this);
return false;
}
if($this->server->checkOrigin($origin) === false)
{
$this->log('Invalid origin provided.');
$this->sendHttpResponse(401);
stream_socket_shutdown($this->socket, STREAM_SHUT_RDWR);
$this->server->removeClientOnError($this);
return false;
}
}
-> server/lib/WebSocket/Server.php
public function checkOrigin($domain)
{
$domain = str_replace('http://', '', $domain);
$domain = str_replace('https://', '', $domain);
$domain = str_replace('www.', '', $domain);
$domain = str_replace('/', '', $domain);
return isset($this->_allowedOrigins[$domain]);
}
public function setAllowedOrigin($domain)
{
$domain = str_replace('http://', '', $domain);
$domain = str_replace('www.', '', $domain);
$domain = (strpos($domain, '/') !== false) ? substr($domain, 0, strpos($domain, '/')) : $domain;
if(empty($domain))
{
return false;
}
$this->_allowedOrigins[$domain] = true;
return true;
}
Edit:
Maybe I wasn’t clear enough. I want that everybody can connect to the websocket but only if they are at my domain (or my localhost), something like Same Origin Policy in AJAX.
My worry is that if I allow localhost, maybe all other localhost in other computers will be allowed too.
Although I was worried about allowing connections from all localhost when I wanted to allow only my localhost, i have found that in another question, kanaka said:
Then, my origin checking code is not safe at all; and it doesn’t matter if all allow all localhosts because if someone has enough knowledge for connecting to my websocket using his own localhost, it is likely that he could modify the Origin header.