Skip to content

Instantly share code, notes, and snippets.

@oskar456
Last active February 17, 2024 12:47
Show Gist options
  • Save oskar456/594f1b5e84ca887c439fb457800b377e to your computer and use it in GitHub Desktop.
Save oskar456/594f1b5e84ca887c439fb457800b377e to your computer and use it in GitHub Desktop.
Cloudflare WARP linux client (using wg-quick for actual tunnel setup)
#!/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()
#!/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}"
@idolm
Copy link

idolm commented Nov 15, 2019

how to copy gererated file to storage/shared?

@rus364
Copy link

rus364 commented Feb 3, 2020

It's not working for me. I'm connecting to the cloudflare network, but next I don't have access to the Internet.
I changed the resulting config for use with firewalld, but that is not the problem because it worked for me a week ago.

@oskar456
Copy link
Author

oskar456 commented Feb 3, 2020

From my experience, it does not work from time to time. Disconnecting and reconnecting usually fixes the problem for me. I guess this has something to do with the slight diversion of the Wireguard protocol used in Cloudflare's implementation.

@oskar456
Copy link
Author

oskar456 commented Feb 7, 2020

@luv2dnce33 this does not look like Linux. Your issue is very probably caused by missing IPv6 NAT rule from the fake IPv6 address 2001:db8… that I put into the config in order to avoid IPv6 depreference. You can probably fix your problem by removing the three lines below this comment in wgcf.conf:

# This fixes up IPv6 depreference due to the use of unique local addressing

@oskar456
Copy link
Author

Another reason could be a MTU issue (TLS handshake is usually big). Try lowering MTU of the tunnel interface.

@oskar456
Copy link
Author

Are there Mac OS equivalents for PostUp and PreDown procedures?

I have no idea, sorry.

@whoizit
Copy link

whoizit commented Mar 22, 2020

@oskar456 wgcf.sh also not works for me.
I getting all credentials (3, not-empty files) in ~/.wgcf
I don't get any errors from doas wg-quick up ~/.wgcf/wgcf.conf and I getting wgcf interface is up
but nothing is pinging, only 172.16.0.2 is pinging, 1.1.1.1 not pinging.
Web pages do not open, but telegram-desktop is works (how?)
I reduce MTU from 1400 to 1300 and 1280.
I commenting 3 strings, as you said

~ $ cat /etc/resolv.conf
# Generated by resolvconf
nameserver 1.1.1.1

on mobile phone warp is works with same internet provider as on desktop

@sersmaster
Copy link

sersmaster commented Mar 24, 2020

Hi. Both the python and bash script don't work for me anymore. I guess Cloudflare changed something on their end.
I get
"parse error: Invalid numeric literal at line 1, column 6"
"error code 1020"
when running the shell script.
Can you look into that :) ?

@oskar456
Copy link
Author

Indeed, the registration yields 403 error from Cloudflare. I don't know how to fix this.

@ihciah
Copy link

ihciah commented Mar 29, 2020

error code 1020 +1

@syphyr
Copy link

syphyr commented Mar 29, 2020

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.

@oskar456
Copy link
Author

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

@gurachan
Copy link

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