Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Solve fix 403 forbidden when dial with CDN edge IP with Custom SNI #1554

Closed
mebest100 opened this issue Nov 20, 2024 · 4 comments
Closed

Solve fix 403 forbidden when dial with CDN edge IP with Custom SNI #1554

mebest100 opened this issue Nov 20, 2024 · 4 comments

Comments

@mebest100
Copy link

When dial with CDN edge IP with Custom SNI, such as url: wss://${cdn_edgeIP}:443/path, CDN will report 403 forbidden error
image

That is because CDN will verify both TLS SNI name and Host in request header , but your below code will take IP as Host in request header when dial with CDN edge IP

build_host(wsuri.host, wsuri.port, wsuri.secure)

Hence we need to correct this bug.
The test code as below:

import ssl
from websockets.client import connect
import asyncio
async def WssHandshake():
  
    server_host = '104.16.177.217' 
    server_port = 443  
    sni_hostname = 'testwebsocket.icanfly668.top'  

    
    ssl_context = ssl.create_default_context()


    headers = {
        'Host': sni_hostname,
        "User-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36"
    }

  
    uri = f"wss://{server_host}:{server_port}/ws"
    async with connect(uri=uri, ssl=ssl_context,server_hostname=sni_hostname, 
        extra_headers=headers, subprotocols=["chat"]) as websocket:
        await websocket.send("Hello, WebSocket with SNI!")
        response = await websocket.recv()
        print(response)

asyncio.run(WssHandshake())

I hv submitted the PR to fix this problem.
#1553

@aaugustin
Copy link
Member

i.e. use host="<cdn_edgeIP>" to force the IP rather the Host header to force the host.

@mebest100
Copy link
Author

Yes, it does work if take host parameter, but why?

I find below code seems relating to it.

     # If host and port are given, override values from the URI.
            host = kwargs.pop("host", host)
            port = kwargs.pop("port", port)
            create_connection = functools.partial(
                loop.create_connection, factory, host, port, **kwargs
            )

But I cannot find any clue why the given host can override values from the URI.
Could you explain it in details? Thx!

@aaugustin
Copy link
Member

Please read the documentation. It's explained in https://websockets.readthedocs.io/en/stable/reference/asyncio/client.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants