Last active
February 17, 2024 12:47
-
-
Save oskar456/594f1b5e84ca887c439fb457800b377e to your computer and use it in GitHub Desktop.
Cloudflare WARP linux client (using wg-quick for actual tunnel setup)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import subprocess | |
import json | |
import os | |
from pathlib import Path | |
import requests | |
from requests.compat import urljoin | |
class CloudflareWarp(): | |
API_URL = "https://api.cloudflareclient.com/v0a774/" | |
_session = None | |
def __init__(self, account, token): | |
self.id = account | |
self.token = token | |
def __repr__(self): | |
return f"CloudflareWarp({self.id}, {self.token})" | |
def _getsession(self): | |
if self._session is None: | |
self._session = requests.session() | |
self._session.headers.update( | |
Authorization=f"Bearer {self.token}", | |
) | |
return self._session | |
def getregurl(self): | |
return urljoin(self.API_URL, f"reg/{self.id}") | |
def getregstate(self): | |
s = self._getsession() | |
self.state = s.get(self.getregurl()).json() | |
return self.state | |
def patchreg(self, data): | |
s = self._getsession() | |
self.state = s.patch(self.getregurl(), json=data).json() | |
return self.state | |
def submit_key(self, key): | |
return self.patchreg({"key": key}) | |
def deregister(self): | |
s = self._getsession() | |
s.delete(self.getregurl()) | |
@classmethod | |
def register(cls, creds_path=None): | |
url = urljoin(cls.API_URL, "reg") | |
r = requests.post(url).json() | |
print('Registered as', r['id'], 'with auth token', r['token']) | |
if creds_path: | |
with open(creds_path, "w") as outf: | |
json.dump(r, outf) | |
return cls(r['id'], r['token']) | |
@classmethod | |
def from_json(cls, path): | |
with open(path) as inf: | |
r = json.load(inf) | |
return cls(r['id'], r['token']) | |
def wg_keypair(): | |
p = subprocess.run( | |
["wg", "genkey"], | |
stdout=subprocess.PIPE, | |
encoding="ascii", | |
) | |
private = p.stdout.strip() | |
p = subprocess.run( | |
["wg", "pubkey"], | |
stdout=subprocess.PIPE, | |
encoding="ascii", | |
input=private, | |
) | |
return (private, p.stdout.strip()) | |
def wg_quick_conffile(privkey, cfconfig): | |
return f"""[Interface] | |
PrivateKey = {privkey} | |
Address = {cfconfig['interface']['addresses']['v4']} | |
Address = {cfconfig['interface']['addresses']['v6']} | |
DNS = 1.1.1.1 | |
MTU = 1400 | |
# This fixes up IPv6 depreference due to the use of unique local addressing | |
Address = 2001:db8{cfconfig['interface']['addresses']['v6'][9:]} | |
PostUp = ip6tables -t nat -I POSTROUTING 1 -o %i -j SNAT --to-source {cfconfig['interface']['addresses']['v6']} | |
PreDown = ip6tables -t nat -D POSTROUTING 1 | |
[Peer] | |
PublicKey = {cfconfig['peers'][0]['public_key']} | |
Endpoint = {cfconfig['peers'][0]['endpoint']['host']} | |
#Endpoint = {cfconfig['peers'][0]['endpoint']['v4']} | |
#Endpoint = {cfconfig['peers'][0]['endpoint']['v6']} | |
AllowedIPs = 0.0.0.0/0 | |
AllowedIPs = ::/0 | |
""" | |
def main(): | |
cfgpath = Path("~/.wgcf/").expanduser() | |
credfile = cfgpath / "creds.json" | |
wgfile = cfgpath / "wgcf.conf" | |
os.makedirs(cfgpath, exist_ok=True) | |
try: | |
cf = CloudflareWarp.from_json(credfile) | |
except (FileNotFoundError, json.decoder.JSONDecodeError): | |
cf = CloudflareWarp.register(credfile) | |
priv, pub = wg_keypair() | |
c = cf.submit_key(pub)["config"] | |
with open(wgfile, "w") as outf: | |
outf.write(wg_quick_conffile(priv, c)) | |
print("To connect, run as root:") | |
print("# wg-quick up", wgfile) | |
if __name__ == '__main__': | |
main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
set -euo pipefail | |
shopt -s inherit_errexit 2>/dev/null || true | |
# this script will generate wg-quick(8) config file | |
# in order to connect to Cloudflare Warp using Wireguard on Linux | |
# note: this is *absolutely not* an official client from Cloudflare | |
# Copyright (C) 2019 Ondrej Caletka | |
# based heavily on macOS client by Jay Freeman (saurik) | |
# Original source: https://cache.saurik.com/twitter/wgcf.sh | |
# Zero Clause BSD license {{{ | |
# | |
# Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. | |
# | |
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. | |
# }}} | |
if ! which jq >/dev/null || ! which wg >/dev/null; then | |
echo "Please install jq and wireguard-tools" | |
exit 0 | |
fi | |
mkdir -p ~/.wgcf | |
chmod 700 ~/.wgcf | |
prv=~/.wgcf/private.key | |
usr=~/.wgcf/identity.cfg | |
cnf=~/.wgcf/wgcf.conf | |
pub=$({ cat "${prv}" 2>/dev/null || wg genkey | tee "${prv}"; } | wg pubkey) | |
test -n "${pub}" | |
api=https://api.cloudflareclient.com/v0i1909051800 | |
ins() { vrb=$1; shift; curl -s -H 'user-agent:' -H 'content-type: application/json' -X "${vrb}" "${api}/$@"; } | |
sec() { ins "$@" -H 'authorization: Bearer '"${reg[1]}"''; } | |
cfgjson=$(if [[ -e "${usr}" ]]; then | |
reg=($(cat "${usr}")) | |
test "${#reg[@]}" -eq 2 | |
sec GET "reg/${reg[0]}" | |
else | |
reg=($(ins POST "reg" -d '{"install_id":"","tos":"'"$(date -u +%FT%T.000Z)"'","key":"'"${pub}"'","fcm_token":"","type":"ios","locale":"en_US"}' | | |
jq -r '.result|.id+" "+.token')) | |
test "${#reg[@]}" -eq 2 | |
echo "${reg[@]}" >"${usr}" | |
sec PATCH "reg/${reg[0]}" -d '{"warp_enabled":true}' | |
fi) | |
# echo $cfgjson | |
cfg=($(echo $cfgjson| jq -r '.result.config|(.peers[0]|.public_key+" "+.endpoint.host)+" "+(.interface.addresses|.v4+" "+.v6)')) | |
test "${#cfg[@]}" -eq 4 | |
cat >"$cnf" <<EOF | |
[Interface] | |
PrivateKey = $(cat "${prv}") | |
DNS = 1.1.1.1 | |
Address = ${cfg[2]} | |
Address = ${cfg[3]} | |
MTU = 1400 | |
# This fixes up IPv6 depreference due to the use of unique local addressing | |
Address = ${cfg[3]/#fd01:5ca1:/2001:db8:} | |
PostUp = ip6tables -t nat -I POSTROUTING 1 -o %i -j SNAT --to-source ${cfg[3]} | |
PreDown = ip6tables -t nat -D POSTROUTING 1 | |
[Peer] | |
PublicKey = ${cfg[0]} | |
AllowedIPs = 0.0.0.0/0 | |
AllowedIPs = ::/0 | |
Endpoint = ${cfg[1]} | |
EOF | |
echo "To connect, run as root:" | |
echo "# wg-quick up ${cnf}" | |
echo "" | |
echo "To disconnect, run as root:" | |
echo "# wg-quick down ${cnf}" |
This script still works: https://github.com/ViRb3/cloudflare-warp-wireguard-client/blob/master/wgcf.py
But I wish it was converted to bash shell. Maybe this can be used to figure out what is currently broken.
I'm pretty sure the problems are caused by missing components of JSON body sent to /reg
endpoint along here and here. It used to work with empty body, but probably due to people abusing referral registrations to get WARP+ credit for free (although I don't see any practical difference between WARP and WARP+), they made some stricter validation of registrations.
I don't have time right now to experiment with that. Feel free to experiment yourself or use some other implementations. This one looks pretty easy to use:
$ wget https://cf-warp.glitch.me/warp.conf
Traceback (most recent call last):
File "wgcf.py", line 124, in <module>
main()
File "wgcf.py", line 114, in main
cf = CloudflareWarp.register(credfile)
File "wgcf.py", line 54, in register
r = requests.post(url).json()
File "/usr/lib/python3/dist-packages/requests/models.py", line 897, in json
return complexjson.loads(self.text, **kwargs)
File "/usr/lib/python3.7/json/__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.7/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.7/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
error code 1020 +1