Search code examples
apachewebsocketreverse-proxy

Handling the Content Security Policy directive for websockets in Apache


I have a websocket application running and Apache configured to serve it via reverse proxy. Here is the apache config

<VirtualHost *:80>
    ServerName 192.168.2.121

    # Proxy for WebSocket
    ProxyPass /ssh/websocket ws://192.168.2.121:8086/ssh/websocket
    ProxyPassReverse /ssh/websocket ws://192.168.2.121:8086/ssh/websocket

    
    # Content Security Policy
    Header always set Content-Security-Policy "default-src 'self'; connect-src 'self' ws://192.168.2.121:8086; script-src 'self';"
    # ErrorLog and CustomLog
    ErrorLog /var/opt/oe/base/log/gui/websocketapp_error.log
    CustomLog /var/opt/oe/base/log/gui/websocketapp_access.log combined

    <Directory /opt/oe/toposrv/sbin/ >
        Require all granted
    </Directory>
    <Directory /var/opt/oe/base/log/gui >
        Require all granted
    </Directory>
</VirtualHost>

When I try to send a connection request for the websocket I get the following error

Refused to connect to 'ws://192.168.2.121:8086/ssh/websocket?username=&password=&node_name=edge1-site1' because it violates the following Content Security Policy directive: "default-src 'self'". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.

Is there something wrong with the config?


Solution

  • Found the solution to the problem. The Apache server was running on port 8084 and the websocket webapp was running on port 8086. The fix was to adjust the port changes as follows:

    <VirtualHost *:8084>
        ServerName 192.168.2.121:8084
    
        # Proxy for WebSocket
        ProxyPass /ssh/websocket ws://192.168.2.121:8086/ssh/websocket
        ProxyPassReverse /ssh/websocket ws://192.168.2.121:8086/ssh/websocket
    
        
        # Content Security Policy
        Header always set Content-Security-Policy "default-src 'self'; connect-src 'self' ws://192.168.2.121:8084; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self';"
        # ErrorLog and CustomLog
        ErrorLog /var/opt/oe/base/log/gui/websocketapp_error.log
        CustomLog /var/opt/oe/base/log/gui/websocketapp_access.log combined
    
        <Directory /opt/oe/toposrv/sbin/ >
            Require all granted
        </Directory>
        <Directory /var/opt/oe/base/log/gui >
            Require all granted
        </Directory>
    </VirtualHost>