Skip to content

Bulk asynchronous downloader for multiple file hosts

feat: detect anubis protection (#1536)

NTFSvolume279bac0c6b61
diff --git a/cyberdrop_dl/clients/flaresolverr.py b/cyberdrop_dl/clients/flaresolverr.py
index 9728655d4..487134afe 100644
--- a/cyberdrop_dl/clients/flaresolverr.py
+++ b/cyberdrop_dl/clients/flaresolverr.py
@@ -8,9 +8,9 @@ from http.cookies import SimpleCookie
from typing import TYPE_CHECKING, Any
import aiohttp
-from bs4 import BeautifulSoup
from multidict import CIMultiDict, CIMultiDictProxy
+from cyberdrop_dl import ddos_guard
from cyberdrop_dl.compat import StrEnum
from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL
from cyberdrop_dl.exceptions import DDOSGuardError
@@ -112,10 +112,10 @@ class FlareSolverr:
raise invalid_response_error
self.manager.client_manager.cookies.update_cookies(resp.solution.cookies)
- self._check_user_agent(resp.solution)
+ await self._check_user_agent(resp.solution)
return resp.solution
- def _check_user_agent(self, solution: FlareSolverrSolution) -> None:
+ async def _check_user_agent(self, solution: FlareSolverrSolution) -> None:
cdl_user_agent = self.manager.global_config.general.user_agent
mismatch_ua_msg = (
"Config user_agent and flaresolverr user_agent do not match:"
@@ -123,10 +123,11 @@ class FlareSolverr:
f"\n Flaresolverr: '{solution.user_agent}'"
)
- soup = BeautifulSoup(solution.content, "html.parser")
- if self.manager.client_manager.check_ddos_guard(soup) or self.manager.client_manager.check_cloudflare(soup):
+ try:
+ await ddos_guard.check(solution.content)
+ except DDOSGuardError:
if solution.user_agent != cdl_user_agent:
- raise DDOSGuardError(mismatch_ua_msg)
+ raise DDOSGuardError(mismatch_ua_msg) from None
if solution.user_agent != cdl_user_agent:
msg = f"{mismatch_ua_msg}\n Response was successful but cookies will not be valid"
diff --git a/cyberdrop_dl/ddos_guard.py b/cyberdrop_dl/ddos_guard.py
new file mode 100644
index 000000000..843da62c3
--- /dev/null
+++ b/cyberdrop_dl/ddos_guard.py
@@ -0,0 +1,180 @@
+from __future__ import annotations
+
+import asyncio
+import dataclasses
+import hashlib
+import json
+import os
+import sys
+from typing import Protocol
+
+import yarl
+from bs4 import BeautifulSoup
+
+from cyberdrop_dl.exceptions import DDOSGuardError
+
+__all__ = ["check"]
+
+
+class _Response(Protocol):
+ @property
+ def content_type(self) -> str: ...
+ async def text(self) -> str: ...
+
+
+async def check(content: _Response | str, /) -> None:
+ if isinstance(content, str):
+ soup = BeautifulSoup(content, "html.parser")
+
+ elif "html" not in content.content_type:
+ return
+
+ else:
+ try:
+ soup = BeautifulSoup(await content.text(), "html.parser")
+ except UnicodeDecodeError:
+ return
+
+ for protection in (DDosGuard, CloudFlareTurnstile, Anubis):
+ if protection.check(soup):
+ raise DDOSGuardError(f"{protection.__name__} anti-bot protection detected")
+
+
+class DDosGuard:
+ TITLES = "Just a moment...", "DDoS-Guard"
+ SELECTOR = ", ".join(
+ (
+ "#cf-challenge-running",
+ ".ray_id",
+ ".attack-box",
+ "#cf-please-wait",
+ "#challenge-spinner",
+ "#trk_jschal_js",
+ "#turnstile-wrapper",
+ ".lds-ring",
+ )
+ )
+
+ @classmethod
+ def check(cls, soup: BeautifulSoup) -> bool:
+ if (title := soup.select_one("title")) and (title_str := title.string):
+ if any(title.casefold() == title_str.casefold() for title in cls.TITLES):
+ return True
+
+ return bool(soup.select_one(cls.SELECTOR))
+
+
+class CloudFlareTurnstile(DDosGuard):
+ TITLES = "Simpcity Cuck Detection", "Attention Required! | Cloudflare", "Sentinel CAPTCHA"
+ SELECTOR = ", ".join(
+ (
+ "captchawrapper",
+ "cf-turnstile",
+ "script[src*='challenges.cloudflare.com/turnstile']",
+ "script:-soup-contains('Dont open Developer Tools')",
+ )
+ )
+
+
+class Anubis(DDosGuard):
+ TITLES = ("Making sure you're not a bot!",)
+ CHALLENGE = "script#anubis_challenge:-soup-contains(algorithm)"
+ SELECTOR = ", ".join(
+ (
+ CHALLENGE,
+ "p:-soup-contains-own(the administrator of this website has set up Anubis to protect the server against the scourge of AI)",
+ ),
+ )
+
+ @classmethod
+ def parse_challenge(cls, soup: BeautifulSoup) -> _AnubisChallenge | None:
+ if script := soup.select_one(cls.CHALLENGE):
+ anubis = json.loads(script.get_text(strip=True))
+ return _AnubisChallenge(
+ difficulty=anubis["rules"]["difficulty"],
+ data=anubis["challenge"]["randomData"],
+ id=anubis["challenge"]["id"],
+ )
+
+ @classmethod
+ async def solve(cls, challenge: _AnubisChallenge) -> _AnubisSolution:
+ return await asyncio.to_thread(cls._solve, challenge)
+
+ @classmethod
+ def _solve(cls, challenge: _AnubisChallenge, *, timeout: int | None = 30) -> _AnubisSolution:
+ import multiprocessing as mp
+ import time
+ from concurrent.futures import ProcessPoolExecutor, as_completed
+
+ max_workers = min(cpu_count() // 2, 1)
+ start_time = time.monotonic()
+
+ with ProcessPoolExecutor(max_workers=max_workers, mp_context=mp.get_context("spawn")) as executor:
+ futures = [
+ executor.submit(_anubis_worker, idx, max_workers, challenge.data, challenge.difficulty)
+ for idx in range(max_workers)
+ ]
+
+ try:
+ for future in as_completed(futures, timeout=timeout):
+ result = future.result()
+ if result is not None:
+ nonce, hash = result
+ elapsed = time.monotonic() - start_time
+ executor.shutdown(wait=False, cancel_futures=True)
+ return _AnubisSolution(challenge.id, nonce, hash, challenge.difficulty, max_workers, elapsed)
+
+ except TimeoutError:
+ pass
+
+ elapsed = time.monotonic() - start_time
+ raise DDOSGuardError(f"Unable to solve challenge after {elapsed:0.2f} seconds: {challenge}")
+
+
[email protected](slots=True, frozen=True)
+class _AnubisChallenge:
+ id: str
+ data: str
+ difficulty: int
+
+
[email protected](slots=True, frozen=True)
+class _AnubisSolution:
+ id: str
+ nonce: int
+ hash: str
+ difficulty: int
+ workers: int = dataclasses.field(compare=False)
+ total_time: float = dataclasses.field(compare=False)
+
+ @property
+ def url(self) -> yarl.URL:
+ # this URl is relative to the origin url
+ return yarl.URL("/.within.website/x/cmd/anubis/api/pass-challenge").with_query(
+ id=self.id,
+ response=self.hash,
+ nonce=self.nonce,
+ elapsedTime=int(self.total_time * 1000),
+ )
+
+
+def _anubis_worker(start: int, step: int, challenge: str, difficulty: int) -> tuple[int, str] | None:
+ nonce = start
+ target = "0" * difficulty
+ while True:
+ hash = hashlib.sha256(f"{challenge}{nonce}".encode()).hexdigest()
+ if hash.startswith(target):
+ return nonce, hash
+ nonce += step
+
+
+if sys.platform not in ("win32", "darwin") and hasattr(os, "sched_getaffinity"):
+
+ def cpu_count() -> int:
+ return len(os.sched_getaffinity(0))
+
+
+else:
+
+ def cpu_count() -> int:
+ return os.cpu_count() or 1
diff --git a/cyberdrop_dl/managers/client_manager.py b/cyberdrop_dl/managers/client_manager.py
index eb266b38f..30ae3b287 100644
--- a/cyberdrop_dl/managers/client_manager.py
+++ b/cyberdrop_dl/managers/client_manager.py
@@ -13,20 +13,14 @@ import certifi
import truststore
from aiohttp import ClientResponse, ClientSession
from aiolimiter import AsyncLimiter
-from bs4 import BeautifulSoup
-from cyberdrop_dl import constants, env
+from cyberdrop_dl import constants, ddos_guard, env
from cyberdrop_dl.clients.download_client import DownloadClient
from cyberdrop_dl.clients.flaresolverr import FlareSolverr
from cyberdrop_dl.clients.response import AbstractResponse
from cyberdrop_dl.clients.scraper_client import ScraperClient
from cyberdrop_dl.data_structures.url_objects import AbsoluteHttpURL, MediaItem
-from cyberdrop_dl.exceptions import (
- DDOSGuardError,
- DownloadError,
- ScrapeError,
- TooManyCrawlerErrors,
-)
+from cyberdrop_dl.exceptions import DDOSGuardError, DownloadError, ScrapeError, TooManyCrawlerErrors
from cyberdrop_dl.ui.prompts.user_prompts import get_cookies_from_browsers
from cyberdrop_dl.utils.aio import WeakAsyncLocks
from cyberdrop_dl.utils.cookie_management import read_netscape_files
@@ -41,6 +35,7 @@ if TYPE_CHECKING:
from collections.abc import Callable, Generator, Iterable, Mapping
from http.cookies import BaseCookie
+ from bs4 import BeautifulSoup
from curl_cffi.requests import AsyncSession
from curl_cffi.requests.models import Response as CurlResponse
@@ -366,26 +361,14 @@ class ClientManager:
message = _DOWNLOAD_ERROR_ETAGS[e_tag]
raise DownloadError(HTTPStatus.NOT_FOUND, message=message)
- async def check_ddos_guard() -> BeautifulSoup | None:
- if "html" not in response.content_type:
- return
- try:
- soup = BeautifulSoup(await response.text(), "html.parser")
- except UnicodeDecodeError:
- return
- else:
- if self.check_ddos_guard(soup) or self.check_cloudflare(soup):
- raise DDOSGuardError
- return soup
-
check_etag()
if HTTPStatus.OK <= response.status < HTTPStatus.BAD_REQUEST:
# Check DDosGuard even on successful pages
- # await check_ddos_guard()
return
await self._check_json(response)
- await check_ddos_guard()
+
+ await ddos_guard.check(response)
raise DownloadError(status=response.status, message=message)
async def _check_json(self, response: AbstractResponse) -> None:
@@ -412,22 +395,6 @@ class ClientManager:
if content_length == "73003" and content_type == "video/mp4":
raise DownloadError(410) # Placeholder video with text "Video removed" (efukt)
- @staticmethod
- def check_ddos_guard(soup: BeautifulSoup) -> bool:
- if (title := soup.select_one("title")) and (title_str := title.string):
- if any(title.casefold() == title_str.casefold() for title in DDosGuard.TITLES):
- return True
-
- return bool(soup.select_one(DDosGuard.ALL_SELECTORS))
-
- @staticmethod
- def check_cloudflare(soup: BeautifulSoup) -> bool:
- if (title := soup.select_one("title")) and (title_str := title.string):
- if any(title.casefold() == title_str.casefold() for title in CloudflareTurnstile.TITLES):
- return True
-
- return bool(soup.select_one(CloudflareTurnstile.ALL_SELECTORS))
-
async def check_file_duration(self, media_item: MediaItem) -> bool:
"""Checks the file runtime against the config runtime limits."""
if media_item.is_segment:
diff --git a/tests/test_ddos_guard.py b/tests/test_ddos_guard.py
new file mode 100644
index 000000000..f1664ce80
--- /dev/null
+++ b/tests/test_ddos_guard.py
@@ -0,0 +1,65 @@
+import pytest
+from bs4 import BeautifulSoup
+
+from cyberdrop_dl import ddos_guard
+from cyberdrop_dl.exceptions import DDOSGuardError
+
+anubis_html = """
+ <!doctype html>
+ <html lang="en">
+ <head>
+ <title>Making sure you&#39;re not a bot!</title>
+ <script id="anubis_version" type="application/json">"v1.23.0"</script><script id="anubis_challenge" type="application/json">{"rules":{"algorithm":"fast","difficulty":5,"report_as":5},"challenge":{"id":"019abb13-2859-7587-bec3-16e0a3f67ce9","method":"fast","randomData":"1b7a4c4a35a9e11ac23c2ae78845476ed627d1f36c8c27c1b3386d7c6f997c2f803fbfd3884b9b51642859e02537a62b9032b8b58b38d4af400aa62c8293ba85","issuedAt":"2025-11-25T12:53:06.265369852Z","metadata":{"User-Agent":"Mozilla/5.0 (X11; Linux x86_64; rv:144.0) Gecko/20100101 Firefox/144.0","X-Real-Ip":""},"spent":false}}</script><script id="anubis_base_prefix" type="application/json">""</script><script id="anubis_public_url" type="application/json">""</script>
+ </head>
+ <body id="top">
+ <main>
+ <h1 id="title" class="centered-div">Making sure you&#39;re not a bot!</h1>
+ <div class="centered-div">
+ <img id="image" style="width:100%;max-width:256px;" src="/.within.website/x/cmd/anubis/static/img/pensive.webp?cacheBuster=v1.23.0"> <img style="display:none;" style="width:100%;max-width:256px;" src="/.within.website/x/cmd/anubis/static/img/happy.webp?cacheBuster=v1.23.0">
+ <p id="status">Loading...</p>
+ <script async type="module" src="/.within.website/x/cmd/anubis/static/js/main.mjs?cacheBuster=v1.23.0"></script>
+ <div id="progress" role="progressbar" aria-labelledby="status">
+ <div class="bar-inner"></div>
+ </div>
+ <details>
+ <p>You are seeing this because the administrator of this website has set up Anubis to protect the server against the scourge of AI companies aggressively scraping websites. This can and does cause downtime for the websites, which makes their resources inaccessible for everyone.</p>
+ </details>
+ </footer>
+ </main>
+ </body>
+ </html>
+"""
+anubis_soup = BeautifulSoup(anubis_html, "html.parser")
+
+
+def test_anubis_detection() -> None:
+ assert ddos_guard.Anubis.check(anubis_soup)
+
+
+def test_anubis_parse_challenge() -> None:
+ anubis = ddos_guard.Anubis.parse_challenge(anubis_soup)
+ assert anubis
+ assert anubis == ddos_guard._AnubisChallenge(
+ id="019abb13-2859-7587-bec3-16e0a3f67ce9",
+ data="1b7a4c4a35a9e11ac23c2ae78845476ed627d1f36c8c27c1b3386d7c6f997c2f803fbfd3884b9b51642859e02537a62b9032b8b58b38d4af400aa62c8293ba85",
+ difficulty=5,
+ )
+
+
+async def test_solve_anubis_challenge() -> None:
+ challenge = ddos_guard.Anubis.parse_challenge(anubis_soup)
+ assert challenge
+ solution = await ddos_guard.Anubis.solve(challenge)
+ assert solution == ddos_guard._AnubisSolution(
+ id="019abb13-2859-7587-bec3-16e0a3f67ce9",
+ nonce=1676094,
+ hash="00000e426afc08534b13bb3f75bad02dc20d73d70674b9dc174416cc7d3685e6",
+ workers=2,
+ difficulty=5,
+ total_time=0,
+ )
+
+
+async def test_ddos_response_should_raise_ddos_guard_error() -> None:
+ with pytest.raises(DDOSGuardError):
+ await ddos_guard.check(anubis_html)