Skip to content

Instantly share code, notes, and snippets.

@oskar456 oskar456/wgcf.py
Last active Nov 15, 2019

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

idolm commented Nov 15, 2019

how to copy gererated file to storage/shared?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.