feat: switch captcha collector to TCI internet panel
This commit is contained in:
3 files changed
+229
-68
No files matched your search
@@ -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;
|
||||
|
||||
+83
-34
@@ -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 = (
|
||||
"<script>UIkit.notification("
|
||||
f"{json.dumps(message, ensure_ascii=False)}"
|
||||
");</script>"
|
||||
if message
|
||||
else ""
|
||||
)
|
||||
host = self.headers["Host"]
|
||||
return (
|
||||
f"{notification}"
|
||||
f'<form action="http://{host}/panel/login/{nonce}" method="POST">'
|
||||
'<input type="hidden" name="redirect" value="">'
|
||||
'<input name="username"><input name="password">'
|
||||
'<img id="loginCaptchaImage" '
|
||||
f'src="http://{host}/panel/captcha/?r={nonce}">'
|
||||
'<input name="captcha"><button name="LoginFromWeb"></button>'
|
||||
"</form>"
|
||||
).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 = (
|
||||
'<form><input type="hidden" name="csrf_token" '
|
||||
f'value="{csrf}"></form>'
|
||||
).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 = '<a href="/panel/logout">خروج</a>'.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)
|
||||
|
||||
+141
-29
@@ -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<string, string> */
|
||||
function panelCookieMap(string $cookieHeader): array
|
||||
{
|
||||
$cookies = [];
|
||||
foreach (explode(';', $cookieHeader) as $pair) {
|
||||
$separator = strpos($pair, '=');
|
||||
if ($separator === false) {
|
||||
continue;
|
||||
}
|
||||
$name = trim(substr($pair, 0, $separator));
|
||||
$value = trim(substr($pair, $separator + 1));
|
||||
if (
|
||||
preg_match('/^[A-Za-z0-9_.-]+$/D', $name) === 1
|
||||
&& preg_match('/[\x00-\x20\x7f;]/', $value) !== 1
|
||||
) {
|
||||
$cookies[$name] = $value;
|
||||
}
|
||||
}
|
||||
return $cookies;
|
||||
}
|
||||
|
||||
function mergePanelCookies(
|
||||
string $cookieHeader,
|
||||
PanelResponse $response,
|
||||
bool $required = false,
|
||||
): string {
|
||||
$cookies = panelCookieMap($cookieHeader);
|
||||
foreach ($response->headers('set-cookie') as $header) {
|
||||
$pair = trim(explode(';', $header, 2)[0]);
|
||||
$separator = strpos($pair, '=');
|
||||
@@ -282,7 +343,7 @@ function extractPanelCookies(PanelResponse $response): string
|
||||
}
|
||||
$cookies[$name] = $value;
|
||||
}
|
||||
if ($cookies === []) {
|
||||
if ($required && $cookies === []) {
|
||||
throw new CollectorError('The panel did not create a login session.', 502);
|
||||
}
|
||||
|
||||
@@ -293,22 +354,44 @@ function extractPanelCookies(PanelResponse $response): string
|
||||
return implode('; ', $parts);
|
||||
}
|
||||
|
||||
function extractPanelCsrf(string $html): string
|
||||
function extractPanelFormAction(string $html): string
|
||||
{
|
||||
$patterns = [
|
||||
'/<input\b[^>]*\bname=(["\'])csrf_token\1[^>]*\bvalue=(["\'])(.*?)\2[^>]*>/is',
|
||||
'/<input\b[^>]*\bvalue=(["\'])(.*?)\1[^>]*\bname=(["\'])csrf_token\3[^>]*>/is',
|
||||
'/<form\b[^>]*\baction\s*=\s*(["\'])(.*?)\1/is',
|
||||
'/<form\b[^>]*\baction\s*=\s*([^\s>"\']+)/is',
|
||||
];
|
||||
foreach ($patterns as $index => $pattern) {
|
||||
foreach ($patterns as $pattern) {
|
||||
if (preg_match($pattern, $html, $matches) === 1) {
|
||||
$value = $index === 0 ? $matches[3] : $matches[2];
|
||||
$token = html_entity_decode($value, ENT_QUOTES | ENT_HTML5, 'UTF-8');
|
||||
if (preg_match('/^[a-f0-9]{64}$/D', $token) === 1) {
|
||||
return $token;
|
||||
$value = html_entity_decode(
|
||||
$matches[count($matches) - 1],
|
||||
ENT_QUOTES | ENT_HTML5,
|
||||
'UTF-8',
|
||||
);
|
||||
if ($value !== '') {
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new CollectorError('Could not find the panel login token.', 502);
|
||||
throw new CollectorError('Could not find the panel login form action.', 502);
|
||||
}
|
||||
|
||||
function extractPanelCaptchaUrl(string $html): string
|
||||
{
|
||||
if (
|
||||
preg_match(
|
||||
'/<img\b(?=[^>]*\bid\s*=\s*(["\'])loginCaptchaImage\1)[^>]*\bsrc\s*=\s*(["\'])(.*?)\2/is',
|
||||
$html,
|
||||
$matches,
|
||||
) !== 1
|
||||
) {
|
||||
throw new CollectorError('Could not find the panel captcha image.', 502);
|
||||
}
|
||||
|
||||
$url = html_entity_decode($matches[3], ENT_QUOTES | ENT_HTML5, 'UTF-8');
|
||||
if ($url === '') {
|
||||
throw new CollectorError('The panel returned an empty captcha URL.', 502);
|
||||
}
|
||||
return $url;
|
||||
}
|
||||
|
||||
function imageType(string $bytes, ?string $contentType): array
|
||||
@@ -335,28 +418,30 @@ function imageType(string $bytes, ?string $contentType): array
|
||||
|
||||
function fetchPanelChallenge(array $config): array
|
||||
{
|
||||
$login = panelRequest($config, 'GET', '/panel');
|
||||
$login = panelRequest($config, 'GET', '/panel/');
|
||||
if ($login->status !== 200) {
|
||||
throw new CollectorError('The panel login page is unavailable.', 502);
|
||||
}
|
||||
$cookie = extractPanelCookies($login);
|
||||
$upstreamCsrf = extractPanelCsrf($login->body);
|
||||
$cookie = mergePanelCookies('', $login, true);
|
||||
$loginUrl = panelUrl($config, extractPanelFormAction($login->body));
|
||||
$captchaUrl = panelUrl($config, extractPanelCaptchaUrl($login->body));
|
||||
|
||||
$captcha = panelRequest(
|
||||
$config,
|
||||
'GET',
|
||||
'/captcha?nonce=' . rawurlencode(bin2hex(random_bytes(8))),
|
||||
$captchaUrl,
|
||||
['Cookie: ' . $cookie],
|
||||
);
|
||||
if ($captcha->status !== 200 || $captcha->body === '') {
|
||||
throw new CollectorError('The panel captcha is unavailable.', 502);
|
||||
}
|
||||
$cookie = mergePanelCookies($cookie, $captcha);
|
||||
$type = imageType($captcha->body, $captcha->header('content-type'));
|
||||
|
||||
return [
|
||||
'id' => bin2hex(random_bytes(16)),
|
||||
'cookie' => $cookie,
|
||||
'upstream_csrf' => $upstreamCsrf,
|
||||
'login_url' => $loginUrl,
|
||||
'image' => $captcha->body,
|
||||
'mime' => $type['mime'],
|
||||
'extension' => $type['extension'],
|
||||
@@ -370,7 +455,7 @@ function challengeIsUsable(mixed $challenge): bool
|
||||
&& isset(
|
||||
$challenge['id'],
|
||||
$challenge['cookie'],
|
||||
$challenge['upstream_csrf'],
|
||||
$challenge['login_url'],
|
||||
$challenge['image'],
|
||||
$challenge['mime'],
|
||||
$challenge['extension'],
|
||||
@@ -378,7 +463,7 @@ function challengeIsUsable(mixed $challenge): bool
|
||||
)
|
||||
&& is_string($challenge['id'])
|
||||
&& is_string($challenge['cookie'])
|
||||
&& is_string($challenge['upstream_csrf'])
|
||||
&& is_string($challenge['login_url'])
|
||||
&& is_string($challenge['image'])
|
||||
&& is_string($challenge['mime'])
|
||||
&& is_string($challenge['extension'])
|
||||
@@ -449,13 +534,14 @@ function validatePendingChallenge(array $config, string $challengeId, string $an
|
||||
'username' => $config['panel_username'],
|
||||
'password' => $config['panel_password'],
|
||||
'captcha' => $answer,
|
||||
'csrf_token' => $challenge['upstream_csrf'],
|
||||
'redirect' => '',
|
||||
'LoginFromWeb' => '1',
|
||||
], '', '&', PHP_QUERY_RFC3986);
|
||||
|
||||
$response = panelRequest(
|
||||
$config,
|
||||
'POST',
|
||||
'/login',
|
||||
$challenge['login_url'],
|
||||
[
|
||||
'Content-Type: application/x-www-form-urlencoded',
|
||||
'Content-Length: ' . strlen($body),
|
||||
@@ -465,21 +551,47 @@ function validatePendingChallenge(array $config, string $challengeId, string $an
|
||||
);
|
||||
|
||||
$location = $response->header('location');
|
||||
$locationPath = $location === null ? null : parse_url($location, PHP_URL_PATH);
|
||||
if ($response->status === 303 && $locationPath === '/panel') {
|
||||
if (
|
||||
!in_array($response->status, [301, 302, 303, 307, 308], true)
|
||||
|| $location === null
|
||||
) {
|
||||
throw new CollectorError(
|
||||
'The panel returned an unexpected login response; nothing was saved.',
|
||||
502,
|
||||
);
|
||||
}
|
||||
|
||||
$cookie = mergePanelCookies($challenge['cookie'], $response);
|
||||
$result = panelRequest(
|
||||
$config,
|
||||
'GET',
|
||||
panelUrl($config, $location),
|
||||
['Cookie: ' . $cookie],
|
||||
);
|
||||
if ($result->status !== 200) {
|
||||
throw new CollectorError(
|
||||
'The panel login result page is unavailable; nothing was saved.',
|
||||
502,
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
stripos($result->body, 'logout') !== false
|
||||
|| str_contains($result->body, 'خروج')
|
||||
) {
|
||||
return storeValidatedSample($config, $challenge, $answer);
|
||||
}
|
||||
|
||||
if (
|
||||
$response->status === 401
|
||||
&& str_contains($response->body, 'کد امنیتی اشتباه است یا اعتبار آن به پایان رسیده است')
|
||||
str_contains($result->body, 'کد امنیتی وارد شده نادرست است')
|
||||
|| str_contains($result->body, 'کد امنیتی منقضی شده است')
|
||||
) {
|
||||
return ['stored' => false, 'rejected' => true];
|
||||
}
|
||||
|
||||
if (
|
||||
$response->status === 401
|
||||
&& str_contains($response->body, 'نام کاربری یا رمز عبور صحیح نیست')
|
||||
str_contains($result->body, 'loginCaptchaImage')
|
||||
|| preg_match('/<input\b[^>]*\bname\s*=\s*(["\'])password\1/is', $result->body) === 1
|
||||
) {
|
||||
throw new CollectorError(
|
||||
'The panel rejected the configured username or password.',
|
||||
|
||||
Reference in new issue
Block a user