简体   繁体   中英

Websockets Secure with headers in Python

For my application i'm using secure websockets, which is working fine. But I would like to secure it a bit more.

For the websocket python server im using the websockets library (on asyncio). but when I check the path value which is sent with the websockets.serve(), I'll always get the path of the socket and the sent_ip is always local.

How can I change my configuration so I can block other ips which are trying to connect

Server.py

import ssl
import asyncio
import logging
import websockets
import pathlib

logging.basicConfig()

STATE = {'value': 0}

USERS = set()

async def register(websocket):
    USERS.add(websocket)
    print("connection made!")

async def unregister(websocket):
    USERS.remove(websocket)

async def update(websocket):
    await websocket.send("Jobnumber: 1")

async def counter(websocket, path):
    await register(websocket)
    addr, seq = websocket.remote_address
    print(addr) #ALWAYS localhost
    print(path) #always the same path /server/sock (as configured in NGNIX)

    try:
        async for message in websocket:
            print (message)

    finally:
        await unregister(websocket)

ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
ssl_context.load_cert_chain(
    pathlib.Path(__file__).with_name('privkey.pem'))

asyncio.get_event_loop().run_until_complete(
    websockets.serve(counter, '', 8004, ssl=ssl_context))
asyncio.get_event_loop().run_forever()

Nginx:

server {

root /var/www/html/;
index index.php index.html index.htm index.nginx-debian.html;

server_name [hidden];

location / {
    try_files $uri $uri/ =404;
}

location /server/sock {
    proxy_pass https://pythonserver;
    proxy_http_version 1.1;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";

}

location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}

listen [::]:443 ssl ipv6only=on; # managed by Certbot
listen 443 ssl; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

ssl_certificate /etc/letsencrypt/live/../fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/.../privkey.pem; # managed by

}

upstream pythonserver { server localhost:8004;

}

Try using this for Nginx, since you are using websockets as well:

server {
        listen 80 ;
        server_name <url>;
        large_client_header_buffers 8 32k;
  if ($http_user_agent ~* Googlebot) {  
    return 403; 
  }
        access_log /var/log/nginx/access.log;
        location / {
                add_header 'Access-Control-Allow-Origin' "$http_origin";
                add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE, PUT';
                add_header 'Access-Control-Allow-Credentials' 'true';
                add_header 'Access-Control-Allow-Headers' 'User-Agent,Keep-Alive,Content-Type';
                proxy_set_header Host $http_host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_pass https://<url>:443;
                proxy_read_timeout 90;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
                proxy_buffers 8 32k;
                proxy_buffer_size 64k;
        }
}




server {
      listen 443;
  server_name abc.com;
        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log warn;
        ssl on;
        ssl_certificate /etc/nginx/ssl/ssl.crt;
        ssl_certificate_key /etc/nginx/ssl/ssl.key;

       location / {
                add_header 'Access-Control-Allow-Origin' "$http_origin";
                add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE, PUT';
                add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Keep-Alive';
                add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
                add_header 'Access-Control-Allow-Credentials' 'true';
                proxy_set_header Host $http_host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_next_upstream error;
                proxy_pass http://pythonserver;
                add_header X-Upstream  $upstream_addr;
                add_header Host $http_host;
                proxy_read_timeout 90;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
                proxy_buffers 8 32k;
                proxy_buffer_size 64k;

        }

}

update url as your server name in 2 places.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM