Question

I'm writing a java-websocket server as a cryptocurrency client.

For security reasons, I'd like to restrict access to the local machine.

Is there a way to restrict access to a java-websocket server by IP or hostname?

If so, how?

Was it helpful?

Solution

You should specify your listening ip to 127.0.0.1 thus it wont be possible to connect from the outside.

Edit

Looking at the example ChatServer.java the binding happens with

ChatServer s = new ChatServer( port );

The class implements two constructors:

  public ChatServer( int port ) throws UnknownHostException {
            super( new InetSocketAddress( port ) );
    }

    public ChatServer( InetSocketAddress address ) {
            super( address );
    }

So you could also call the server with an inetSocketAddress. Create one thats binds to localhost:

new ServerSocket(9090, 0, InetAddress.getByName(null));

and then call the server with that instead of just the port.

So replace

ChatServer s = new ChatServer( port );

with

InetSocketAddress myLocalSocket = new ServerSocket(9090, 0, InetAddress.getByName(null));
ChatServer s = new ChatServer( myLocalSocket );

in your example and it should work.

OTHER TIPS

The accepted answer by Max will prevent connections to your socket from outside, but there is another attack vector that you should consider.

A connection to your localhost WebSocket can be made by JavaScript hosted on any outside website. If your local user is tricked into visiting a remote site, the HTML/JavaScript hosted by that site will be able to communicate with your local web socket.

You may be able to mitigate this by restrict connections based Origin header value, which will indicates the script origin address generating the WebSocket connection request. Keep in mind that the Origin header is optional and you are relying on the browser to set it appropriately to where the script came from.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top