stunnel with wss getting ERR_CONNECTION_TIMED_OUT - wss

I'm trying to use stunnel with wss on my site but when I try to connect I always get:
WebSocket connection to 'wss://www.soinfit.com:8443/' failed: Error in connection establishment: net::ERR_CONNECTION_TIMED_OUT
My socket is running on port 8080 as this:
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat;
require dirname(__DIR__) . '/vendor/autoload.php';
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
),
8080
);
$server->run();
My stunnel config is:
debug = 4
output = /var/log/stunnel4/websocket.log
socket = l:TCP_NODELAY=1
socket = r:TCP_NODELAY=1
cert = /etc/ssl/private/47f2ad52d70c0.crt
key = /etc/ssl/private/soinfit.key
[websocket]
accept = 8443
connect = 8080
I'm using Chrome to connect and I'm using this code:
try {
conn = new WebSocket('wss://www.soinfit.com:8443');
conn.onclose = function (e) {
}
conn.onopen = function(e) {
console.log("test");
};
} catch (error) {
console.log(error);
}
There is nothing in the log file.
What am I doing wrong?
Thanks.

Related

Prevent nginx from killing idle tcp sockets

I'm trying to use nginx as a reverse proxy for ssl/tcp sockets (so that I can write my server custom as raw tcp, but have nginx handle the ssl certificates). My use case requires the tcp connections remain alive, but to go idle (no packets back and forth) for extended periods of time (determined by the client, but as long as an hour). Unfortunately, nginx kills my socket connections after the first 10 minutes (timed to within a second) of inactivity, and I haven't been able to find either online or in the docs what actually controls this timeout.
I know that it has to be nginx doing it (not my raw server timing out, or my client's ssl socket), since I can directly connect to the server's raw tcp server without timeout issues, but if I run nginx as a raw tcp reverse proxy (no ssl) it does timeout.
Here's some code to reproduce the issue, note that I've commented out the ssl relevent pieces in nginx because the timeout occurs either way.
/etc/nginx/modules-enabled/test.conf:
stream {
upstream tcp-server {
server localhost:33445;
}
server {
listen 33446;
# listen 33446 ssl;
proxy_pass tcp-server;
# Certs
# ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
# ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
}
}
server.js;
const net = require("net");
const s = net.createServer();
s.on("connection", (sock) => {
console.log('Got connection from', sock.remoteAddress, sock.remotePort );
sock.on("error", (err) => {
console.error(err)
clearInterval(i);
});
sock.on("close", () => {
console.log('lost connection from', sock.remoteAddress, sock.remotePort );
clearInterval(i);
});
});
s.listen(33445);
client.js
const net = require('net');
const host = 'example.com';
let use_tls = false;
let client;
let start = Date.now()
// Use me to circumvent nginx, and no timeout occurs
// let port = 33445;
// Use me to use nginx, and no timeouts occur after 10 mins of no RX/TX
let port = 33446;
client = new net.Socket();
client.connect({ port, host }, function() {
console.log('Connected via TCP');
// Include me, and nginx doesn't kill the socket
// setInterval(() => { client.write("ping") }, 5000);
});
client.on('end', function() {
console.log('Disconnected: ' + ((Date.now() - start)/1000/60) + " mins");
});
I've tried various directives in the nginx stream block, but nothing seems to help. Thanks in advance!

MailKit - smtp.Connect throw exception in C# .Net

Exception while connecting to the server: A connection attempt failed because the connected party did not properly respond after a period of time, or an established connection failed because the connected host has failed to respond.
1.) able to ping the server
2.) telnet smtp.office365.com 587 respond as expected.
public ConnectSmtpServer()
{
using MailKit.Net.Smtp;
string _SmtpServer = "smtp.office365.com";
int _portNumber = 587;
Console.WriteLine("Welcome!");
using (SmtpClient smtp = new SmtpClient())
{
try
{
smtp.Timeout = 30 * 1000;
smtp.Connect(_SmtpServer, _portNumber, SecureSocketOptions.Auto);
Console.WriteLine("Test smtp connection using MailKit.Net !");
smtp.Connect(_SmtpServer, _portNumber, SecureSocketOptions.Auto);
Console.WriteLine();
}
}
}

Not able to connet to ejabberd server through smack

I am setting up a chat service using ejabberd and building an XMPP client for android devices using smack.
Here are some important details.
server OS: ubuntu 18.04
server hosted as localhost (jid format: alice#localhost).
server system IP : 192.168.4.162
Client:
Smack 4.3.1
Using external phone through USB debugging : Nokia 3.1 Plus.
Here is my code
Here are some of the configurations I tried.
private class MyLoginTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
// Create a connection to the jabber.org server.
InetAddress addr = null;
try{
addr = InetAddress.getByName("192.168.4.162");
}catch(UnknownHostException e){
e.printStackTrace();
}
XMPPTCPConnectionConfiguration config = null;
DomainBareJid serviceName = null;
try{
serviceName = JidCreate.domainBareFrom("localhost");
System.out.println("serviceName: "+serviceName);
}catch(XmppStringprepException e){
e.printStackTrace();
}
HostnameVerifier verifier = new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// ConnectionConfiguration connConfig = new ConnectionConfiguration("talk.google.com", PORT, SERVICE);
try{
config = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword("alice", "9009")
.setHost("192.168.4.162")
.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.setXmppDomain("localhost")
.setHostnameVerifier(verifier)
.setHostAddress(addr)
.setPort(5222)
.build();
}catch(XmppStringprepException e){
e.printStackTrace();
}
AbstractXMPPConnection conn1 = new XMPPTCPConnection(config);
try {
System.out.println("Connecting......."); AndroidUsingLinkProperties.setup(getApplicationContext());
conn1.connect().login();
if(conn1.isConnected()) {
Log.w("app", "conn done");
}
conn1.login();
if(conn1.isAuthenticated()) {
Log.w("app", "Auth done");
}
}
catch (Exception e) {
Log.w("app", e.toString());
}
return "";
}
#Override
protected void onPostExecute(String result) {
}
}
The configurations i tried above the result is:
org.jivesoftware.smack.SmackException$ConnectionException: The following addresses failed: '192.168.4.162:5222' failed because: /192.168.4.162 exception: java.net.ConnectException: failed to connect to /192.168.4.162 (port 5222) from /192.168.4.182 (port 39568) after 30000ms: isConnected failed: EHOSTUNREACH (No route to host)
however I am successfully able to build a connection to my server through any other client(psi, gajim, My web app(BOSH connection)).
following may help if networking is the issue:
$ nmap localhost
Starting Nmap 7.80 ( https://nmap.org ) at 2019-08-28 18:00 IST
Nmap scan report for localhost (127.0.0.1)
Host is up (0.000056s latency).
Not shown: 992 closed ports
PORT STATE SERVICE
111/tcp open rpcbind
139/tcp open netbios-ssn
445/tcp open microsoft-ds
631/tcp open ipp
5222/tcp open xmpp-client
5269/tcp open xmpp-server
5280/tcp open xmpp-bosh
8600/tcp open asterix
Nmap done: 1 IP address (1 host up) scanned in 0.09 seconds
I have been there and I found out the accidentally my phone and my ejabberd server were on different network. They should be on the same network as in this case. Make sure you are on same network and this error should go away.

Client cannot access server which bind loopback address in C#

Now a socket in server side binds 192.168.1.69:9000,and then start to listen. Client connects the server using 127.0.0.1:9000. But fail. However,it works when client connect the server using 192.168.1.69:9000. Client and server are both running on the same commputer.My question is: it should be successful When client using loopback address connect the server, but fail.Why?
Server Code:
this.pro_ListenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this.pro_ListenSocket.ReceiveBufferSize = this.pro_BufferSize;
this.pro_ListenSocket.SendBufferSize = this.pro_BufferSize;
try
{
this.pro_ListenSocket.Bind(new IPEndPoint(this.pro_ServerIP, this.pro_Port));
}
catch (SocketException socketError)
{
return false;
}
catch (Exception)
{
return false;
}
try
{
this.pro_OnRunning = true;
this.pro_ListenSocket.Listen(500);
this.StartToAcceptClient(this.pro_ListenSocket);
}
catch (Exception ex)
{
return false;
}
Loopback is represented as a network adapter, just like any other. You have set your server to only listen for connections on the adapter at 192.168.1.69. If you want your server to listen on additional adapters, the easiest approach is to make it available on all available adapters by specifying the address IPAddress.Any (0.0.0.0).
this.pro_ListenSocket.Bind(new IPEndPoint(IPAddress.Any, this.pro_Port));

RMI and 2 machines - two way communication

I've got problem with RMI comunication between 2 machines (win 7 and win xp VM). The exception with I have problem is:
java.rmi.ConnectException: Connection refused to host: 169.254.161.21; nested exception is:
java.net.ConnectException: Connection timed out: connect
It's really weired because during connection I use address 192.168.1.4 (server), but exception somehow show sth different. I disabled firewall on both side. Ping working to both side. I tried telnet to server and use server port:
telnet 192.168.1.4 1099 and it's working... I can't figure out where the problem is.
If I run this on host side (eg server side) everything works fine.
How is it look from SERVER:
public class Server
{
public static void main(String args[])
{
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(is);
String portNum, registryURL;
try{
System.out.println("Enter the RMIregistry port number:");
portNum = (br.readLine()).trim();
int RMIPortNum = Integer.parseInt(portNum);
startRegistry(RMIPortNum); // Registry registry = LocateRegistry.createRegistry(RMIPortNum);
ServerSide_Impl exportedObj = new ServerSide_Impl();
registryURL = "rmi://localhost:" + portNum + "/callback";
//registryURL = "rmi://192.168.1.4:" + portNum + "/callback";
Naming.rebind(registryURL, exportedObj);
System.out.println("Callback Server ready.");
}// end try
catch (Exception re) {
System.out.println(
"Exception in HelloServer.main: " + re);
} // end catch
} // end main
//This method starts a RMI registry on the local host, if
//it does not already exists at the specified port number.
private static void startRegistry(int RMIPortNum) throws RemoteException
{
try
{
Registry registry = LocateRegistry.getRegistry(RMIPortNum);
registry.list( );
// This call will throw an exception
// if the registry does not already exist
}
catch (RemoteException e)
{
Registry registry = LocateRegistry.createRegistry(RMIPortNum);
}
} // end startRegistry
} // end class
Client side is look like:
try
{
this.serverAd = serverAddress.getText();
String path = System.getProperty("user.dir");
String pathAfter = path.replace("\\", "/");
String pathFile = "file:/"+pathAfter + "/wideopen.policy";
System.setProperty("java.security.policy", pathFile);
System.setSecurityManager(new RMISecurityManager());
this.hostName = hostNameTextField.getText();
this.portNum = hostPortNumberTextField.getText();
RMIPort = Integer.parseInt(this.portNum);
this.time = Integer.parseInt(timeTextField.getText());
//this.registryURL = "rmi://localhost:" + this.portNum + "/callback";
String registryURLString = "rmi://"+this.serverAd+":" + this.portNum + "/callback";
this.registryURL = registryURLString;
ConsoleTextField.append("\n"+ this.registryURL + "\n");
// find the remote object and cast it to an
// interface object
obj = (ServerSide_Interface)Naming.lookup(this.registryURL);
boolean test = obj.Connect();
if(test)
{
callbackObj = new ClientSide_Impl();
// register for callback
obj.registerForCallback(callbackObj);
isConnected = true;
ConsoleTextField.append("Nawiązano połaczenie z serwerem\n");
TableModel modelTemp = obj.Server_GenerateStartValues();
myDataTable.setModel(modelTemp);
myDataTable.setEnabled(true);
}
else ConsoleTextField.append("Brak połączenia z serwerem\n");
}
catch (Exception ex ){
ConsoleTextField.append(ex + "\n");
System.out.println(ex);
}
This connection is working fine if I run client on host side. If I use VM and try connect between 2 different machines, I can;t figure out what did I do bad
There is something wrong with your etc/hosts file or your DNS setup. It is providing the wrong IP address to the server as the server's external IP address, so RMI embeds the wrong address into the stub, so the client attempts to connect to the wrong IP address.
If you can't fix that, you can set the system property java.rmi.server.hostname to the correct IP address at the server JVM, before exporting any RMI objects (including Registries). That tells RMI to embed that address in the stub.