Spaces:
Paused

KeyGuard-API / app.py
SeaWolf-AI's picture
KeyGuard address check API
8566b60 verified
Raw History Blame Contribute Delete
9.86 kB
# -*- coding: utf-8 -*-
"""KeyGuard address check. TLS handshake on port 443 only, returns the public certificate. The verdict is computed in the browser.
Targets and results are not stored or logged."""
import asyncio, collections, ipaddress, os, re, socket, ssl, time
from concurrent.futures import ThreadPoolExecutor
from cryptography import x509
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec, ed25519, ed448, rsa
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse, RedirectResponse
PORT, TIMEOUT, BUDGET = 443, 6.0, 20.0
PER_MIN, PER_DAY, PER_TARGET_HOUR, GLOBAL_MIN = 6, 60, 12, 60
HOPS = int(os.environ.get("TRUSTED_HOPS", "1")) # how many x-forwarded-for entries, from the right, to trust
ORIGINS = [o for o in os.environ.get("ORIGINS", "https://final-bench-keyguard.static.hf.space").split(",") if o]
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
app.add_middleware(CORSMiddleware, allow_origins=ORIGINS, allow_methods=["GET", "POST"], allow_headers=["content-type"], max_age=600)
POOL = ThreadPoolExecutor(max_workers=8)
SEM = asyncio.Semaphore(8)
HITS = collections.defaultdict(collections.deque)
CACHE, CACHE_SEC = collections.OrderedDict(), 600 # public certificates only, in memory, 10 minutes
BAD_NETS = [ipaddress.ip_network(n) for n in ("64:ff9b::/96", "64:ff9b:1::/48", "2002::/16", "2001::/32", "fec0::/10", "192.88.99.0/24", "168.63.129.16/32")]
LABEL = re.compile(r"(?!-)[a-z0-9-]{1,63}(?<!-)")
RSA_OID = bytes.fromhex("06092a864886f70d010101")
class Deny(Exception):
def __init__(self, code, status=400):
self.code, self.status = code, status
def allowed(ip):
ip = ipaddress.ip_address(str(ip).split("%")[0])
if ip.version == 6 and ip.ipv4_mapped:
ip = ip.ipv4_mapped
if not ip.is_global or ip.is_multicast or ip.is_reserved or ip.is_unspecified or ip.is_loopback or ip.is_link_local:
return False
return not any(ip.version == n.version and ip in n for n in BAD_NETS)
def parse_target(s):
"""One host name or IP. No port, path or user info (a leading https:// and one trailing / are stripped)."""
if not isinstance(s, str) or len(s) > 300:
raise Deny("bad_target")
s = re.sub(r"^https://", "", s.strip(), flags=re.I)
if s.endswith("/"):
s = s[:-1]
if s.startswith("[") and s.endswith("]"):
s = s[1:-1]
if "%" in s:
raise Deny("bad_target")
try:
return str(ipaddress.ip_address(s)), True
except ValueError:
pass
try:
h = s.rstrip(".").lower().encode("idna").decode("ascii")
except UnicodeError:
raise Deny("bad_target")
parts = h.split(".")
if len(h) > 253 or len(parts) < 2 or not all(LABEL.fullmatch(p) for p in parts) or not re.search(r"[a-z]", parts[-1]) or parts[-1].startswith("0x"):
raise Deny("bad_target")
if parts[-1] in ("local", "localhost", "internal", "lan", "home", "corp", "test", "invalid", "example", "onion", "arpa"):
raise Deny("private_target")
return h, False
def resolve(host, is_ip):
if is_ip:
ips = [host]
else:
try:
ips = list(dict.fromkeys(a[4][0] for a in socket.getaddrinfo(host, PORT, type=socket.SOCK_STREAM)))
except (OSError, UnicodeError):
raise Deny("dns")
if not ips:
raise Deny("dns")
if not all(allowed(i) for i in ips): # one private or special address is enough to refuse
raise Deny("private_target")
return sorted(ips, key=lambda i: ":" in i)[:2]
def context(rsa_only):
c = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
c.check_hostname = False
c.verify_mode = ssl.CERT_NONE
c.options |= getattr(ssl, "OP_LEGACY_SERVER_CONNECT", 0x4)
c.set_ciphers("aRSA:@SECLEVEL=0" if rsa_only else "ALL:@SECLEVEL=0")
c.minimum_version = ssl.TLSVersion.TLSv1 # old devices are the point
if rsa_only:
c.maximum_version = ssl.TLSVersion.TLSv1_2
return c
def handshake(ip, sni, rsa_only):
with socket.create_connection((ip, PORT), TIMEOUT) as s: # connect only to the address that was checked
s.settimeout(TIMEOUT)
with context(rsa_only).wrap_socket(s, server_hostname=sni) as w:
return w.getpeercert(True), w.version()
def describe(der):
d = {"type": "unknown", "bits": None, "issuer": "", "subject": "", "not_after": "", "self_signed": None}
try:
c = x509.load_der_x509_certificate(der)
except Exception:
d["type"] = "RSA" if RSA_OID in der else "unknown"
return d
def cn(n):
a = n.get_attributes_for_oid(x509.NameOID.COMMON_NAME) or n.get_attributes_for_oid(x509.NameOID.ORGANIZATION_NAME)
return str(a[0].value)[:120] if a else ""
try:
d.update(subject=cn(c.subject), issuer=cn(c.issuer), not_after=c.not_valid_after_utc.strftime("%Y-%m-%d"),
self_signed=c.subject == c.issuer, sha256=c.fingerprint(hashes.SHA256()).hex())
except Exception:
pass
try:
if c.public_key_algorithm_oid.dotted_string == "1.2.840.113549.1.1.1":
d["type"] = "RSA" # set before loading: very short or odd keys are refused by the library, and they are what we look for
k = c.public_key()
if isinstance(k, rsa.RSAPublicKey): d["type"] = "RSA"
elif isinstance(k, ec.EllipticCurvePublicKey): d["type"] = "EC"
elif isinstance(k, (ed25519.Ed25519PublicKey, ed448.Ed448PublicKey)): d["type"] = "EdDSA"
else: d["type"] = "other"
d["bits"] = getattr(k, "key_size", None)
except Exception:
pass
return d
def fetch(host, is_ip):
ips = resolve(host, is_ip)
sni, err, got, t0 = None if is_ip else host, "connect", None, time.time()
for ip in ips:
for rsa_only in (True, False):
if time.time() - t0 > BUDGET - TIMEOUT:
break
try:
der, ver = handshake(ip, sni, rsa_only)
except TimeoutError:
err = "timeout"
break
except ssl.SSLError:
err = "tls"
continue
except ConnectionResetError:
err = "tls"
continue
except OSError:
break
if der:
got = (der, ver, describe(der))
if got[2]["type"] == "RSA":
return ip, got
if got:
return ip, got
raise Deny(err, 200)
def client_ip(req):
xs = [x.strip() for x in req.headers.get("x-forwarded-for", "").split(",") if x.strip()]
v = xs[-HOPS] if len(xs) >= HOPS else (req.client.host if req.client else "")
try:
return str(ipaddress.ip_address(v))
except ValueError:
return ""
def rate_key(ip):
a = ipaddress.ip_address(ip) if ip else None
return str(ipaddress.ip_network(ip + "/64", False)) if a and a.version == 6 else (ip or "unknown")
def limit(key, n, sec, now):
q = HITS[key]
while q and q[0] < now - sec:
q.popleft()
if len(q) >= n:
raise Deny("rate", 429)
return q
def check_rate(who, target, cached):
now = time.time()
qs = [limit(("m", who), PER_MIN, 60, now), limit(("d", who), PER_DAY, 86400, now)]
if not cached: # a cached answer makes no connection
qs += [limit(("g",), GLOBAL_MIN, 60, now), limit(("t", target), PER_TARGET_HOUR, 3600, now)]
for q in qs:
q.append(now)
if len(HITS) > 5000:
for k in [k for k, q in HITS.items() if not q or q[-1] < now - 86400]:
del HITS[k]
@app.middleware("http")
async def hdr(req, call):
r = await call(req)
r.headers["X-Content-Type-Options"] = "nosniff"
r.headers["Referrer-Policy"] = "no-referrer"
if req.url.path.startswith("/api/"):
r.headers["Cache-Control"] = "no-store"
return r
@app.get("/api/myip")
async def myip(req: Request):
ip = client_ip(req)
return {"ip": ip, "public": bool(ip) and allowed(ip)}
@app.post("/api/cert")
async def cert(req: Request):
try:
if req.headers.get("origin") not in ORIGINS:
raise Deny("origin", 403)
if req.headers.get("content-type", "").split(";")[0].strip() != "application/json" or int(req.headers.get("content-length") or 9999) > 2000:
raise Deny("bad_request")
try:
b = await req.json()
except Exception:
raise Deny("bad_request")
if not isinstance(b, dict) or b.get("consent") is not True:
raise Deny("consent")
host, is_ip = parse_target(b.get("target"))
if is_ip and not allowed(host):
raise Deny("private_target")
hit = CACHE.get(host)
hit = hit[1] if hit and time.time() - hit[0] < CACHE_SEC else None
check_rate(rate_key(client_ip(req)), host, hit is not None)
if hit:
return hit
async with SEM:
try:
ip, (der, ver, d) = await asyncio.wait_for(asyncio.get_running_loop().run_in_executor(POOL, fetch, host, is_ip), BUDGET + 5)
except asyncio.TimeoutError:
raise Deny("timeout", 200)
out = {"ok": True, "target": host, "ip": ip, "tls": ver, "pem": ssl.DER_cert_to_PEM_cert(der) if len(der) < 60000 else "", **d}
CACHE[host] = (time.time(), out)
while len(CACHE) > 500:
CACHE.popitem(last=False)
return out
except Deny as e:
return JSONResponse({"ok": False, "error": e.code}, status_code=e.status)
except Exception:
return JSONResponse({"ok": False, "error": "internal"}, status_code=500)
@app.get("/")
async def home():
return RedirectResponse("https://huggingface.co/spaces/FINAL-Bench/KeyGuard")