ctfd-dl 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,121 @@
1
+ Metadata-Version: 2.4
2
+ Name: ctfd-dl
3
+ Version: 1.0.0
4
+ Summary: CTFd challenge downloader and organizer
5
+ Home-page: https://github.com/tikipiya/ctfd-dl
6
+ Author: tikisan
7
+ Author-email:
8
+ License: MIT
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Requires-Python: >=3.10
17
+ Description-Content-Type: text/markdown
18
+ Requires-Dist: requests>=2.31.0
19
+ Requires-Dist: tqdm>=4.66.0
20
+ Requires-Dist: python-dotenv>=1.0.0
21
+ Requires-Dist: PyYAML>=6.0
22
+ Requires-Dist: urllib3>=2.0.0
23
+ Requires-Dist: pytest>=7.4.0
24
+ Requires-Dist: pytest-mock>=3.12.0
25
+ Dynamic: author
26
+ Dynamic: classifier
27
+ Dynamic: description
28
+ Dynamic: description-content-type
29
+ Dynamic: home-page
30
+ Dynamic: license
31
+ Dynamic: requires-dist
32
+ Dynamic: requires-python
33
+ Dynamic: summary
34
+
35
+ # CTFd Downloader
36
+
37
+ CTFd インスタンスから課題情報と添付ファイルを自動取得・整理する Python ツールです。
38
+
39
+ ## 機能
40
+
41
+ - Token 認証またはユーザ名/パスワード認証による CTFd API へのアクセス
42
+ - 課題一覧・詳細情報の取得
43
+ - 添付ファイルの自動ダウンロード
44
+ - `challenges/<Category>/<Challenge Name>/` の構造で整理保存
45
+ - メタデータ(JSON)と README(Markdown)の自動生成
46
+ - 並列ダウンロードとリトライ機能
47
+ - ロギングとエラーハンドリング
48
+
49
+ ## インストール
50
+
51
+ ```bash
52
+ pip install ctfd-dl
53
+ ```
54
+
55
+ ## 設定
56
+
57
+ 1. `config.example.yaml` を `config.yaml` にコピー
58
+ 2. `config.yaml` を編集して CTFd インスタンスの情報を設定
59
+
60
+ ```yaml
61
+ base_url: "https://ctf.example.com"
62
+ api_token: "your_api_token_here" # 推奨
63
+ # または
64
+ username: "your_username"
65
+ password: "your_password"
66
+ output_dir: "./challenges"
67
+ concurrency: 4
68
+ ```
69
+
70
+ または環境変数を使用:
71
+
72
+ ```bash
73
+ export CTFD_BASE_URL="https://ctf.example.com"
74
+ export CTFD_API_TOKEN="your_api_token_here"
75
+ ```
76
+
77
+ ## 使用方法
78
+
79
+ パッケージをインストールすると、`ctfd-dl` コマンドが利用可能になります。
80
+
81
+ ```bash
82
+ # 基本的な使用
83
+ ctfd-dl --config config.yaml
84
+
85
+ # コマンドライン引数で設定を上書き
86
+ ctfd-dl --base-url https://ctf.example.com --token YOUR_TOKEN --output ./my_challenges
87
+
88
+ # メタデータのみ取得(ファイルダウンロードをスキップ)
89
+ ctfd-dl --skip-download
90
+
91
+ # 詳細ログを出力
92
+ ctfd-dl --verbose
93
+ ```
94
+
95
+ ## 出力構造
96
+
97
+ ```
98
+ challenges/
99
+ └─ <Category>/
100
+ └─ <Challenge Name>/
101
+ ├─ files/
102
+ │ ├─ attached1.zip
103
+ │ └─ script.py
104
+ ├─ metadata.json
105
+ └─ README.md
106
+ ```
107
+
108
+ ## 注意事項
109
+
110
+ - **法的注意**: 他者運営の CTFd インスタンスにアクセスする場合は、必ず運営者の許可を得てください。
111
+ - **セキュリティ**: ダウンロードした実行ファイルは直接実行せず、適切な環境で解析してください。
112
+ - **サーバ負荷**: 並列ダウンロード数(`concurrency`)を適切に設定し、サーバに負荷をかけないようにしてください。
113
+
114
+ ## ライセンス
115
+
116
+ MIT License
117
+
118
+ ## 作者
119
+
120
+ tikisan (GitHub: @tikipiya)
121
+
@@ -0,0 +1,15 @@
1
+ ctfd_downloader/__init__.py,sha256=QM-JaPEK677802x2QN8tZWLwuswHclKqLxx9AvyW5ks,54
2
+ ctfd_downloader/client.py,sha256=s_79Fdtc5atlL9J4SOEalw7s80MI9Yy1k4NCZRrGPc8,7383
3
+ ctfd_downloader/config.py,sha256=9eLxE5hdZjdnViThNKUNebWXhTPL9326aE7Pe8eruGc,3278
4
+ ctfd_downloader/downloader.py,sha256=4-zJW2c-NJTGm7YBKr3Ut-XLiXFy2hxoDUCLU1T5TGY,5547
5
+ ctfd_downloader/main.py,sha256=Y_TjG-ECvCusJvVxCTFX9leRj_6n7-L9MzLhYZcpY2g,7047
6
+ ctfd_downloader/storage.py,sha256=PQQ0ZM0NNX4kieENVMHrMzv5dA1HsGcxo4LGyPRJ3AY,5305
7
+ tests/__init__.py,sha256=d8lN19U5sdzN6HTLtk5d_pQyOJizPRVEM5nG8FOxmyU,43
8
+ tests/test_client.py,sha256=ig5nK-erkq29dmkLQq6Q6MWJ8vdQI96SxQaTF74n0jM,2454
9
+ tests/test_downloader.py,sha256=A5jIC10zC-tB0nyVtxLbvlTTnXDIrbqd_NRUF6vDRk4,3482
10
+ tests/test_storage.py,sha256=Tr5oiD7A2MeurT9cO2I81MfgQ069RPOiHCfwSYZwNtc,3683
11
+ ctfd_dl-1.0.0.dist-info/METADATA,sha256=B-D_ML7_N39_yvTp-qi93W9nMPTuSfeVQo0__l4SWbc,3317
12
+ ctfd_dl-1.0.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
13
+ ctfd_dl-1.0.0.dist-info/entry_points.txt,sha256=HyB_xrh_05HHEvNyqFqXZrZUZnQ7Cj4eLfmfW0n2o-M,54
14
+ ctfd_dl-1.0.0.dist-info/top_level.txt,sha256=136ojiqLrEhXOcSIJetUnwsRjsZb_kGwRjrDL9CRs9Y,22
15
+ ctfd_dl-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ ctfd-dl = ctfd_downloader.main:main
@@ -0,0 +1,2 @@
1
+ ctfd_downloader
2
+ tests
@@ -0,0 +1,3 @@
1
+ """CTFd Downloader package."""
2
+ __version__ = "1.0.0"
3
+
@@ -0,0 +1,207 @@
1
+ """CTFd API クライアント."""
2
+ import time
3
+ import logging
4
+ import requests
5
+ from typing import List, Dict, Optional, Any
6
+ from urllib.parse import urljoin
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ class CTFdClient:
12
+ """CTFd API クライアント."""
13
+
14
+ def __init__(
15
+ self,
16
+ base_url: str,
17
+ api_token: Optional[str] = None,
18
+ username: Optional[str] = None,
19
+ password: Optional[str] = None,
20
+ ):
21
+ """
22
+ クライアントを初期化.
23
+
24
+ Args:
25
+ base_url: CTFd インスタンスのベースURL
26
+ api_token: API トークン(優先)
27
+ username: ユーザ名(Tokenがない場合)
28
+ password: パスワード(Tokenがない場合)
29
+ """
30
+ self.base_url = base_url.rstrip("/")
31
+ self.api_token = api_token
32
+ self.username = username
33
+ self.password = password
34
+ self.session = requests.Session()
35
+ self.authenticated = False
36
+
37
+ # HTTPS を強制
38
+ if not self.base_url.startswith("https://"):
39
+ logger.warning(f"BASE_URL が HTTPS ではありません: {self.base_url}")
40
+
41
+ def authenticate(self) -> bool:
42
+ """
43
+ 認証を実行.
44
+
45
+ Returns:
46
+ 認証成功時 True
47
+ """
48
+ if self.api_token:
49
+ return self._authenticate_with_token()
50
+ elif self.username and self.password:
51
+ return self._authenticate_with_credentials()
52
+ else:
53
+ logger.error("認証情報が設定されていません(API_TOKEN または USERNAME/PASSWORD)")
54
+ return False
55
+
56
+ def _authenticate_with_token(self) -> bool:
57
+ """Token 認証を実行."""
58
+ try:
59
+ self.session.headers.update({"Authorization": f"Token {self.api_token}"})
60
+ # 認証確認のためユーザ情報を取得
61
+ response = self.session.get(f"{self.base_url}/api/v1/users/me")
62
+ if response.status_code == 200:
63
+ self.authenticated = True
64
+ logger.info("Token 認証に成功しました")
65
+ return True
66
+ else:
67
+ logger.error(f"Token 認証に失敗しました: {response.status_code}")
68
+ return False
69
+ except Exception as e:
70
+ logger.error(f"Token 認証中にエラーが発生しました: {e}")
71
+ return False
72
+
73
+ def _authenticate_with_credentials(self) -> bool:
74
+ """ユーザ名/パスワード認証を実行."""
75
+ try:
76
+ # CSRF トークンを取得
77
+ login_page = self.session.get(f"{self.base_url}/login")
78
+ if login_page.status_code != 200:
79
+ logger.error(f"ログインページの取得に失敗しました: {login_page.status_code}")
80
+ return False
81
+
82
+ # CSRF トークンを抽出(CTFd の実装に依存)
83
+ # 一般的には hidden input または meta tag から取得
84
+ csrf_token = None
85
+ if "csrfNonce" in login_page.text:
86
+ import re
87
+ match = re.search(r'csrfNonce["\']?\s*[:=]\s*["\']([^"\']+)["\']', login_page.text)
88
+ if match:
89
+ csrf_token = match.group(1)
90
+
91
+ # ログインリクエスト
92
+ login_data = {
93
+ "name": self.username,
94
+ "password": self.password,
95
+ }
96
+ if csrf_token:
97
+ login_data["nonce"] = csrf_token
98
+
99
+ response = self.session.post(
100
+ f"{self.base_url}/login",
101
+ data=login_data,
102
+ allow_redirects=False,
103
+ )
104
+
105
+ if response.status_code in [200, 302]:
106
+ # Cookie が設定されているか確認
107
+ if self.session.cookies:
108
+ self.authenticated = True
109
+ logger.info("ユーザ名/パスワード認証に成功しました")
110
+ return True
111
+ else:
112
+ logger.error("認証に失敗しました(Cookie が設定されませんでした)")
113
+ return False
114
+ else:
115
+ logger.error(f"ログインに失敗しました: {response.status_code}")
116
+ return False
117
+ except Exception as e:
118
+ logger.error(f"認証中にエラーが発生しました: {e}")
119
+ return False
120
+
121
+ def list_challenges(self) -> List[Dict[str, Any]]:
122
+ """
123
+ 課題一覧を取得.
124
+
125
+ Returns:
126
+ 課題のリスト
127
+ """
128
+ if not self.authenticated:
129
+ logger.error("認証されていません")
130
+ return []
131
+
132
+ try:
133
+ challenges = []
134
+ page = 1
135
+ while True:
136
+ response = self.session.get(
137
+ f"{self.base_url}/api/v1/challenges",
138
+ params={"page": page},
139
+ )
140
+ if response.status_code != 200:
141
+ logger.error(f"課題一覧の取得に失敗しました: {response.status_code}")
142
+ break
143
+
144
+ data = response.json()
145
+ if "data" in data:
146
+ page_challenges = data["data"]
147
+ if not page_challenges:
148
+ break
149
+ challenges.extend(page_challenges)
150
+ # ページネーション確認
151
+ meta = data.get("meta", {})
152
+ if meta.get("page", page) >= meta.get("pages", 1):
153
+ break
154
+ page += 1
155
+ else:
156
+ break
157
+
158
+ logger.info(f"{len(challenges)} 件の課題を取得しました")
159
+ return challenges
160
+ except Exception as e:
161
+ logger.error(f"課題一覧の取得中にエラーが発生しました: {e}")
162
+ return []
163
+
164
+ def get_challenge(self, challenge_id: int) -> Optional[Dict[str, Any]]:
165
+ """
166
+ 課題詳細を取得.
167
+
168
+ Args:
169
+ challenge_id: 課題ID
170
+
171
+ Returns:
172
+ 課題詳細データ
173
+ """
174
+ if not self.authenticated:
175
+ logger.error("認証されていません")
176
+ return None
177
+
178
+ try:
179
+ response = self.session.get(f"{self.base_url}/api/v1/challenges/{challenge_id}")
180
+ if response.status_code == 200:
181
+ data = response.json()
182
+ return data.get("data")
183
+ else:
184
+ logger.warning(f"課題 {challenge_id} の取得に失敗しました: {response.status_code}")
185
+ return None
186
+ except Exception as e:
187
+ logger.error(f"課題 {challenge_id} の取得中にエラーが発生しました: {e}")
188
+ return None
189
+
190
+ def get_file_url(self, relative_path: str) -> str:
191
+ """
192
+ ファイルの絶対URLを取得.
193
+
194
+ Args:
195
+ relative_path: 相対パスまたは絶対URL
196
+
197
+ Returns:
198
+ 絶対URL
199
+ """
200
+ if relative_path.startswith("http://") or relative_path.startswith("https://"):
201
+ return relative_path
202
+ # 相対パスの場合、base_url と結合
203
+ if relative_path.startswith("/"):
204
+ return urljoin(self.base_url, relative_path)
205
+ else:
206
+ return urljoin(f"{self.base_url}/", relative_path)
207
+
@@ -0,0 +1,110 @@
1
+ """設定管理モジュール."""
2
+ import os
3
+ import yaml
4
+ import logging
5
+ from pathlib import Path
6
+ from typing import Optional, Dict, Any
7
+ from dotenv import load_dotenv
8
+
9
+ # .env ファイルを読み込み
10
+ load_dotenv()
11
+
12
+
13
+ class Config:
14
+ """設定管理クラス."""
15
+
16
+ def __init__(self, config_path: Optional[str] = None):
17
+ """
18
+ 設定を初期化.
19
+
20
+ Args:
21
+ config_path: 設定ファイルのパス(デフォルト: config.yaml)
22
+ """
23
+ self.config_path = config_path or "config.yaml"
24
+ self.config: Dict[str, Any] = {}
25
+ self._load_config()
26
+
27
+ def _load_config(self):
28
+ """設定ファイルを読み込む."""
29
+ if os.path.exists(self.config_path):
30
+ with open(self.config_path, "r", encoding="utf-8") as f:
31
+ self.config = yaml.safe_load(f) or {}
32
+ else:
33
+ self.config = {}
34
+
35
+ # 環境変数で上書き
36
+ self.config.setdefault("base_url", os.getenv("CTFD_BASE_URL", ""))
37
+ self.config.setdefault("api_token", os.getenv("CTFD_API_TOKEN", ""))
38
+ self.config.setdefault("username", os.getenv("CTFD_USERNAME", ""))
39
+ self.config.setdefault("password", os.getenv("CTFD_PASSWORD", ""))
40
+
41
+ # デフォルト値の設定
42
+ defaults = {
43
+ "output_dir": "./challenges",
44
+ "concurrency": 4,
45
+ "retry": {
46
+ "max_attempts": 3,
47
+ "backoff_base": 2,
48
+ },
49
+ "file": {
50
+ "overwrite": False,
51
+ "sanitize_names": True,
52
+ },
53
+ "logging": {
54
+ "level": "INFO",
55
+ },
56
+ }
57
+
58
+ for key, value in defaults.items():
59
+ if key not in self.config:
60
+ self.config[key] = value
61
+ elif isinstance(value, dict):
62
+ self.config[key] = {**value, **self.config.get(key, {})}
63
+
64
+ def get(self, key: str, default: Any = None) -> Any:
65
+ """
66
+ 設定値を取得.
67
+
68
+ Args:
69
+ key: 設定キー(ドット区切りでネスト可能)
70
+ default: デフォルト値
71
+
72
+ Returns:
73
+ 設定値
74
+ """
75
+ keys = key.split(".")
76
+ value = self.config
77
+ for k in keys:
78
+ if isinstance(value, dict):
79
+ value = value.get(k)
80
+ if value is None:
81
+ return default
82
+ else:
83
+ return default
84
+ return value if value is not None else default
85
+
86
+ def set(self, key: str, value: Any):
87
+ """
88
+ 設定値を設定.
89
+
90
+ Args:
91
+ key: 設定キー(ドット区切りでネスト可能)
92
+ value: 設定値
93
+ """
94
+ keys = key.split(".")
95
+ config = self.config
96
+ for k in keys[:-1]:
97
+ if k not in config:
98
+ config[k] = {}
99
+ config = config[k]
100
+ config[keys[-1]] = value
101
+
102
+ def setup_logging(self):
103
+ """ロギングを設定."""
104
+ level = getattr(logging, self.get("logging.level", "INFO").upper(), logging.INFO)
105
+ logging.basicConfig(
106
+ level=level,
107
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
108
+ datefmt="%Y-%m-%d %H:%M:%S",
109
+ )
110
+
@@ -0,0 +1,149 @@
1
+ """ファイルダウンローダー."""
2
+ import os
3
+ import time
4
+ import logging
5
+ from typing import Optional, Callable
6
+ from concurrent.futures import ThreadPoolExecutor, Future
7
+ import requests
8
+ from tqdm import tqdm
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+
13
+ class Downloader:
14
+ """ファイルダウンローダー."""
15
+
16
+ def __init__(
17
+ self,
18
+ session: requests.Session,
19
+ max_workers: int = 4,
20
+ max_attempts: int = 3,
21
+ backoff_base: float = 2.0,
22
+ ):
23
+ """
24
+ ダウンローダーを初期化.
25
+
26
+ Args:
27
+ session: requests.Session オブジェクト
28
+ max_workers: 並列ダウンロード数
29
+ max_attempts: 最大リトライ回数
30
+ backoff_base: 指数バックオフのベース値
31
+ """
32
+ self.session = session
33
+ self.max_workers = max_workers
34
+ self.max_attempts = max_attempts
35
+ self.backoff_base = backoff_base
36
+ self.executor: Optional[ThreadPoolExecutor] = None
37
+
38
+ def download_file(
39
+ self,
40
+ url: str,
41
+ dest_path: str,
42
+ overwrite: bool = False,
43
+ progress_callback: Optional[Callable[[int, int], None]] = None,
44
+ ) -> bool:
45
+ """
46
+ ファイルをダウンロード.
47
+
48
+ Args:
49
+ url: ダウンロードURL
50
+ dest_path: 保存先パス
51
+ overwrite: 既存ファイルを上書きするか
52
+ progress_callback: 進捗コールバック (downloaded, total)
53
+
54
+ Returns:
55
+ 成功時 True
56
+ """
57
+ if os.path.exists(dest_path) and not overwrite:
58
+ logger.debug(f"ファイルが既に存在します(スキップ): {dest_path}")
59
+ return True
60
+
61
+ # ディレクトリを作成
62
+ os.makedirs(os.path.dirname(dest_path), exist_ok=True)
63
+
64
+ for attempt in range(self.max_attempts):
65
+ try:
66
+ response = self.session.get(url, stream=True, timeout=30)
67
+ if response.status_code == 429:
68
+ # レート制限
69
+ retry_after = int(response.headers.get("Retry-After", 60))
70
+ logger.warning(f"レート制限に達しました。{retry_after}秒待機します")
71
+ time.sleep(retry_after)
72
+ continue
73
+
74
+ if response.status_code != 200:
75
+ logger.error(f"ダウンロードに失敗しました: {url} (ステータス: {response.status_code})")
76
+ if attempt < self.max_attempts - 1:
77
+ wait_time = self.backoff_base ** attempt
78
+ logger.info(f"{wait_time}秒後にリトライします...")
79
+ time.sleep(wait_time)
80
+ continue
81
+ return False
82
+
83
+ # Content-Length を取得
84
+ total_size = int(response.headers.get("Content-Length", 0))
85
+ chunk_size = 8192
86
+
87
+ with open(dest_path, "wb") as f:
88
+ downloaded = 0
89
+ for chunk in response.iter_content(chunk_size=chunk_size):
90
+ if chunk:
91
+ f.write(chunk)
92
+ downloaded += len(chunk)
93
+ if progress_callback:
94
+ progress_callback(downloaded, total_size)
95
+
96
+ logger.info(f"ダウンロード完了: {dest_path}")
97
+ return True
98
+
99
+ except requests.exceptions.RequestException as e:
100
+ logger.warning(f"ダウンロード中にエラーが発生しました(試行 {attempt + 1}/{self.max_attempts}): {e}")
101
+ if attempt < self.max_attempts - 1:
102
+ wait_time = self.backoff_base ** attempt
103
+ time.sleep(wait_time)
104
+ else:
105
+ logger.error(f"ダウンロードに失敗しました: {url}")
106
+ return False
107
+ except Exception as e:
108
+ logger.error(f"予期しないエラーが発生しました: {e}")
109
+ return False
110
+
111
+ return False
112
+
113
+ def download_files_parallel(
114
+ self,
115
+ file_list: list[tuple[str, str]],
116
+ overwrite: bool = False,
117
+ ) -> dict[str, bool]:
118
+ """
119
+ 複数ファイルを並列ダウンロード.
120
+
121
+ Args:
122
+ file_list: (url, dest_path) のタプルのリスト
123
+ overwrite: 既存ファイルを上書きするか
124
+
125
+ Returns:
126
+ {dest_path: success} の辞書
127
+ """
128
+ results = {}
129
+ with ThreadPoolExecutor(max_workers=self.max_workers) as executor:
130
+ futures: dict[Future, tuple[str, str]] = {}
131
+ for url, dest_path in file_list:
132
+ future = executor.submit(self.download_file, url, dest_path, overwrite)
133
+ futures[future] = (url, dest_path)
134
+
135
+ # 進捗バー
136
+ with tqdm(total=len(file_list), desc="ダウンロード中") as pbar:
137
+ for future in futures:
138
+ url, dest_path = futures[future]
139
+ try:
140
+ success = future.result()
141
+ results[dest_path] = success
142
+ pbar.update(1)
143
+ except Exception as e:
144
+ logger.error(f"ダウンロードタスクでエラーが発生しました: {e}")
145
+ results[dest_path] = False
146
+ pbar.update(1)
147
+
148
+ return results
149
+
@@ -0,0 +1,218 @@
1
+ """CLI エントリーポイント."""
2
+ import argparse
3
+ import sys
4
+ import logging
5
+
6
+ from ctfd_downloader.config import Config
7
+ from ctfd_downloader.client import CTFdClient
8
+ from ctfd_downloader.downloader import Downloader
9
+ from ctfd_downloader.storage import Storage
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ def main():
15
+ """メイン関数."""
16
+ parser = argparse.ArgumentParser(
17
+ description="CTFd challenge downloader and organizer",
18
+ formatter_class=argparse.RawDescriptionHelpFormatter,
19
+ )
20
+ parser.add_argument(
21
+ "--config",
22
+ type=str,
23
+ default="config.yaml",
24
+ help="設定ファイルのパス (default: config.yaml)",
25
+ )
26
+ parser.add_argument(
27
+ "--base-url",
28
+ type=str,
29
+ help="CTFd インスタンスのベースURL(設定ファイルより優先)",
30
+ )
31
+ parser.add_argument(
32
+ "--token",
33
+ type=str,
34
+ help="API トークン(設定ファイルより優先)",
35
+ )
36
+ parser.add_argument(
37
+ "--user",
38
+ type=str,
39
+ help="ユーザ名(設定ファイルより優先)",
40
+ )
41
+ parser.add_argument(
42
+ "--password",
43
+ type=str,
44
+ help="パスワード(設定ファイルより優先)",
45
+ )
46
+ parser.add_argument(
47
+ "--output",
48
+ type=str,
49
+ help="出力ディレクトリ(設定ファイルより優先)",
50
+ )
51
+ parser.add_argument(
52
+ "--concurrency",
53
+ type=int,
54
+ help="並列ダウンロード数(設定ファイルより優先)",
55
+ )
56
+ parser.add_argument(
57
+ "--skip-download",
58
+ action="store_true",
59
+ help="メタデータのみ取得し、ファイルダウンロードをスキップ",
60
+ )
61
+ parser.add_argument(
62
+ "--force-overwrite",
63
+ action="store_true",
64
+ help="既存ファイルを上書き",
65
+ )
66
+ parser.add_argument(
67
+ "--verbose",
68
+ action="store_true",
69
+ help="詳細ログを出力",
70
+ )
71
+
72
+ args = parser.parse_args()
73
+
74
+ # 設定を読み込み
75
+ config = Config(args.config)
76
+
77
+ # コマンドライン引数で上書き
78
+ if args.base_url:
79
+ config.set("base_url", args.base_url)
80
+ if args.token:
81
+ config.set("api_token", args.token)
82
+ if args.user:
83
+ config.set("username", args.user)
84
+ if args.password:
85
+ config.set("password", args.password)
86
+ if args.output:
87
+ config.set("output_dir", args.output)
88
+ if args.concurrency:
89
+ config.set("concurrency", args.concurrency)
90
+ if args.force_overwrite:
91
+ config.set("file.overwrite", True)
92
+ if args.verbose:
93
+ config.set("logging.level", "DEBUG")
94
+
95
+ # ロギング設定
96
+ config.setup_logging()
97
+
98
+ # 必須設定の確認
99
+ base_url = config.get("base_url")
100
+ if not base_url:
101
+ logger.error("BASE_URL が設定されていません")
102
+ sys.exit(1)
103
+
104
+ api_token = config.get("api_token")
105
+ username = config.get("username")
106
+ password = config.get("password")
107
+
108
+ if not api_token and not (username and password):
109
+ logger.error("認証情報が設定されていません(API_TOKEN または USERNAME/PASSWORD)")
110
+ sys.exit(1)
111
+
112
+ # クライアント初期化
113
+ client = CTFdClient(
114
+ base_url=base_url,
115
+ api_token=api_token,
116
+ username=username,
117
+ password=password,
118
+ )
119
+
120
+ # 認証
121
+ if not client.authenticate():
122
+ logger.error("認証に失敗しました")
123
+ sys.exit(1)
124
+
125
+ # ストレージ初期化
126
+ output_dir = config.get("output_dir", "./challenges")
127
+ sanitize_names = config.get("file.sanitize_names", True)
128
+ storage = Storage(root_dir=output_dir, sanitize_names=sanitize_names)
129
+
130
+ # ダウンローダー初期化
131
+ concurrency = config.get("concurrency", 4)
132
+ max_attempts = config.get("retry.max_attempts", 3)
133
+ backoff_base = config.get("retry.backoff_base", 2.0)
134
+ downloader = Downloader(
135
+ session=client.session,
136
+ max_workers=concurrency,
137
+ max_attempts=max_attempts,
138
+ backoff_base=backoff_base,
139
+ )
140
+
141
+ # 課題一覧を取得
142
+ logger.info("課題一覧を取得しています...")
143
+ challenges = client.list_challenges()
144
+ if not challenges:
145
+ logger.warning("課題が見つかりませんでした")
146
+ sys.exit(0)
147
+
148
+ # 各課題を処理
149
+ overwrite = config.get("file.overwrite", False)
150
+ success_count = 0
151
+ error_count = 0
152
+ file_download_count = 0
153
+ file_success_count = 0
154
+
155
+ for challenge in challenges:
156
+ challenge_id = challenge.get("id")
157
+ challenge_name = challenge.get("name", "Unknown")
158
+ category = challenge.get("category", "Uncategorized")
159
+
160
+ logger.info(f"課題を処理中: [{category}] {challenge_name} (ID: {challenge_id})")
161
+
162
+ try:
163
+ # 課題詳細を取得
164
+ detail = client.get_challenge(challenge_id)
165
+ if not detail:
166
+ logger.warning(f"課題 {challenge_id} の詳細を取得できませんでした")
167
+ error_count += 1
168
+ continue
169
+
170
+ # source_url を追加
171
+ detail["source_url"] = f"{base_url}/challenges/{challenge_id}"
172
+
173
+ # ディレクトリを作成
174
+ challenge_dir = storage.get_challenge_dir(category, challenge_name)
175
+ storage.ensure_dir(challenge_dir)
176
+
177
+ # メタデータとREADMEを保存
178
+ storage.save_metadata(challenge_dir, detail)
179
+ storage.save_readme(challenge_dir, detail)
180
+
181
+ # ファイルをダウンロード
182
+ files = detail.get("files", [])
183
+ if files and not args.skip_download:
184
+ file_list = []
185
+ for file_path in files:
186
+ file_url = client.get_file_url(file_path)
187
+ dest_path = storage.get_file_path(challenge_dir, file_url)
188
+ file_list.append((file_url, str(dest_path)))
189
+ file_download_count += 1
190
+
191
+ if file_list:
192
+ logger.info(f" {len(file_list)} 個のファイルをダウンロード中...")
193
+ results = downloader.download_files_parallel(file_list, overwrite=overwrite)
194
+ file_success_count += sum(1 for success in results.values() if success)
195
+
196
+ success_count += 1
197
+ logger.info(f" ✓ 完了: {challenge_name}")
198
+
199
+ except Exception as e:
200
+ logger.error(f"課題 {challenge_id} の処理中にエラーが発生しました: {e}", exc_info=True)
201
+ error_count += 1
202
+
203
+ # 統計を出力
204
+ logger.info("=" * 60)
205
+ logger.info("処理完了")
206
+ logger.info(f" 課題: 成功 {success_count} / 失敗 {error_count} / 合計 {len(challenges)}")
207
+ if not args.skip_download:
208
+ logger.info(f" ファイル: 成功 {file_success_count} / 合計 {file_download_count}")
209
+ logger.info(f" 出力先: {output_dir}")
210
+ logger.info("=" * 60)
211
+
212
+ if error_count > 0:
213
+ sys.exit(1)
214
+
215
+
216
+ if __name__ == "__main__":
217
+ main()
218
+
@@ -0,0 +1,167 @@
1
+ """ストレージ管理モジュール."""
2
+ import os
3
+ import json
4
+ import re
5
+ import logging
6
+ from datetime import datetime
7
+ from pathlib import Path
8
+ from typing import Dict, Any, Optional
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+
13
+ class Storage:
14
+ """ストレージ管理クラス."""
15
+
16
+ # OS で禁止されている文字
17
+ FORBIDDEN_CHARS = r'[<>:"/\\|?*\x00-\x1f]'
18
+ MAX_FILENAME_LENGTH = 255
19
+
20
+ def __init__(self, root_dir: str = "./challenges", sanitize_names: bool = True):
21
+ """
22
+ ストレージを初期化.
23
+
24
+ Args:
25
+ root_dir: ルートディレクトリ
26
+ sanitize_names: ファイル名を正規化するか
27
+ """
28
+ self.root_dir = Path(root_dir).resolve()
29
+ self.sanitize_names = sanitize_names
30
+ self.root_dir.mkdir(parents=True, exist_ok=True)
31
+
32
+ def sanitize_filename(self, name: str) -> str:
33
+ """
34
+ ファイル名を正規化(OS 安全化).
35
+
36
+ Args:
37
+ name: 元のファイル名
38
+
39
+ Returns:
40
+ 正規化されたファイル名
41
+ """
42
+ if not self.sanitize_names:
43
+ return name
44
+
45
+ # 禁止文字を除去
46
+ sanitized = re.sub(self.FORBIDDEN_CHARS, "_", name)
47
+ # 連続するアンダースコアを1つに
48
+ sanitized = re.sub(r"_+", "_", sanitized)
49
+ # 先頭・末尾のアンダースコアと空白を除去
50
+ sanitized = sanitized.strip("_ ")
51
+ # 長さ制限
52
+ if len(sanitized) > self.MAX_FILENAME_LENGTH:
53
+ sanitized = sanitized[:self.MAX_FILENAME_LENGTH]
54
+ # 空文字列の場合はデフォルト名
55
+ if not sanitized:
56
+ sanitized = "unnamed"
57
+
58
+ return sanitized
59
+
60
+ def get_challenge_dir(self, category: str, challenge_name: str) -> Path:
61
+ """
62
+ 課題ディレクトリのパスを取得.
63
+
64
+ Args:
65
+ category: カテゴリ名
66
+ challenge_name: 課題名
67
+
68
+ Returns:
69
+ ディレクトリパス
70
+ """
71
+ safe_category = self.sanitize_filename(category or "Uncategorized")
72
+ safe_name = self.sanitize_filename(challenge_name)
73
+ return self.root_dir / safe_category / safe_name
74
+
75
+ def ensure_dir(self, path: Path):
76
+ """
77
+ ディレクトリを作成.
78
+
79
+ Args:
80
+ path: ディレクトリパス
81
+ """
82
+ path.mkdir(parents=True, exist_ok=True)
83
+ # パーミッション設定(700)
84
+ os.chmod(path, 0o700)
85
+
86
+ def save_metadata(self, challenge_dir: Path, metadata: Dict[str, Any]):
87
+ """
88
+ メタデータを保存.
89
+
90
+ Args:
91
+ challenge_dir: 課題ディレクトリ
92
+ metadata: メタデータ辞書
93
+ """
94
+ metadata_path = challenge_dir / "metadata.json"
95
+ # fetched_at を追加
96
+ metadata_with_timestamp = {
97
+ **metadata,
98
+ "fetched_at": datetime.now().isoformat(),
99
+ "source_url": metadata.get("source_url", ""),
100
+ }
101
+ with open(metadata_path, "w", encoding="utf-8") as f:
102
+ json.dump(metadata_with_timestamp, f, indent=2, ensure_ascii=False)
103
+ logger.debug(f"メタデータを保存しました: {metadata_path}")
104
+
105
+ def save_readme(self, challenge_dir: Path, metadata: Dict[str, Any]):
106
+ """
107
+ README.md を生成・保存.
108
+
109
+ Args:
110
+ challenge_dir: 課題ディレクトリ
111
+ metadata: メタデータ辞書
112
+ """
113
+ readme_path = challenge_dir / "README.md"
114
+
115
+ # 説明文からHTMLタグを除去(簡易版)
116
+ description = metadata.get("description", "")
117
+ if description:
118
+ import re
119
+ description = re.sub(r"<[^>]+>", "", description)
120
+ description = description.strip()
121
+
122
+ # ファイル一覧
123
+ files = metadata.get("files", [])
124
+ file_list = "\n".join([f"- {os.path.basename(f)}" for f in files]) if files else "- (なし)"
125
+
126
+ readme_content = f"""# {metadata.get('name', 'Unknown Challenge')}
127
+
128
+ **カテゴリ:** {metadata.get('category', 'Uncategorized')}
129
+ **ポイント:** {metadata.get('value', 0)}
130
+ **取得日時:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
131
+ **ソースURL:** {metadata.get('source_url', 'N/A')}
132
+
133
+ ## 説明
134
+
135
+ {description or '(説明なし)'}
136
+
137
+ ## ファイル
138
+
139
+ {file_list}
140
+
141
+ ## 注意
142
+
143
+ このファイルは CTFd から自動取得されたものです。
144
+ ダウンロードした実行ファイルは直接実行せず、適切な環境で解析してください。
145
+ """
146
+
147
+ with open(readme_path, "w", encoding="utf-8") as f:
148
+ f.write(readme_content)
149
+ logger.debug(f"README.md を保存しました: {readme_path}")
150
+
151
+ def get_file_path(self, challenge_dir: Path, file_url: str) -> Path:
152
+ """
153
+ ファイルの保存パスを取得.
154
+
155
+ Args:
156
+ challenge_dir: 課題ディレクトリ
157
+ file_url: ファイルURL
158
+
159
+ Returns:
160
+ ファイルパス
161
+ """
162
+ files_dir = challenge_dir / "files"
163
+ files_dir.mkdir(exist_ok=True)
164
+ filename = os.path.basename(file_url.split("?")[0]) # クエリパラメータを除去
165
+ safe_filename = self.sanitize_filename(filename)
166
+ return files_dir / safe_filename
167
+
tests/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """テストファイル."""
2
+ __all__ = []
3
+
tests/test_client.py ADDED
@@ -0,0 +1,65 @@
1
+ """CTFd クライアントのテスト."""
2
+ import pytest
3
+ from unittest.mock import Mock, patch, MagicMock
4
+ from ctfd_downloader.client import CTFdClient
5
+
6
+
7
+ class TestCTFdClient:
8
+ """CTFdClient のテスト."""
9
+
10
+ def test_get_file_url_absolute(self):
11
+ """絶対URLの処理テスト."""
12
+ client = CTFdClient(base_url="https://ctf.example.com")
13
+ url = client.get_file_url("https://example.com/file.zip")
14
+ assert url == "https://example.com/file.zip"
15
+
16
+ def test_get_file_url_relative_root(self):
17
+ """ルート相対パスの処理テスト."""
18
+ client = CTFdClient(base_url="https://ctf.example.com")
19
+ url = client.get_file_url("/files/abc123/file.zip")
20
+ assert url == "https://ctf.example.com/files/abc123/file.zip"
21
+
22
+ def test_get_file_url_relative(self):
23
+ """相対パスの処理テスト."""
24
+ client = CTFdClient(base_url="https://ctf.example.com")
25
+ url = client.get_file_url("files/abc123/file.zip")
26
+ assert url == "https://ctf.example.com/files/abc123/file.zip"
27
+
28
+ @patch("ctfd_downloader.client.requests.Session")
29
+ def test_authenticate_with_token_success(self, mock_session_class):
30
+ """Token認証の成功テスト."""
31
+ mock_session = Mock()
32
+ mock_session_class.return_value = mock_session
33
+ mock_response = Mock()
34
+ mock_response.status_code = 200
35
+ mock_session.get.return_value = mock_response
36
+
37
+ client = CTFdClient(
38
+ base_url="https://ctf.example.com",
39
+ api_token="test_token",
40
+ )
41
+ result = client.authenticate()
42
+
43
+ assert result is True
44
+ assert client.authenticated is True
45
+ mock_session.headers.update.assert_called_once()
46
+ mock_session.get.assert_called_once_with("https://ctf.example.com/api/v1/users/me")
47
+
48
+ @patch("ctfd_downloader.client.requests.Session")
49
+ def test_authenticate_with_token_failure(self, mock_session_class):
50
+ """Token認証の失敗テスト."""
51
+ mock_session = Mock()
52
+ mock_session_class.return_value = mock_session
53
+ mock_response = Mock()
54
+ mock_response.status_code = 401
55
+ mock_session.get.return_value = mock_response
56
+
57
+ client = CTFdClient(
58
+ base_url="https://ctf.example.com",
59
+ api_token="invalid_token",
60
+ )
61
+ result = client.authenticate()
62
+
63
+ assert result is False
64
+ assert client.authenticated is False
65
+
@@ -0,0 +1,108 @@
1
+ """ダウンローダーのテスト."""
2
+ import pytest
3
+ import tempfile
4
+ import os
5
+ from unittest.mock import Mock, patch, MagicMock
6
+ from ctfd_downloader.downloader import Downloader
7
+ import requests
8
+
9
+
10
+ class TestDownloader:
11
+ """Downloader のテスト."""
12
+
13
+ def setup_method(self):
14
+ """テスト前のセットアップ."""
15
+ self.temp_dir = tempfile.mkdtemp()
16
+ self.session = Mock()
17
+ self.downloader = Downloader(
18
+ session=self.session,
19
+ max_workers=2,
20
+ max_attempts=3,
21
+ backoff_base=2.0,
22
+ )
23
+
24
+ def teardown_method(self):
25
+ """テスト後のクリーンアップ."""
26
+ import shutil
27
+ shutil.rmtree(self.temp_dir)
28
+
29
+ def test_download_file_success(self):
30
+ """ダウンロード成功テスト."""
31
+ dest_path = os.path.join(self.temp_dir, "test_file.txt")
32
+ os.makedirs(os.path.dirname(dest_path), exist_ok=True)
33
+
34
+ mock_response = Mock()
35
+ mock_response.status_code = 200
36
+ mock_response.headers = {"Content-Length": "10"}
37
+ mock_response.iter_content = lambda chunk_size: [b"test data"]
38
+
39
+ self.session.get.return_value = mock_response
40
+
41
+ result = self.downloader.download_file(
42
+ "https://example.com/file.txt",
43
+ dest_path,
44
+ overwrite=False,
45
+ )
46
+
47
+ assert result is True
48
+ assert os.path.exists(dest_path)
49
+
50
+ def test_download_file_skip_existing(self):
51
+ """既存ファイルのスキップテスト."""
52
+ dest_path = os.path.join(self.temp_dir, "existing_file.txt")
53
+ os.makedirs(os.path.dirname(dest_path), exist_ok=True)
54
+ with open(dest_path, "w") as f:
55
+ f.write("existing")
56
+
57
+ result = self.downloader.download_file(
58
+ "https://example.com/file.txt",
59
+ dest_path,
60
+ overwrite=False,
61
+ )
62
+
63
+ assert result is True
64
+ # セッションのgetが呼ばれていないことを確認
65
+ self.session.get.assert_not_called()
66
+
67
+ def test_download_file_404_error(self):
68
+ """404エラーのテスト."""
69
+ mock_response = Mock()
70
+ mock_response.status_code = 404
71
+ self.session.get.return_value = mock_response
72
+
73
+ dest_path = os.path.join(self.temp_dir, "not_found.txt")
74
+ os.makedirs(os.path.dirname(dest_path), exist_ok=True)
75
+
76
+ result = self.downloader.download_file(
77
+ "https://example.com/notfound.txt",
78
+ dest_path,
79
+ overwrite=False,
80
+ )
81
+
82
+ assert result is False
83
+
84
+ def test_download_file_rate_limit(self):
85
+ """レート制限のテスト."""
86
+ mock_response_429 = Mock()
87
+ mock_response_429.status_code = 429
88
+ mock_response_429.headers = {"Retry-After": "1"}
89
+
90
+ mock_response_200 = Mock()
91
+ mock_response_200.status_code = 200
92
+ mock_response_200.headers = {"Content-Length": "10"}
93
+ mock_response_200.iter_content = lambda chunk_size: [b"test data"]
94
+
95
+ self.session.get.side_effect = [mock_response_429, mock_response_200]
96
+
97
+ dest_path = os.path.join(self.temp_dir, "rate_limited.txt")
98
+ os.makedirs(os.path.dirname(dest_path), exist_ok=True)
99
+
100
+ with patch("time.sleep"): # スリープをモック
101
+ result = self.downloader.download_file(
102
+ "https://example.com/file.txt",
103
+ dest_path,
104
+ overwrite=False,
105
+ )
106
+
107
+ assert result is True
108
+
tests/test_storage.py ADDED
@@ -0,0 +1,102 @@
1
+ """ストレージのテスト."""
2
+ import pytest
3
+ import tempfile
4
+ import shutil
5
+ from pathlib import Path
6
+ from ctfd_downloader.storage import Storage
7
+
8
+
9
+ class TestStorage:
10
+ """Storage のテスト."""
11
+
12
+ def setup_method(self):
13
+ """テスト前のセットアップ."""
14
+ self.temp_dir = tempfile.mkdtemp()
15
+ self.storage = Storage(root_dir=self.temp_dir, sanitize_names=True)
16
+
17
+ def teardown_method(self):
18
+ """テスト後のクリーンアップ."""
19
+ shutil.rmtree(self.temp_dir)
20
+
21
+ def test_sanitize_filename_basic(self):
22
+ """基本的なファイル名正規化テスト."""
23
+ assert self.storage.sanitize_filename("test.txt") == "test.txt"
24
+ assert self.storage.sanitize_filename("test file.zip") == "test file.zip"
25
+
26
+ def test_sanitize_filename_forbidden_chars(self):
27
+ """禁止文字の除去テスト."""
28
+ assert self.storage.sanitize_filename("test<>file.zip") == "test__file.zip"
29
+ assert self.storage.sanitize_filename("test:file.zip") == "test_file.zip"
30
+ assert self.storage.sanitize_filename("test/file.zip") == "test_file.zip"
31
+
32
+ def test_sanitize_filename_multiple_underscores(self):
33
+ """連続アンダースコアの正規化テスト."""
34
+ assert self.storage.sanitize_filename("test___file.zip") == "test_file.zip"
35
+
36
+ def test_sanitize_filename_long_name(self):
37
+ """長いファイル名の切り詰めテスト."""
38
+ long_name = "a" * 300
39
+ result = self.storage.sanitize_filename(long_name)
40
+ assert len(result) == 255
41
+
42
+ def test_sanitize_filename_empty(self):
43
+ """空文字列の処理テスト."""
44
+ assert self.storage.sanitize_filename("") == "unnamed"
45
+ assert self.storage.sanitize_filename(" ") == "unnamed"
46
+
47
+ def test_get_challenge_dir(self):
48
+ """課題ディレクトリパスの取得テスト."""
49
+ path = self.storage.get_challenge_dir("Web", "SQLi 101")
50
+ assert isinstance(path, Path)
51
+ assert "Web" in str(path)
52
+ assert "SQLi" in str(path)
53
+
54
+ def test_get_challenge_dir_uncategorized(self):
55
+ """カテゴリなしの場合のテスト."""
56
+ path = self.storage.get_challenge_dir("", "Test Challenge")
57
+ assert "Uncategorized" in str(path)
58
+
59
+ def test_save_metadata(self):
60
+ """メタデータ保存テスト."""
61
+ challenge_dir = Path(self.temp_dir) / "test_challenge"
62
+ challenge_dir.mkdir(parents=True)
63
+
64
+ metadata = {
65
+ "id": 1,
66
+ "name": "Test Challenge",
67
+ "category": "Web",
68
+ "value": 100,
69
+ }
70
+ self.storage.save_metadata(challenge_dir, metadata)
71
+
72
+ metadata_path = challenge_dir / "metadata.json"
73
+ assert metadata_path.exists()
74
+
75
+ import json
76
+ with open(metadata_path, "r", encoding="utf-8") as f:
77
+ saved_data = json.load(f)
78
+ assert saved_data["id"] == 1
79
+ assert "fetched_at" in saved_data
80
+
81
+ def test_save_readme(self):
82
+ """README保存テスト."""
83
+ challenge_dir = Path(self.temp_dir) / "test_challenge"
84
+ challenge_dir.mkdir(parents=True)
85
+
86
+ metadata = {
87
+ "name": "Test Challenge",
88
+ "category": "Web",
89
+ "value": 100,
90
+ "description": "<p>Test description</p>",
91
+ "files": ["/files/test.zip"],
92
+ }
93
+ self.storage.save_readme(challenge_dir, metadata)
94
+
95
+ readme_path = challenge_dir / "README.md"
96
+ assert readme_path.exists()
97
+
98
+ content = readme_path.read_text(encoding="utf-8")
99
+ assert "Test Challenge" in content
100
+ assert "Web" in content
101
+ assert "100" in content
102
+