ctfd-dl 1.0.2__tar.gz

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.
ctfd_dl-1.0.2/PKG-INFO ADDED
@@ -0,0 +1,121 @@
1
+ Metadata-Version: 2.4
2
+ Name: ctfd-dl
3
+ Version: 1.0.2
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,87 @@
1
+ # CTFd Downloader
2
+
3
+ CTFd インスタンスから課題情報と添付ファイルを自動取得・整理する Python ツールです。
4
+
5
+ ## 機能
6
+
7
+ - Token 認証またはユーザ名/パスワード認証による CTFd API へのアクセス
8
+ - 課題一覧・詳細情報の取得
9
+ - 添付ファイルの自動ダウンロード
10
+ - `challenges/<Category>/<Challenge Name>/` の構造で整理保存
11
+ - メタデータ(JSON)と README(Markdown)の自動生成
12
+ - 並列ダウンロードとリトライ機能
13
+ - ロギングとエラーハンドリング
14
+
15
+ ## インストール
16
+
17
+ ```bash
18
+ pip install ctfd-dl
19
+ ```
20
+
21
+ ## 設定
22
+
23
+ 1. `config.example.yaml` を `config.yaml` にコピー
24
+ 2. `config.yaml` を編集して CTFd インスタンスの情報を設定
25
+
26
+ ```yaml
27
+ base_url: "https://ctf.example.com"
28
+ api_token: "your_api_token_here" # 推奨
29
+ # または
30
+ username: "your_username"
31
+ password: "your_password"
32
+ output_dir: "./challenges"
33
+ concurrency: 4
34
+ ```
35
+
36
+ または環境変数を使用:
37
+
38
+ ```bash
39
+ export CTFD_BASE_URL="https://ctf.example.com"
40
+ export CTFD_API_TOKEN="your_api_token_here"
41
+ ```
42
+
43
+ ## 使用方法
44
+
45
+ パッケージをインストールすると、`ctfd-dl` コマンドが利用可能になります。
46
+
47
+ ```bash
48
+ # 基本的な使用
49
+ ctfd-dl --config config.yaml
50
+
51
+ # コマンドライン引数で設定を上書き
52
+ ctfd-dl --base-url https://ctf.example.com --token YOUR_TOKEN --output ./my_challenges
53
+
54
+ # メタデータのみ取得(ファイルダウンロードをスキップ)
55
+ ctfd-dl --skip-download
56
+
57
+ # 詳細ログを出力
58
+ ctfd-dl --verbose
59
+ ```
60
+
61
+ ## 出力構造
62
+
63
+ ```
64
+ challenges/
65
+ └─ <Category>/
66
+ └─ <Challenge Name>/
67
+ ├─ files/
68
+ │ ├─ attached1.zip
69
+ │ └─ script.py
70
+ ├─ metadata.json
71
+ └─ README.md
72
+ ```
73
+
74
+ ## 注意事項
75
+
76
+ - **法的注意**: 他者運営の CTFd インスタンスにアクセスする場合は、必ず運営者の許可を得てください。
77
+ - **セキュリティ**: ダウンロードした実行ファイルは直接実行せず、適切な環境で解析してください。
78
+ - **サーバ負荷**: 並列ダウンロード数(`concurrency`)を適切に設定し、サーバに負荷をかけないようにしてください。
79
+
80
+ ## ライセンス
81
+
82
+ MIT License
83
+
84
+ ## 作者
85
+
86
+ tikisan (GitHub: @tikipiya)
87
+
@@ -0,0 +1,121 @@
1
+ Metadata-Version: 2.4
2
+ Name: ctfd-dl
3
+ Version: 1.0.2
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,18 @@
1
+ README.md
2
+ setup.py
3
+ ctfd_dl.egg-info/PKG-INFO
4
+ ctfd_dl.egg-info/SOURCES.txt
5
+ ctfd_dl.egg-info/dependency_links.txt
6
+ ctfd_dl.egg-info/entry_points.txt
7
+ ctfd_dl.egg-info/requires.txt
8
+ ctfd_dl.egg-info/top_level.txt
9
+ ctfd_downloader/__init__.py
10
+ ctfd_downloader/client.py
11
+ ctfd_downloader/config.py
12
+ ctfd_downloader/downloader.py
13
+ ctfd_downloader/main.py
14
+ ctfd_downloader/storage.py
15
+ tests/__init__.py
16
+ tests/test_client.py
17
+ tests/test_downloader.py
18
+ tests/test_storage.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ ctfd-dl = ctfd_downloader.main:main
@@ -0,0 +1,7 @@
1
+ requests>=2.31.0
2
+ tqdm>=4.66.0
3
+ python-dotenv>=1.0.0
4
+ PyYAML>=6.0
5
+ urllib3>=2.0.0
6
+ pytest>=7.4.0
7
+ pytest-mock>=3.12.0
@@ -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
+