wafsolver
wafsolver
Solve AWS WAF JavaScript challenges without a browser.
_Note: intended for accessing sites you are allowed to access programmatically._
Install
pip install wafsolver
Use
import requests
import wafsolver
DOMAIN = "example.com"
URL = f"https://{DOMAIN}/"
session = requests.Session()
res = session.get(URL)
if wafsolver.is_challenged(res.headers):
token = wafsolver.solve_challenge(DOMAIN, res.text)
session.cookies.set(wafsolver.TOKEN_COOKIE, token, domain=DOMAIN)
res = session.get(URL)
print(res.status_code, len(res.text))
Reuse one solver when you need several tokens, or want to refresh one:
from wafsolver import WafSolver
solver = WafSolver("example.com")
token = solver.solve(challenge_html)
refreshed = solver.solve(challenge_html, existing_token=token)
1""".. include:: ../README.md""" # noqa: D415 2 3import importlib.metadata 4 5from .challenge import ( 6 BANDWIDTH_CHALLENGE, 7 BANDWIDTH_SIZES, 8 SCRYPT_CHALLENGE, 9 SHA256_CHALLENGE, 10 select_solver, 11 solve_bandwidth, 12 solve_scrypt, 13 solve_sha256, 14) 15from .client import ( 16 ACTION_HEADER, 17 TOKEN_COOKIE, 18 WafSolver, 19 is_challenged, 20 parse_challenge_page, 21 solve_challenge, 22) 23from .errors import ( 24 ChallengePageError, 25 InvalidDifficultyError, 26 TokenRequestError, 27 UnsupportedChallengeError, 28 WafSolveError, 29) 30 31try: 32 __version__ = importlib.metadata.version(__name__) 33except importlib.metadata.PackageNotFoundError: 34 __version__ = "0.0.0" 35 36__all__ = ( 37 "ACTION_HEADER", 38 "BANDWIDTH_CHALLENGE", 39 "BANDWIDTH_SIZES", 40 "SCRYPT_CHALLENGE", 41 "SHA256_CHALLENGE", 42 "TOKEN_COOKIE", 43 "ChallengePageError", 44 "InvalidDifficultyError", 45 "TokenRequestError", 46 "UnsupportedChallengeError", 47 "WafSolveError", 48 "WafSolver", 49 "__version__", 50 "is_challenged", 51 "parse_challenge_page", 52 "select_solver", 53 "solve_bandwidth", 54 "solve_challenge", 55 "solve_scrypt", 56 "solve_sha256", 57)
11class ChallengePageError(WafSolveError): 12 """Raised when a page does not look like an AWS WAF challenge page."""
Raised when a page does not look like an AWS WAF challenge page.
28class InvalidDifficultyError(WafSolveError): 29 """Raised when a challenge reports a difficulty with no known meaning.""" 30 31 def __init__(self, difficulty: int) -> None: 32 """Initialize the error. 33 34 Args: 35 difficulty (int): The unusable difficulty. 36 """ 37 self.difficulty = difficulty 38 super().__init__(f"Invalid difficulty {difficulty}")
Raised when a challenge reports a difficulty with no known meaning.
31 def __init__(self, difficulty: int) -> None: 32 """Initialize the error. 33 34 Args: 35 difficulty (int): The unusable difficulty. 36 """ 37 self.difficulty = difficulty 38 super().__init__(f"Invalid difficulty {difficulty}")
Initialize the error.
Arguments:
- difficulty (int): The unusable difficulty.
41class TokenRequestError(WafSolveError): 42 """Raised when the token endpoint rejects the solution."""
Raised when the token endpoint rejects the solution.
15class UnsupportedChallengeError(WafSolveError): 16 """Raised when the WAF serves a challenge type this library cannot solve.""" 17 18 def __init__(self, challenge_type: str) -> None: 19 """Initialize the error. 20 21 Args: 22 challenge_type (str): The unrecognised challenge type identifier. 23 """ 24 self.challenge_type = challenge_type 25 super().__init__(f"Unsupported AWS WAF challenge type: {challenge_type}")
Raised when the WAF serves a challenge type this library cannot solve.
18 def __init__(self, challenge_type: str) -> None: 19 """Initialize the error. 20 21 Args: 22 challenge_type (str): The unrecognised challenge type identifier. 23 """ 24 self.challenge_type = challenge_type 25 super().__init__(f"Unsupported AWS WAF challenge type: {challenge_type}")
Initialize the error.
Arguments:
- challenge_type (str): The unrecognised challenge type identifier.
7class WafSolveError(Exception): 8 """Base class for every failure while solving a WAF challenge."""
Base class for every failure while solving a WAF challenge.
73class WafSolver: 74 """Solves AWS WAF challenges for a domain. 75 76 Args: 77 domain (str): The domain the token will be used for. 78 user_agent (str): The user agent to present, which must match the 79 one the fingerprint reports. Defaults to a recent Chrome. 80 impersonate (BrowserTypeLiteral): The TLS fingerprint ``curl_cffi`` 81 should imitate. 82 """ 83 84 def __init__( 85 self, 86 domain: str, 87 user_agent: str = fingerprint.USER_AGENT, 88 impersonate: BrowserTypeLiteral = "chrome", 89 ) -> None: 90 """Initialize the solver.""" 91 self.domain = domain 92 self.user_agent = user_agent 93 self.session = requests.Session(impersonate=impersonate) 94 self.session.headers.update( 95 { 96 "user-agent": user_agent, 97 "accept": "*/*", 98 "accept-language": "en-US,en;q=0.9", 99 "sec-fetch-site": "cross-site", 100 "sec-fetch-mode": "cors", 101 "sec-fetch-dest": "empty", 102 } 103 ) 104 105 def fetch_inputs(self, endpoint: str) -> dict[str, Any]: 106 """Fetch a fresh challenge from the token endpoint. 107 108 Args: 109 endpoint (str): The token endpoint, without a scheme. 110 111 Returns: 112 dict[str, Any]: The challenge inputs. 113 """ 114 res = self.session.get(f"https://{endpoint}/inputs?client=browser") 115 return dict(res.json()) 116 117 def build_envelope( 118 self, 119 inputs: Mapping[str, Any], 120 goku_props: Mapping[str, Any], 121 existing_token: str | None = None, 122 ) -> dict[str, Any]: 123 """Solve the challenge and build the envelope to post. 124 125 Args: 126 inputs (Mapping[str, Any]): The challenge inputs. 127 goku_props (Mapping[str, Any]): The props from the challenge page. 128 existing_token (str | None): A token to refresh, if any. 129 130 Returns: 131 dict[str, Any]: The envelope, carrying a ``_mode`` key naming the 132 endpoint it must be posted to. 133 """ 134 mode, solver = select_solver(str(inputs["challenge_type"])) 135 checksum, encrypted_fp = fingerprint.build(self.user_agent) 136 solution = solver(dict(inputs), checksum) 137 return { 138 "_mode": mode, 139 "challenge": inputs["challenge"], 140 "solution": solution, 141 "signals": [{"name": "Zoey", "value": {"Present": encrypted_fp}}], 142 "checksum": checksum, 143 "existing_token": existing_token, 144 "client": "Browser", 145 "domain": self.domain, 146 "metrics": fingerprint.build_metrics(), 147 "goku_props": dict(goku_props), 148 } 149 150 @staticmethod 151 def build_multipart_parts(body: Mapping[str, Any]) -> list[tuple[str, bytes]]: 152 """Split an envelope into the multipart fields ``mp_verify`` expects. 153 154 challenge.js moves the payload out of the JSON and posts it as a 155 separate field, leaving ``solution`` null in the metadata. 156 157 Args: 158 body (Mapping[str, Any]): The envelope to split. 159 160 Returns: 161 list[tuple[str, bytes]]: The ordered ``(name, data)`` fields. 162 """ 163 metadata = {k: v for k, v in body.items() if k != "_mode"} 164 solution = metadata["solution"] 165 metadata["solution"] = None 166 return [ 167 ("solution_metadata", json.dumps(metadata).encode()), 168 ("solution_data", str(solution).encode()), 169 ] 170 171 def submit(self, endpoint: str, envelope: Mapping[str, Any]) -> str: 172 """Post a solved envelope and return the token. 173 174 Args: 175 endpoint (str): The token endpoint, without a scheme. 176 envelope (Mapping[str, Any]): The envelope from 177 :meth:`build_envelope`. 178 179 Raises: 180 TokenRequestError: If the endpoint rejects the solution or returns 181 no token. 182 183 Returns: 184 str: The acquired token. 185 """ 186 body = dict(envelope) 187 mode = body.pop("_mode") 188 url = f"https://{endpoint}/{mode}" 189 190 if mode == "mp_verify": 191 # curl_cffi has no `files=`; multipart goes through CurlMime. 192 multipart = CurlMime() 193 for name, data in self.build_multipart_parts(body): 194 multipart.addpart(name=name, data=data) 195 res = self.session.post(url, multipart=multipart) 196 else: 197 res = self.session.post( 198 url, 199 json=body, 200 headers={"content-type": "text/plain;charset=UTF-8"}, 201 ) 202 203 if not res.ok: 204 msg = f"{url} returned HTTP {res.status_code}: {res.text[:200]}" 205 raise TokenRequestError(msg) 206 token = res.json().get("token") 207 if not token: 208 msg = f"{url} did not return a token." 209 raise TokenRequestError(msg) 210 return str(token) 211 212 def solve(self, challenge_html: str, existing_token: str | None = None) -> str: 213 """Solve a challenge page and return an ``aws-waf-token``. 214 215 Args: 216 challenge_html (str): The challenge page body served by the WAF. 217 existing_token (str | None): A token to refresh, if any. 218 219 Returns: 220 str: The acquired token. 221 """ 222 goku_props, endpoint = parse_challenge_page(challenge_html) 223 inputs = self.fetch_inputs(endpoint) 224 envelope = self.build_envelope(inputs, goku_props, existing_token) 225 return self.submit(endpoint, envelope)
Solves AWS WAF challenges for a domain.
Arguments:
- domain (str): The domain the token will be used for.
- user_agent (str): The user agent to present, which must match the one the fingerprint reports. Defaults to a recent Chrome.
- impersonate (BrowserTypeLiteral): The TLS fingerprint
curl_cffishould imitate.
84 def __init__( 85 self, 86 domain: str, 87 user_agent: str = fingerprint.USER_AGENT, 88 impersonate: BrowserTypeLiteral = "chrome", 89 ) -> None: 90 """Initialize the solver.""" 91 self.domain = domain 92 self.user_agent = user_agent 93 self.session = requests.Session(impersonate=impersonate) 94 self.session.headers.update( 95 { 96 "user-agent": user_agent, 97 "accept": "*/*", 98 "accept-language": "en-US,en;q=0.9", 99 "sec-fetch-site": "cross-site", 100 "sec-fetch-mode": "cors", 101 "sec-fetch-dest": "empty", 102 } 103 )
Initialize the solver.
105 def fetch_inputs(self, endpoint: str) -> dict[str, Any]: 106 """Fetch a fresh challenge from the token endpoint. 107 108 Args: 109 endpoint (str): The token endpoint, without a scheme. 110 111 Returns: 112 dict[str, Any]: The challenge inputs. 113 """ 114 res = self.session.get(f"https://{endpoint}/inputs?client=browser") 115 return dict(res.json())
Fetch a fresh challenge from the token endpoint.
Arguments:
- endpoint (str): The token endpoint, without a scheme.
Returns:
dict[str, Any]: The challenge inputs.
117 def build_envelope( 118 self, 119 inputs: Mapping[str, Any], 120 goku_props: Mapping[str, Any], 121 existing_token: str | None = None, 122 ) -> dict[str, Any]: 123 """Solve the challenge and build the envelope to post. 124 125 Args: 126 inputs (Mapping[str, Any]): The challenge inputs. 127 goku_props (Mapping[str, Any]): The props from the challenge page. 128 existing_token (str | None): A token to refresh, if any. 129 130 Returns: 131 dict[str, Any]: The envelope, carrying a ``_mode`` key naming the 132 endpoint it must be posted to. 133 """ 134 mode, solver = select_solver(str(inputs["challenge_type"])) 135 checksum, encrypted_fp = fingerprint.build(self.user_agent) 136 solution = solver(dict(inputs), checksum) 137 return { 138 "_mode": mode, 139 "challenge": inputs["challenge"], 140 "solution": solution, 141 "signals": [{"name": "Zoey", "value": {"Present": encrypted_fp}}], 142 "checksum": checksum, 143 "existing_token": existing_token, 144 "client": "Browser", 145 "domain": self.domain, 146 "metrics": fingerprint.build_metrics(), 147 "goku_props": dict(goku_props), 148 }
Solve the challenge and build the envelope to post.
Arguments:
- inputs (Mapping[str, Any]): The challenge inputs.
- goku_props (Mapping[str, Any]): The props from the challenge page.
- existing_token (str | None): A token to refresh, if any.
Returns:
dict[str, Any]: The envelope, carrying a
_modekey naming the endpoint it must be posted to.
150 @staticmethod 151 def build_multipart_parts(body: Mapping[str, Any]) -> list[tuple[str, bytes]]: 152 """Split an envelope into the multipart fields ``mp_verify`` expects. 153 154 challenge.js moves the payload out of the JSON and posts it as a 155 separate field, leaving ``solution`` null in the metadata. 156 157 Args: 158 body (Mapping[str, Any]): The envelope to split. 159 160 Returns: 161 list[tuple[str, bytes]]: The ordered ``(name, data)`` fields. 162 """ 163 metadata = {k: v for k, v in body.items() if k != "_mode"} 164 solution = metadata["solution"] 165 metadata["solution"] = None 166 return [ 167 ("solution_metadata", json.dumps(metadata).encode()), 168 ("solution_data", str(solution).encode()), 169 ]
Split an envelope into the multipart fields mp_verify expects.
challenge.js moves the payload out of the JSON and posts it as a
separate field, leaving solution null in the metadata.
Arguments:
- body (Mapping[str, Any]): The envelope to split.
Returns:
list[tuple[str, bytes]]: The ordered
(name, data)fields.
171 def submit(self, endpoint: str, envelope: Mapping[str, Any]) -> str: 172 """Post a solved envelope and return the token. 173 174 Args: 175 endpoint (str): The token endpoint, without a scheme. 176 envelope (Mapping[str, Any]): The envelope from 177 :meth:`build_envelope`. 178 179 Raises: 180 TokenRequestError: If the endpoint rejects the solution or returns 181 no token. 182 183 Returns: 184 str: The acquired token. 185 """ 186 body = dict(envelope) 187 mode = body.pop("_mode") 188 url = f"https://{endpoint}/{mode}" 189 190 if mode == "mp_verify": 191 # curl_cffi has no `files=`; multipart goes through CurlMime. 192 multipart = CurlMime() 193 for name, data in self.build_multipart_parts(body): 194 multipart.addpart(name=name, data=data) 195 res = self.session.post(url, multipart=multipart) 196 else: 197 res = self.session.post( 198 url, 199 json=body, 200 headers={"content-type": "text/plain;charset=UTF-8"}, 201 ) 202 203 if not res.ok: 204 msg = f"{url} returned HTTP {res.status_code}: {res.text[:200]}" 205 raise TokenRequestError(msg) 206 token = res.json().get("token") 207 if not token: 208 msg = f"{url} did not return a token." 209 raise TokenRequestError(msg) 210 return str(token)
Post a solved envelope and return the token.
Arguments:
- endpoint (str): The token endpoint, without a scheme.
- envelope (Mapping[str, Any]): The envelope from
build_envelope().
Raises:
- TokenRequestError: If the endpoint rejects the solution or returns no token.
Returns:
str: The acquired token.
212 def solve(self, challenge_html: str, existing_token: str | None = None) -> str: 213 """Solve a challenge page and return an ``aws-waf-token``. 214 215 Args: 216 challenge_html (str): The challenge page body served by the WAF. 217 existing_token (str | None): A token to refresh, if any. 218 219 Returns: 220 str: The acquired token. 221 """ 222 goku_props, endpoint = parse_challenge_page(challenge_html) 223 inputs = self.fetch_inputs(endpoint) 224 envelope = self.build_envelope(inputs, goku_props, existing_token) 225 return self.submit(endpoint, envelope)
Solve a challenge page and return an aws-waf-token.
Arguments:
- challenge_html (str): The challenge page body served by the WAF.
- existing_token (str | None): A token to refresh, if any.
Returns:
str: The acquired token.
38def is_challenged(headers: Mapping[str, str]) -> bool: 39 """Report whether a response is a WAF challenge rather than real content. 40 41 Args: 42 headers (Mapping[str, str]): The response headers. 43 44 Returns: 45 bool: True if the WAF intercepted the request with a challenge. 46 """ 47 return headers.get(ACTION_HEADER) == "challenge"
Report whether a response is a WAF challenge rather than real content.
Arguments:
- headers (Mapping[str, str]): The response headers.
Returns:
bool: True if the WAF intercepted the request with a challenge.
50def parse_challenge_page(html: str) -> tuple[dict[str, Any], str]: 51 """Extract the challenge parameters from a WAF stub page. 52 53 Args: 54 html (str): The challenge page body. 55 56 Raises: 57 ChallengePageError: If the page is not a WAF challenge page. 58 59 Returns: 60 tuple[dict[str, Any], str]: The ``gokuProps`` object and the token 61 endpoint (host plus path prefix, without a scheme). 62 """ 63 try: 64 props = html.split(_GOKU_MARKER)[1].split(";", maxsplit=1)[0] 65 goku_props = json.loads(props) 66 endpoint = html.split(_SCRIPT_MARKER)[1].split(_CHALLENGE_MARKER, maxsplit=1)[0] 67 except (IndexError, ValueError) as err: 68 msg = "Could not parse the AWS WAF challenge page." 69 raise ChallengePageError(msg) from err 70 return goku_props, endpoint
Extract the challenge parameters from a WAF stub page.
Arguments:
- html (str): The challenge page body.
Raises:
- ChallengePageError: If the page is not a WAF challenge page.
Returns:
tuple[dict[str, Any], str]: The
gokuPropsobject and the token endpoint (host plus path prefix, without a scheme).
134def select_solver( 135 challenge_type: str, 136) -> tuple[ChallengeMode, Callable[[dict[str, Any], str], str]]: 137 """Pick the endpoint mode and solver for a challenge type. 138 139 Args: 140 challenge_type (str): The challenge type identifier. 141 142 Raises: 143 UnsupportedChallengeError: If the challenge type is not recognised. 144 145 Returns: 146 tuple[ChallengeMode, Callable[[dict[str, Any], str], str]]: The 147 endpoint mode and a solver taking the challenge inputs and the 148 fingerprint checksum. 149 """ 150 if challenge_type == BANDWIDTH_CHALLENGE: 151 return "mp_verify", lambda inputs, _: solve_bandwidth(inputs["difficulty"]) 152 if challenge_type == SHA256_CHALLENGE: 153 return "verify", lambda inputs, checksum: solve_sha256( 154 inputs["challenge"]["input"], 155 checksum, 156 inputs["difficulty"], 157 ) 158 if challenge_type == SCRYPT_CHALLENGE: 159 return "verify", lambda inputs, checksum: solve_scrypt( 160 inputs["challenge"]["input"], 161 checksum, 162 inputs["difficulty"], 163 ) 164 raise UnsupportedChallengeError(challenge_type)
Pick the endpoint mode and solver for a challenge type.
Arguments:
- challenge_type (str): The challenge type identifier.
Raises:
- UnsupportedChallengeError: If the challenge type is not recognised.
Returns:
tuple[ChallengeMode, Callable[[dict[str, Any], str], str]]: The endpoint mode and a solver taking the challenge inputs and the fingerprint checksum.
113def solve_bandwidth(difficulty: int) -> str: 114 """Build the bandwidth challenge payload. 115 116 There is no work to do here: ``challenge.js`` allocates a zero-filled 117 buffer whose size depends on the difficulty and returns it base64 encoded. 118 119 Args: 120 difficulty (int): The challenge difficulty, selecting the payload size. 121 122 Raises: 123 InvalidDifficultyError: If the difficulty has no known payload size. 124 125 Returns: 126 str: The base64 encoded payload. 127 """ 128 size = BANDWIDTH_SIZES.get(difficulty) 129 if size is None: 130 raise InvalidDifficultyError(difficulty) 131 return base64.b64encode(b"\x00" * size).decode()
Build the bandwidth challenge payload.
There is no work to do here: challenge.js allocates a zero-filled
buffer whose size depends on the difficulty and returns it base64 encoded.
Arguments:
- difficulty (int): The challenge difficulty, selecting the payload size.
Raises:
- InvalidDifficultyError: If the difficulty has no known payload size.
Returns:
str: The base64 encoded payload.
228def solve_challenge( 229 domain: str, 230 challenge_html: str, 231 user_agent: str = fingerprint.USER_AGENT, 232) -> str: 233 """Solve a challenge page in one call. 234 235 Args: 236 domain (str): The domain the token will be used for. 237 challenge_html (str): The challenge page body served by the WAF. 238 user_agent (str): The user agent to present. 239 240 Returns: 241 str: The acquired ``aws-waf-token``. 242 """ 243 return WafSolver(domain, user_agent=user_agent).solve(challenge_html)
Solve a challenge page in one call.
Arguments:
- domain (str): The domain the token will be used for.
- challenge_html (str): The challenge page body served by the WAF.
- user_agent (str): The user agent to present.
Returns:
str: The acquired
aws-waf-token.
86def solve_scrypt(challenge_input: str, checksum: str, difficulty: int) -> str: 87 """Find a nonce whose scrypt digest meets the difficulty. 88 89 Args: 90 challenge_input (str): The challenge input string. 91 checksum (str): The fingerprint checksum, also used as the salt. 92 difficulty (int): Required number of leading zero bits. 93 94 Returns: 95 str: The winning nonce. 96 """ 97 base = challenge_input + checksum 98 salt = checksum.encode() 99 for nonce in itertools.count(): 100 digest = hashlib.scrypt( 101 f"{base}{nonce}".encode(), 102 salt=salt, 103 n=_SCRYPT_N, 104 r=_SCRYPT_R, 105 p=_SCRYPT_P, 106 dklen=_SCRYPT_DKLEN, 107 ) 108 if has_leading_zero_bits(digest, difficulty): 109 return str(nonce) 110 raise AssertionError # pragma: no cover - unreachable
Find a nonce whose scrypt digest meets the difficulty.
Arguments:
- challenge_input (str): The challenge input string.
- checksum (str): The fingerprint checksum, also used as the salt.
- difficulty (int): Required number of leading zero bits.
Returns:
str: The winning nonce.
67def solve_sha256(challenge_input: str, checksum: str, difficulty: int) -> str: 68 """Find a nonce whose SHA-256 digest meets the difficulty. 69 70 Args: 71 challenge_input (str): The challenge input string. 72 checksum (str): The fingerprint checksum. 73 difficulty (int): Required number of leading zero bits. 74 75 Returns: 76 str: The winning nonce. 77 """ 78 base = (challenge_input + checksum).encode() 79 for nonce in itertools.count(): 80 digest = hashlib.sha256(base + str(nonce).encode()).digest() 81 if has_leading_zero_bits(digest, difficulty): 82 return str(nonce) 83 raise AssertionError # pragma: no cover - unreachable
Find a nonce whose SHA-256 digest meets the difficulty.
Arguments:
- challenge_input (str): The challenge input string.
- checksum (str): The fingerprint checksum.
- difficulty (int): Required number of leading zero bits.
Returns:
str: The winning nonce.