0

I'm trying to connect to a websocket server that protected with CloudFlare through upgrade: websocket header. Expected result is 101 Switching Protocol. Using a raw Socket, I was able to connect into the server but with several issues such as SSLv3 Handshake Failure or the server doesn't give any response; sometimes occur.

import ssl
import socket

socketch = ssl._create_unverified_context().wrap_socket(socket.socket(), server_hostname='unpkg.com')
socketch.connect(('unpkg.com', 443))
socketch.sendall(b'''GET / HTTP/1.1\r
Host: identity.o2.co.uk.zainvps.tk\r
User-Agent: cpprestsdk/2.9.0\r
Upgrade: websocket\r
Connection: Upgrade\r
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r
Sec-WebSocket-Version: 13\r\n\r
''')
print(socketch.recv(10000))
print('')

Using a raw socket is unstable, so I think it's better to use requests module.

import requests

heading = {'Host':'identity.o2.co.uk.zainvps.tk','Connection':'upgrade','Upgrade':'websocket','Sec-Websocket-Version':'13','Sec-Websocket-Key':'dGhlIHNhbXBsZSBub25jZQ=='}

r = requests.get('https://unpkg.com', headers=heading)
print(r.status_code)

Using requests; the server responded with 403 status codes which means it's rejected by the CloudFlare protection but when using Socket, it gives the correct 101 status code. I'm assuming that it is because of wrapped socket gives an expected SSL Hostname through server_hostname.

Is this idea can also be implemented inside requests.Session()?

UPDATE 1: Someone mentioning about the use of CloudScraper module to bypass the CloudFlare protection. Using CloudScraper still returns in 403 status code with Custom Headers.

import cloudscraper

scraper = cloudscraper.create_scraper()
url = 'https://unpkg.com'
sc = scraper.get(url, headers={"Host": "usaws1.sshstores.vip", "Connection": "upgrade", "Upgrade": "websocket","Sec-WebSocket-Key": "dGhlIHNhbXBsZSBub25jZQ==", "Sec-WebSocket-Version": "13"})
print(sc.status_code)

enter image description here

  • Use CloudScraper, https://pypi.org/project/cloudscraper/ - it's really easy to setup and it works like a charm. Example here: https://stackoverflow.com/questions/49087990/python-request-being-blocked-by-cloudflare – Cow Aug 18 '22 at 06:23
  • I have used CloudScrapper but when using Custom Headers mentioned, it is also returns `403` status code. @user56700 –  Aug 18 '22 at 06:24
  • Ok, you didn't mention you tried it, so I assumed you didn't. – Cow Aug 18 '22 at 06:25
  • I can see on the CloudScraper doc you can set a custom header, have you tried that? – Cow Aug 18 '22 at 06:28
  • Thread updated.. consider to checking it out :) @user56700 –  Aug 18 '22 at 06:33

0 Answers0