diff --git a/ipserv.py b/ipserv.py index adbe7d0..968ce9e 100644 --- a/ipserv.py +++ b/ipserv.py @@ -4,6 +4,7 @@ import time import os import aiohttp import random +import ipaddress from fastapi import FastAPI, Header, Request, Query, HTTPException from fastapi.responses import JSONResponse, PlainTextResponse from fastapi.staticfiles import StaticFiles @@ -94,6 +95,13 @@ async def ip( ip = X_Forwarded_For else: ip = request.client.host + + try: + _ip = ip_address.ip_address(ip) + if isinstance(_ip, ipaddress.IPv6Address): + raise HTTPException(400, detail="IPv6 is not supported at this time.") + except ValueError: + raise HTTPException(400, detail="%r does not appear to be a valid IP address" % ip) logging.info("looking up IP info for %s", ip) data = await make_request( @@ -119,6 +127,13 @@ async def lookup(ip: str = Query(...), User_Agent: str = Header("Mozilla/5.0")): logging.info("cache hit for %s", ip) return JSONResponse(data) logging.info("cache expired for %s", ip) + + try: + _ip = ip_address.ip_address(ip) + if isinstance(_ip, ipaddress.IPv6Address): + raise HTTPException(400, detail="IPv6 is not supported at this time.") + except ValueError: + raise HTTPException(400, detail="%r does not appear to be a valid IP address" % ip) logging.info("looking up IP info for %s", ip) data = await make_request( @@ -139,8 +154,13 @@ async def lookup(ip: str = Query(...), User_Agent: str = Header("Mozilla/5.0")): @app.get("/imfeelinglucky") async def im_feeling_lucky(req: Request): host = req.client.host - if host.count(".") != 3: - raise HTTPException(400, "IPv4 only endpoint.") + + try: + _ip = ip_address.ip_address(host) + if isinstance(_ip, ipaddress.IPv6Address): + raise HTTPException(400, detail="IPv6 is not supported at this time.") + except ValueError: + raise HTTPException(400, detail="%r does not appear to be a valid IP address" % host) data = await make_request(host, {"User-Agent": "Mozilla/5.0 Nex/19.04.2024"}) if not isinstance(data, dict):