diff --git a/README.md b/README.md index 5348b93..44f3027 100644 --- a/README.md +++ b/README.md @@ -119,9 +119,9 @@ Open `http://127.0.0.1:8080`, enter the number, and press Enter. ASCII, Persian, and Arabic digits are accepted and normalized to ASCII. The next challenge is loaded without a page refresh so the numeric keyboard stays open on phones. -By default the collector connects to `https://panel.mvphub.ir` with the panel's -demo credentials (`username` / `password`) and appends to `dataset/labels.csv`. -Set real credentials through the process environment: +By default the collector connects to the TCI customer panel at +`https://internet.tci.ir/panel/` and appends to `dataset/labels.csv`. Set your +TCI credentials through the process environment: ```bash PANEL_LOGIN_USERNAME='your-user' \ @@ -131,7 +131,7 @@ php -S 127.0.0.1:8080 -t web The supported settings are: -- `PANEL_BASE_URL` — panel origin; defaults to `https://panel.mvphub.ir`. +- `PANEL_BASE_URL` — panel origin; defaults to `https://internet.tci.ir`. - `PANEL_LOGIN_USERNAME` — login username; defaults to `username`. - `PANEL_LOGIN_PASSWORD` — plaintext login password; defaults to `password`. - `PANEL_REQUEST_TIMEOUT` — upstream timeout in seconds; defaults to `10`. @@ -164,7 +164,7 @@ server { include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root/index.php; fastcgi_param OCR_DATASET_DIR /srv/tci-ocr/dataset; - fastcgi_param PANEL_BASE_URL https://panel.mvphub.ir; + fastcgi_param PANEL_BASE_URL https://internet.tci.ir; fastcgi_param PANEL_LOGIN_USERNAME your-user; fastcgi_param PANEL_LOGIN_PASSWORD your-password; fastcgi_pass unix:/run/php/php8.3-fpm.sock; diff --git a/tests/test_tools.py b/tests/test_tools.py index 44df9eb..6e30609 100644 --- a/tests/test_tools.py +++ b/tests/test_tools.py @@ -253,34 +253,62 @@ class ToolTests(unittest.TestCase): cookie = self.headers.get("Cookie", "") for part in cookie.split(";"): name, separator, value = part.strip().partition("=") - if separator and name == "CUSTOMER_PORTAL_SESSION": + if separator and name == "PHPSESSID": return value return "" + def render_login(self, session_id: str) -> bytes: + type(self).sequence += 1 + nonce = type(self).sequence + session = type(self).sessions[session_id] + message = session.pop("message", "") + notification = ( + "" + if message + else "" + ) + host = self.headers["Host"] + return ( + f"{notification}" + f'
" + ).encode() + def do_GET(self): path = urllib.parse.urlsplit(self.path).path - if path == "/panel": - type(self).sequence += 1 - session_id = f"session-{type(self).sequence}" - csrf = f"{type(self).sequence:064x}" - type(self).sessions[session_id] = {"csrf": csrf} - body = ( - '' - ).encode() + if path in {"/panel", "/panel/"}: + session_id = self.session_id() + session = type(self).sessions.get(session_id) + headers = None + if session is None: + type(self).sequence += 1 + session_id = f"session-{type(self).sequence}" + session = {} + type(self).sessions[session_id] = session + headers = { + "Set-Cookie": ( + f"PHPSESSID={session_id}; Path=/; HttpOnly" + ) + } + if session.get("authenticated"): + body = 'خروج'.encode() + else: + body = self.render_login(session_id) self.send_body( 200, body, - headers={ - "Set-Cookie": ( - "CUSTOMER_PORTAL_SESSION=" - f"{session_id}; Path=/; HttpOnly; SameSite=Lax" - ) - }, + headers=headers, ) return - if path == "/captcha": + if path == "/panel/captcha/": session = type(self).sessions.get(self.session_id()) if session is None: self.send_body(400, b"missing session") @@ -296,13 +324,19 @@ class ToolTests(unittest.TestCase): session["code"] = code session["image"] = image type(self).latest_code = code - self.send_body(200, image, content_type="image/png") + self.send_body( + 200, + image, + content_type="image/png", + headers={"Set-Cookie": "captcha_seen=1; Path=/"}, + ) return self.send_body(404, b"not found") def do_POST(self): - if urllib.parse.urlsplit(self.path).path != "/login": + path = urllib.parse.urlsplit(self.path).path + if not path.startswith("/panel/login/"): self.send_body(404, b"not found") return @@ -312,13 +346,20 @@ class ToolTests(unittest.TestCase): keep_blank_values=True, ) session = type(self).sessions.get(self.session_id()) - if session is None or values.get("csrf_token", [""])[0] != session["csrf"]: - self.send_body(400, "درخواست ورود معتبر نیست".encode()) + if ( + session is None + or "captcha_seen=1" not in self.headers.get("Cookie", "") + or values.get("redirect") != [""] + or values.get("LoginFromWeb") != ["1"] + ): + self.send_body(400, b"invalid login request") return if values.get("captcha", [""])[0] != session.get("code"): + session["message"] = "کد امنیتی وارد شده نادرست است." self.send_body( - 401, - "کد امنیتی اشتباه است یا اعتبار آن به پایان رسیده است".encode(), + 302, + b"", + headers={"Location": "/panel/"}, ) return if ( @@ -326,12 +367,15 @@ class ToolTests(unittest.TestCase): or values.get("username", [""])[0] != "username" or values.get("password", [""])[0] != "password" ): + session["message"] = "نام کاربری یا گذرواژه نادرست است." self.send_body( - 401, - "نام کاربری یا رمز عبور صحیح نیست".encode(), + 302, + b"", + headers={"Location": "/panel/"}, ) return - self.send_body(303, b"", headers={"Location": "/panel"}) + session["authenticated"] = True + self.send_body(302, b"", headers={"Location": "/panel/"}) panel_server = http.server.ThreadingHTTPServer( ("127.0.0.1", 0), @@ -441,14 +485,19 @@ class ToolTests(unittest.TestCase): ) self.assertEqual(image_headers["Content-Type"], "image/png") - _, rejected_body, _ = post( - { - "action": "submit", - "csrf_token": csrf_token, - "challenge_id": first_challenge, - "label": "99999", - } - ) + try: + _, rejected_body, _ = post( + { + "action": "submit", + "csrf_token": csrf_token, + "challenge_id": first_challenge, + "label": "99999", + } + ) + except urllib.error.HTTPError as problem: + details = problem.read().decode(errors="replace") + problem.close() + self.fail(f"captcha rejection returned {problem.code}: {details}") rejected = json.loads(rejected_body) self.assertEqual(rejected["outcome"], "rejected") self.assertNotEqual(rejected["challenge"]["id"], first_challenge) diff --git a/web/collector.php b/web/collector.php index 9784a4d..b02e553 100644 --- a/web/collector.php +++ b/web/collector.php @@ -57,7 +57,7 @@ function collectorConfig(): array 'panel_base_url' => rtrim( $_SERVER['PANEL_BASE_URL'] ?? getenv('PANEL_BASE_URL') - ?: 'https://panel.mvphub.ir', + ?: 'https://internet.tci.ir', '/', ), 'panel_username' => (string) ( @@ -168,9 +168,46 @@ function panelUrl(array $config, string $path): string || isset($parts['query']) || isset($parts['fragment']) ) { - throw new CollectorError('PANEL_BASE_URL must be a valid HTTP or HTTPS origin.', 500); + throw new CollectorError('PANEL_BASE_URL must be a valid HTTP or HTTPS URL.', 500); } - return $base . '/' . ltrim($path, '/'); + + $scheme = strtolower((string) $parts['scheme']); + $host = strtolower((string) $parts['host']); + $port = isset($parts['port']) ? ':' . (int) $parts['port'] : ''; + $origin = $scheme . '://' . $parts['host'] . $port; + + if (str_starts_with($path, '//')) { + $url = $scheme . ':' . $path; + } elseif (preg_match('#^https?://#i', $path) === 1) { + $url = $path; + } elseif (str_starts_with($path, '/')) { + $url = $origin . $path; + } else { + $basePath = (string) ($parts['path'] ?? ''); + $directory = $basePath === '' || $basePath === '/' + ? '/panel/' + : rtrim($basePath, '/') . '/'; + $url = $origin . $directory . $path; + } + + $target = parse_url($url); + if ($target === false) { + throw new CollectorError('The panel returned an unsafe URL.', 502); + } + $targetPort = isset($target['port']) ? ':' . (int) $target['port'] : ''; + if ( + !isset($target['scheme'], $target['host']) + || strtolower((string) $target['scheme']) !== $scheme + || strtolower((string) $target['host']) !== $host + || $targetPort !== $port + || isset($target['user']) + || isset($target['pass']) + || isset($target['fragment']) + ) { + throw new CollectorError('The panel returned an unsafe URL.', 502); + } + + return $url; } /** @@ -263,9 +300,33 @@ function panelRequest( return new PanelResponse($status, $parsedHeaders, $responseBody); } -function extractPanelCookies(PanelResponse $response): string +/** @return array