WebSocket opcode 7 with wss:// - javascript

I tried to launch a server in wss:// last Tuesday, but it didn't work. Today I decided to look at the WebSocket code and I found why my WebSocket closed directly. This is error code I found:
1002 Unsupported usage of rsv bits without negotiated extension.
VALUE OF RSV1:Opcode: 7, fin: false, length: 69, hasPayload: true, masked: false
My program works with ws:// but not with wss://. I can't understand why TLS is blocked.
I precise IPtables are stopped and my certificate is OK.
Do you have any idea?
Below is my code if you want to look:
var fs = require('fs');
var https = require('https');
var WebSocketServer = require('websocket').server;
var express = require('express');
var serverTLS = express.createServer({
key: fs.readFileSync(__dirname + '/notification_mail/notification.mail.com.key'),
cert: fs.readFileSync(__dirname + '/notification_mail/notification.mail.com.crt')
});
serverTLS.configure(function(){
serverTLS.set('views',__dirname);
serverTLS.set('view engine','ejs');
});
serverTLS.get('/',function(req,res){
res.render('index',{layout: false });
});
serverTLS.listen("443");
var wss = new WebSocketServer({ httpServer: serverTLS, autoAcceptConnections: true });
wss.on('connect', function(connection) {
console.log((new Date()) + " Connection accepted.");
connection.on('close', function(connection) {
console.log((new Date()) + " Disconnected");
});
});
console.log("Server launch");
And my HTML file
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<h1>Serveur 2</h1>
<div id="tchat"></div>
<script>
var url = "wss://notification.mail.com";
var wsCtor = window['MozWebSocket'] ? MozWebSocket : WebSocket;
this.socket = new wsCtor(url, 'connect');
this.socket.onclose = function(){
alert ("Connection lost");
}
</script>
</body>
</html>

The error message is confusing, since
opcode 7 is indeed reserved (https://www.rfc-editor.org/rfc/rfc6455#section-5.2), but
it also mentions RSV1 which is also reserved, but gives no observed value
Did you try Chrome or IE10?
You could also try running AutobahnTestsuite against your node server.
The testsuite has a fuzzingclient mode that supports WSS. The testsuite includes extensive wire log reports which might help finding out what happens.
Disclosure: I am original author of Autobahn and work for Tavendo.

I launched wss:// (but on .NET) and I got 7 opcode, too. I used ReadTimeout (ReceiveTimeout) every 5 seconds for sending "ping" to client. In ws:// and wss:// all worked well, but in wss:// every 5 seconds I got "7 opcode".
I removed the timeout and it worked.

Related

Trying to port my socketio client from js to python but it is not working

I have the following JS code that works great to connect to a socket via the socketio client library:
userApi = 'userapiaccesfskdglk';
userAccess = 'useaccesfjkasdfdlkf2';
var axios = require('axios');
var socket = require('socket.io-client')('wss://test-meownow12345.com:4566');
socket.emit('Authenticate', {api: userApi, access: userAccess});
socket.on('Party', function(party) {
console.log('party', party)
})
These are not the actual userApi, userAccess, or urls used, but using them still gets the same point across.
This is what i have in python, that to me looks like an exact port but is not working:
from socketIO_client import SocketIO, LoggingNamespace
import logging
logging.basicConfig(level=logging.DEBUG)
def on_party():
print('connect')
userApi = 'userapiaccesfskdglk'
userAccess = 'useaccesfjkasdfdlkf2'
with SocketIO('wss://test-meownow12345.com', 4566, LoggingNamespace) as socketIO:
socketIO.emit('Authenticate', {'api': userApi, 'access': userAccess})
socketIO.on('Party', on_party)
It seems like it is equivalent but it is clearly not as the code cannot get past the following line that opens the socket.io connection:
with SocketIO('wss://test-meownow12345.com', 4566, LoggingNamespace) as socketIO:
In my console it prints out the following log errors that just repeat:
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): wss
WARNING:socketIO-client:wss:4566//test-meownow12345.com/socket.io [engine.io waiting for connection] HTTPConnectionPool(host='wss', port=4566): Max retries exceeded with url: //test-meownow12345.com/socket.io/?EIO=3&transport=polling&t=1523668232386-0 (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x105000278>: Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known',))
I'm not really sure what this means.
I have tried changing the line giving this message and drop the 'wss://' part to make it:
with SocketIO('test-meownow12345.com', 4566, LoggingNamespace) as socketIO:
but this still fails, albeit with a new message in the logs that repeats:
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): test-meownow12345.com
WARNING:socketIO-client:test-meownow12345.com:4566/socket.io [engine.io waiting for connection] ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',))
DEBUG:urllib3.connectionpool:Starting new HTTP connection (2): test-meownow12345.com
DEBUG:urllib3.connectionpool:Starting new HTTP connection (3): test-meownow12345.com
Any help is really appreciated, this is quite a frustrating problem.
If you look at SocketIO class
class SocketIO(EngineIO):
It inherits from EngineIO which has __init__ as
class EngineIO(LoggingMixin):
def __init__(
self, host, port=None, Namespace=EngineIONamespace,
wait_for_connection=True, transports=TRANSPORTS,
resource='engine.io', hurry_interval_in_seconds=1, **kw):
self._is_secure, self._url = parse_host(host, port, resource)
self._wait_for_connection = wait_for_connection
And definition of parse_host is
def parse_host(host, port, resource):
if not host.startswith('http'):
host = 'http://' + host
url_pack = parse_url(host)
is_secure = url_pack.scheme == 'https'
port = port or url_pack.port or (443 if is_secure else 80)
url = '%s:%s%s/%s' % (url_pack.hostname, port, url_pack.path, resource)
return is_secure, url
This indicates that the usage should be like below
with SocketIO('https://test-meownow12345.com', 4566, LoggingNamespace) as socketIO:
socketIO.emit('Authenticate', {'api': userApi, 'access': userAccess})
socketIO.on('Party', on_party)

I'm getting a net::ERR_INSECURE_RESPONSE with socket.io/node.js

Here is the current code that I am using to try to connect my web application running socket.io to my node application.
var options = {
key: fs.readFileSync('csgo2x.key').toString(),
cert: fs.readFileSync('csgo2x.crt').toString(),
ca : [fs.readFileSync("csgo2x.pem").toString()],
rejectUnauthorized: false
};
var server = require('https').createServer(options);
var portNo = 443;
server.listen(portNo, function() {
console.log((new Date()) + " Server is listening on port " + portNo);
});
However...when I try to connect my socket.io application running on my Ubuntu server...it gives the error net::ERR_INSECURE_RESPONSE.
I am using certificates from Cloudflare btw and for some reason it's not working

Can't connect to wss:// (Error in connection establishment: net::ERR_CONNECTION_CLOSED)

I have VPS with LAMP. I have free signed SSL certificate from Startssl.com (ssl certificate working correctly)
With http:// protocol I can connect to ws://chat.example.com:1337/some-variable but when I replace protocol http:// to https:// then I can't connect to wss://chat.example.com:1337/some-variable
When I try to connect to wss:// I'm getting error Error in connection establishment: net::ERR_CONNECTION_CLOSED
Why?
// http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
"use strict";
// Optional. You will see this name in eg. 'ps' or 'top' command
process.title = 'node-chat';
// Port where we'll run the websocket server
var webSocketsServerPort = 1337;
// websocket and http servers
var webSocketServer = require('websocket').server;
var http = require('http');
var $ = require("jquery");
/**
* HTTP server
*/
var server = http.createServer(function(request, response) {
// Not important for us. We're writing WebSocket server, not HTTP server
});
server.listen(webSocketsServerPort, function() {
console.log((new Date()) + " Server is listening on port " + webSocketsServerPort);
});
/**
* WebSocket server
*/
var wsServer = new webSocketServer({
// WebSocket server is tied to a HTTP server. WebSocket request is just
// an enhanced HTTP request. For more info http://tools.ietf.org/html/rfc6455#page-6
httpServer: server
});
EDIT
I have source from http://ahoj.io/nodejs-and-websocket-simple-chat-tutorial
To critique my answer better, as the last one was a mistake and I didn't mean to submit it until after I finished digging, try this:
// Private key and certification
var options = {
key: fs.readFileSync('cert/server.key'),
cert: fs.readFileSync('cert/server.crt')
};
var server = https.createServer(options, function(request, response) {
console.log((new Date()) + ' Received HTTP(S) request for ' + request.url);
}

registration using sip.js and websockets in Node (wss or ws)

I'm trying to register SIP agents using sip.js and Node to start load testing to my Kamailio
Node version v0.10.32
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"
global.WebSocket = require('ws')
// SipJS Initialization
var SIP = require('./sip-0.6.0.js');
var Uaconfig = {
traceSip: true,
register: true,
userAgentString: 'sipJS Test tool',
uri: 'ramenlabs.io',
wsServers: ['wss://ramenlabs.io:5063'],
authorizationUser: 'gogasca',
password: '********'
//hackIpInContact: true
};
var userAgent = new SIP.UA(Uaconfig);
When I run I get an error:
Thu Oct 16 2014 03:40:53 GMT+0000 (UTC) | sip.transport | WebSocket connection error: Error: unexpected server response (400)
Because initial Websocket from Sip.js lacks Sec-WebSocket-Protocol: sip to indicate SIP Protocol.
If i use sample web page it works perfectly with same parameters, but not from my node command line.
How to force this?
In API js I do see the 'sip' extra header but contains the window.Websocket
try {
this.ws = new window.WebSocket(this.server.ws_uri, 'sip');
}
catch(e) {
this.logger.log('Error connecting to WebSocket ' + this.server.ws_uri + ': ' + e);
//return false;
}
You can set debug=3 in kamailio.cfg, restart and try again. Then look in syslog file (/var/log/syslog or /var/log/messages) for debug messages from Kamailio to see if you get a hint on why the connection is not accepted.

WebSocket connection to OpenShift app failed

I created an app with NodeJS and I'm using ws module. If I test the app in localhost it works and there isn't any problem to connect websockets. Now I've upload the app to Openshift and when I try to access from the client it returns that is not possible to stablish a connection to the websocket.
If I do a tail in putty to my app I have this message: DEBUG: This type of response MUST NOT have a body. Ignoring data passed to end().
The code that I have in the server is:
#!/bin/env node
//Openshift variables
var ipaddress = process.env.OPENSHIFT_NODEJS_IP || "192.168.69.42";
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080;
//NodeJS require modules
var Enum = require('enum');
var WebSocketServer = require('ws').Server
wss = new WebSocketServer({host:ipaddress, port:port});
var fs = require('fs');
wss.on('connection', function(ws) {
console.log((new Date()) + ' Connection from origin: ' + ws._socket.remoteAddress);
});
console.log((new Date()) + " Server is listening on: " + ipaddress + ':' port);
And in the client:
var ws = new WebSocket("ws://192.168.69.42:8080/");
ws.onopen = function() {
console.log("Connected.");
ws.send("This is the client speaking.");
};
For all WebSocket connections on OpenShift you need to use port 8000 (for Secured sessions it would be 8443). So, your server example works well (I run them after removing the unnecessary line var Enum = require('enum');, you just need to hardcode the port on client to 8000:
var ws = new WebSocket("ws://YourApp-YourName.rhcloud.com:8000");
ws.onopen = function(){
console.log('opened')
}
More information here.
Here is an example on github that works that you can check out: https://github.com/developercorey/openshift-nodejs-http-and-websocket-example

Categories

Resources