You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
271 lines
9.7 KiB
PHP
271 lines
9.7 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\Configurations;
|
|
use App\Utils\QQWry;
|
|
|
|
/**
|
|
* Server-side country check for anonymous registration endpoints.
|
|
*
|
|
* The web server must place the real client address in REMOTE_ADDR. Forwarded
|
|
* headers never determine the address; a mismatch only fails closed.
|
|
*/
|
|
class RegistrationIpRestriction
|
|
{
|
|
public const CONFIG_KEY = 'cnreg';
|
|
public const DENY_CHINA = 'china';
|
|
public const DENY_UNKNOWN = 'unknown';
|
|
public const DENY_DATABASE_UNAVAILABLE = 'database_unavailable';
|
|
|
|
public static function configuredEnabled(): bool
|
|
{
|
|
try {
|
|
$redis = new RedisClient();
|
|
$value = $redis->get(self::CONFIG_KEY, 60, static function () {
|
|
return self::databaseValue(self::CONFIG_KEY, 'false');
|
|
});
|
|
} catch (\Throwable $exception) {
|
|
$value = self::databaseValue(self::CONFIG_KEY, 'false');
|
|
}
|
|
|
|
return $value === 'true';
|
|
}
|
|
|
|
public static function configuredEnglish(): bool
|
|
{
|
|
try {
|
|
$redis = new RedisClient();
|
|
$value = $redis->get('language', 60, static function () {
|
|
return self::databaseValue('language', 'false');
|
|
});
|
|
} catch (\Throwable $exception) {
|
|
$value = self::databaseValue('language', 'false');
|
|
}
|
|
|
|
return $value === 'true';
|
|
}
|
|
|
|
/** @return ?string One of the DENY_* codes, or null when registration is allowed. */
|
|
public static function denialForRequest($request, bool $enabled, ?callable $lookup = null): ?string
|
|
{
|
|
if (!$enabled) {
|
|
return null;
|
|
}
|
|
|
|
// Bootstrap snapshots the web-server peer address before loading the
|
|
// legacy configuration file, which may rewrite REMOTE_ADDR from an
|
|
// attacker-controlled forwarding header on older installations.
|
|
// The fallback exists only for isolated tests and CLI requests.
|
|
$ip = defined('ORIGINAL_REMOTE_ADDR')
|
|
? constant('ORIGINAL_REMOTE_ADDR')
|
|
: $request->getServerParam('REMOTE_ADDR', '');
|
|
if (self::hasForwardedAddressMismatch($request, $ip)) {
|
|
return self::DENY_UNKNOWN;
|
|
}
|
|
return self::denialForIp($ip, $lookup);
|
|
}
|
|
|
|
/**
|
|
* @param callable|null $lookup Optional test-only IPv4-to-location resolver.
|
|
* @return ?string One of the DENY_* codes, or null for a known non-China IP.
|
|
*/
|
|
public static function denialForIp($rawIp, ?callable $lookup = null): ?string
|
|
{
|
|
$ip = self::publicIpv4($rawIp);
|
|
if ($ip === null) {
|
|
return self::DENY_UNKNOWN;
|
|
}
|
|
|
|
if ($lookup === null) {
|
|
$basePath = defined('BASE_PATH') ? BASE_PATH : dirname(__DIR__, 2);
|
|
$databasePath = $basePath . '/storage/qqwry.dat';
|
|
if (!is_file($databasePath) || !is_readable($databasePath) || @filesize($databasePath) < 8) {
|
|
return self::DENY_DATABASE_UNAVAILABLE;
|
|
}
|
|
try {
|
|
$database = new QQWry();
|
|
} catch (\Throwable $exception) {
|
|
return self::DENY_DATABASE_UNAVAILABLE;
|
|
}
|
|
$lookup = static function ($address) use ($database) {
|
|
return @$database->getlocation($address);
|
|
};
|
|
}
|
|
|
|
try {
|
|
$location = $lookup($ip);
|
|
} catch (\Throwable $exception) {
|
|
return self::DENY_UNKNOWN;
|
|
}
|
|
if (!is_array($location) || !isset($location['country']) || !self::locationCoversIp($ip, $location)) {
|
|
return self::DENY_UNKNOWN;
|
|
}
|
|
|
|
return self::denialForCountry($location['country']);
|
|
}
|
|
|
|
public static function denialForCountry($country): ?string
|
|
{
|
|
$country = trim((string) $country);
|
|
if ($country === '') {
|
|
return self::DENY_UNKNOWN;
|
|
}
|
|
|
|
// QQWry strings are GBK/GB18030. In tests or alternate data sources,
|
|
// accept a valid UTF-8 string without converting it again.
|
|
if (!preg_match('//u', $country)) {
|
|
if (!function_exists('iconv')) {
|
|
return self::DENY_UNKNOWN;
|
|
}
|
|
$country = @iconv('GB18030', 'UTF-8//IGNORE', $country);
|
|
if ($country === false || !preg_match('//u', $country)) {
|
|
return self::DENY_UNKNOWN;
|
|
}
|
|
$country = trim($country);
|
|
}
|
|
|
|
if ($country === '' || preg_match('/^(未知|未查询到|局域网|内网|本机|保留地址|未分配|CZ88\.NET|IANA|Unknown|N\/A)/iu', $country)) {
|
|
return self::DENY_UNKNOWN;
|
|
}
|
|
|
|
// HK, MO and TW have separate GeoIP country codes from mainland CN.
|
|
if (preg_match('/^(中国|中國|中華人民共和國|中华人民共和国)?(香港|澳门|澳門|台湾|臺灣)/u', $country)) {
|
|
return null;
|
|
}
|
|
|
|
if (preg_match('/^(中国|中國|中華人民共和國|中华人民共和国)/u', $country)) {
|
|
return self::DENY_CHINA;
|
|
}
|
|
|
|
// Older QQWry releases occasionally put only a mainland province or
|
|
// municipality in the country field, without a leading "中国".
|
|
if (preg_match('/^(北京|天津|上海|重庆|河北|山西|辽宁|吉林|黑龙江|江苏|浙江|安徽|福建|江西|山东|河南|湖北|湖南|广东|海南|四川|贵州|云南|陕西|甘肃|青海|内蒙古|广西|西藏|宁夏|新疆)/u', $country)) {
|
|
return self::DENY_CHINA;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
public static function message(string $denial, bool $english): string
|
|
{
|
|
if ($denial === self::DENY_CHINA) {
|
|
return $english
|
|
? 'Registration is not available from mainland China IP addresses.'
|
|
: '暂不支持中国大陆 IP 注册';
|
|
}
|
|
|
|
if ($denial === self::DENY_DATABASE_UNAVAILABLE) {
|
|
return $english
|
|
? 'The IP location database is unavailable. Please contact the site administrator.'
|
|
: 'IP 地区数据库不可用,请联系网站管理员';
|
|
}
|
|
|
|
return $english
|
|
? 'We cannot verify your IP location right now. Please try again later or contact support.'
|
|
: '暂时无法验证当前 IP 所在地区,请稍后重试或联系管理员';
|
|
}
|
|
|
|
private static function publicIpv4($rawIp): ?string
|
|
{
|
|
$ip = trim((string) $rawIp);
|
|
if (stripos($ip, '::ffff:') === 0) {
|
|
$ip = substr($ip, 7);
|
|
}
|
|
|
|
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
|
|
return null;
|
|
}
|
|
|
|
return $ip;
|
|
}
|
|
|
|
private static function locationCoversIp(string $ip, array $location): bool
|
|
{
|
|
$begin = $location['beginip'] ?? null;
|
|
$end = $location['endip'] ?? null;
|
|
if (!is_string($begin) || !is_string($end)
|
|
|| filter_var($begin, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false
|
|
|| filter_var($end, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
|
|
return false;
|
|
}
|
|
|
|
// QQWry returns its last row when a lookup misses. Validate that the
|
|
// returned range actually contains this address before trusting it.
|
|
$addressBytes = inet_pton($ip);
|
|
$beginBytes = inet_pton($begin);
|
|
$endBytes = inet_pton($end);
|
|
return $addressBytes !== false && $beginBytes !== false && $endBytes !== false
|
|
&& strcmp($beginBytes, $addressBytes) <= 0
|
|
&& strcmp($addressBytes, $endBytes) <= 0;
|
|
}
|
|
|
|
private static function hasForwardedAddressMismatch($request, $peerIp): bool
|
|
{
|
|
$peerIp = self::publicIpv4($peerIp);
|
|
if ($peerIp === null) {
|
|
return true;
|
|
}
|
|
|
|
foreach (['X-Forwarded-For', 'CF-Connecting-IP', 'X-Real-IP', 'True-Client-IP'] as $header) {
|
|
$value = trim((string) $request->getHeaderLine($header));
|
|
if ($value === '') {
|
|
continue;
|
|
}
|
|
if ($header === 'X-Forwarded-For') {
|
|
$value = trim(explode(',', $value, 2)[0]);
|
|
}
|
|
if (self::forwardedIpv4($value) !== $peerIp) {
|
|
return true;
|
|
}
|
|
}
|
|
|
|
$forwarded = trim((string) $request->getHeaderLine('Forwarded'));
|
|
if ($forwarded !== '') {
|
|
$firstHop = explode(',', $forwarded, 2)[0];
|
|
$address = null;
|
|
foreach (explode(';', $firstHop) as $parameter) {
|
|
if (preg_match('/^\s*for\s*=\s*(.+)\s*$/i', $parameter, $matches)) {
|
|
$address = trim($matches[1], " \t\r\n\"'");
|
|
break;
|
|
}
|
|
}
|
|
if ($address === null || self::forwardedIpv4($address) !== $peerIp) {
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
private static function forwardedIpv4($value): ?string
|
|
{
|
|
$value = trim((string) $value);
|
|
if (preg_match('/^\[([^\]]+)\](?::([0-9]{1,5}))?$/', $value, $matches)) {
|
|
$value = $matches[1];
|
|
$port = $matches[2] ?? null;
|
|
} elseif (preg_match('/^([0-9.]+):([0-9]{1,5})$/', $value, $matches)) {
|
|
$value = $matches[1];
|
|
$port = $matches[2];
|
|
} else {
|
|
$port = null;
|
|
}
|
|
|
|
if ($port !== null && ((int) $port < 1 || (int) $port > 65535)) {
|
|
return null;
|
|
}
|
|
|
|
return self::publicIpv4($value);
|
|
}
|
|
|
|
private static function databaseValue(string $key, string $default): string
|
|
{
|
|
try {
|
|
$value = Configurations::where('name', $key)->value('value');
|
|
return $value === null ? $default : (string) $value;
|
|
} catch (\Throwable $exception) {
|
|
return $default;
|
|
}
|
|
}
|
|
}
|