Upgrade GeoIP functionality & replace the databases (#2471)

* Replaced Maxmind's IP database

* Began rebuilding GeoIP reader functionality

The GeoIP2 package does not worth with DB's that aren't built by maxmind themselves, making it rather unhelpful for us.

Since my long-term goal is for someone to be able to bring in their own DB, making a custom implementation seems like the reasonable choice.

(Plus my aim is already to replace the MaxMind DB due to it's licencing)

* Created an IP address lookup page

* + ASN info

* Bump last patch

* Make PHPStan happy

* Very minor refactor + PHPDocs
This commit is contained in:
Belle Aerni authored and GitHub committed 2024-10-31 19:31:50 +01:00
1 parent 2b431f8757
commit a5d15c2a99
27 files changed
+526 -210

No files matched your search

+3 -3
View File
@@ -709,14 +709,14 @@ $di['license_server'] = function () use ($di) {
/*
* @param void
*
* @return \GeoIp2\Database\Reader
* @return \FOSSBilling\GeoIP\Reader
*/
$di['geoip'] = fn (): \GeoIp2\Database\Reader => new GeoIp2\Database\Reader(PATH_LIBRARY . '/GeoLite2-Country.mmdb');
$di['geoip'] = fn (): FOSSBilling\GeoIP\Reader => new FOSSBilling\GeoIP\Reader(PATH_LIBRARY . '/FOSSBilling/GeoIP/Databases/CC0-Country.mmdb');
/*
* @param void
*
* @return \Box_Password
* @return \FOSSBilling\PasswordManager
*/
$di['password'] = fn (): \FOSSBilling\PasswordManager => new FOSSBilling\PasswordManager();
+1 -1
View File
@@ -315,7 +315,7 @@ LOCK TABLES `setting` WRITE;
INSERT INTO `setting` (`id`, `param`, `value`, `public`, `category`, `hash`, `created_at`, `updated_at`)
VALUES
(1,'last_patch','42',0,NULL,NULL,'2024-01-04 12:00:00','2024-01-04 12:00:00'),
(1,'last_patch','43',0,NULL,NULL,'2024-01-04 12:00:00','2024-01-04 12:00:00'),
(2,'company_name','Company Name',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'),
(3,'company_email','company@email.com',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'),
(4,'company_signature','FOSSBilling.org - Client Management, Invoicing and Support Software',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'),
+1 -1
View File
@@ -480,7 +480,7 @@ LOCK TABLES `setting` WRITE;
INSERT INTO `setting` (`id`, `param`, `value`, `public`, `category`, `hash`, `created_at`, `updated_at`)
VALUES
(1,'last_patch','42',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'),
(1,'last_patch','43',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'),
(2,'company_name','FOSSBilling demo',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'),
(3,'company_email','demo@fossbilling.org',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'),
(4,'company_signature','FOSSBilling.org - Client Management, Invoicing and Support Software',0,NULL,NULL,'2022-12-01 12:00:00','2022-12-01 12:00:00'),
+14 -1
View File
@@ -69,6 +69,8 @@ class Box_TwigExtensions extends AbstractExtension implements InjectionAwareInte
'money_convert' => new TwigFilter('money_convert', $this->twig_money_convert(...), ['needs_environment' => true, 'is_safe' => ['html']]),
'money_convert_without_currency' => new TwigFilter('money_convert_without_currency', $this->money_convert_without_currency(...), ['needs_environment' => true, 'is_safe' => ['html']]),
'iplookup' => new TwigFilter('iplookup', $this->ipLookupLink(...), ['is_safe' => ['html']]),
// We override these default twig filters so we can explicitly disable it from calling certain functions that may leak data or allow commands to be executed on the system.
'filter' => new TwigFilter('filter', $this->filteredFilter(...)),
'map' => new TwigFilter('map', $this->filteredMap(...)),
@@ -96,7 +98,7 @@ class Box_TwigExtensions extends AbstractExtension implements InjectionAwareInte
try {
$record = $this->di['geoip']->country($value);
return $record->country->name;
return $record->name;
} catch (Exception) {
return '';
}
@@ -366,4 +368,15 @@ class Box_TwigExtensions extends AbstractExtension implements InjectionAwareInte
return $array;
}
public function ipLookupLink(?string $ip)
{
if ($ip === null || $ip === '') {
return '';
}
$link = $this->di['url']->adminLink('security/iplookup', ['ip' => $ip]);
return "<a href='{$link}' target='_blank' class='iplookuplink'>{$ip}</a>";
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
/**
* Copyright 2022-2024 FOSSBilling
* Copyright 2011-2021 BoxBilling, Inc.
* SPDX-License-Identifier: Apache-2.0.
*
* @copyright FOSSBilling (https://www.fossbilling.org)
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
*/
namespace FOSSBilling\GeoIP;
class ASN implements \JsonSerializable
{
private readonly int|float $asnNumber;
private readonly string $asnOrg;
public function __construct(array $asnRecord)
{
if (!array_key_exists('autonomous_system_number', $asnRecord) || !array_key_exists('autonomous_system_organization', $asnRecord)) {
throw new IncompleteRecord('The is no ASN information for the provided IP address');
}
$this->asnNumber = $asnRecord['autonomous_system_number'];
$this->asnOrg = $asnRecord['autonomous_system_organization'];
}
public function jsonSerialize(): array
{
return [
'asnNumber' => $this->asnNumber,
'asnOrg' => $this->asnOrg,
];
}
}
+61
View File
@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
/**
* Copyright 2022-2024 FOSSBilling
* Copyright 2011-2021 BoxBilling, Inc.
* SPDX-License-Identifier: Apache-2.0.
*
* @copyright FOSSBilling (https://www.fossbilling.org)
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
*/
namespace FOSSBilling\GeoIP;
use PrinsFrank\Standards\Country\CountryAlpha2;
use PrinsFrank\Standards\Language\LanguageAlpha2;
class Country implements \JsonSerializable
{
/**
* Country name, translated based on the LanguageAlpha2 provided.
*/
public readonly string $name;
/**
* A flag emoji for the country. Does not display correctly on Windows.
*/
public readonly string $flag;
/**
* An array of Alpha3 currency codes for the given country.
*
* @var string[]
*/
public readonly array $currencies;
public function __construct(array $countyRecord, LanguageAlpha2 $language)
{
if (!array_key_exists('iso_code', $countyRecord)) {
throw new IncompleteRecord('The is no country information for the provided IP address');
}
// Instance the language
$country = CountryAlpha2::from($countyRecord['iso_code']);
$this->name = $country->getNameInLanguage($language);
$this->flag = $country->getFlagEmoji();
foreach ($country->getCurrenciesAlpha3() as $currency) {
$currencies[] = $currency->value;
}
$this->currencies = $currencies ?? [];
}
public function jsonSerialize(): array
{
return [
'name' => $this->name,
'flag' => $this->flag,
'currencies' => $this->currencies,
];
}
}
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
/**
* Copyright 2022-2024 FOSSBilling
* Copyright 2011-2021 BoxBilling, Inc.
* SPDX-License-Identifier: Apache-2.0.
*
* @copyright FOSSBilling (https://www.fossbilling.org)
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
*/
namespace FOSSBilling\GeoIP;
class IncompleteRecord extends \Exception
{
}
+96
View File
@@ -0,0 +1,96 @@
<?php
declare(strict_types=1);
/**
* Copyright 2022-2024 FOSSBilling
* Copyright 2011-2021 BoxBilling, Inc.
* SPDX-License-Identifier: Apache-2.0.
*
* @copyright FOSSBilling (https://www.fossbilling.org)
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
*/
namespace FOSSBilling\GeoIP;
use FOSSBilling\i18n;
use FOSSBilling\StandardsHelper;
use MaxMind\Db\Reader as MaxMindReader;
use MaxMind\Db\Reader\InvalidDatabaseException;
use PrinsFrank\Standards\Language\LanguageAlpha2;
class Reader
{
private readonly MaxMindReader $reader;
private readonly LanguageAlpha2 $language;
/**
* Constructs a new GeoIP reader instance.
*
* @param string $database a path to the database to load
* @param string $locale (Optional) the locale to use for country names. Defaults to the locale being used by FOSSBilling.
*
* @throws \InvalidArgumentException for invalid database path or unknown arguments
* @throws InvalidDatabaseException if the database is invalid or there is an error reading from it
*/
public function __construct(string $database, string $locale = null)
{
$this->reader = new MaxMindReader($database);
if ($locale === null) {
$locale = i18n::getActiveLocale();
}
$this->language = StandardsHelper::getLanguageObject(false, $locale);
}
/**
* Retrieves the record for the IP address.
*
* @param string $ipAddress the IP address to look up
*
* @return array the record for the IP address
*
* @throws \InvalidArgumentException if something other than a single IP address is passed to the method
* @throws InvalidDatabaseException if the database is invalid or there is an error reading from it
*/
public function get(string $ipAddress)
{
return $this->reader->get($ipAddress);
}
/**
* Retrieves the country for an IP address.
*
* @param string $ipAddress the IP address to look up
*
* @return Country A country object for the associated record
*
* @throws IncompleteRecord if the record for the given IP address does not contain the needed information
* @throws \InvalidArgumentException if something other than a single IP address is passed to the method
* @throws InvalidDatabaseException if the database is invalid or there is an error reading from it
*/
public function country(string $ipAddress): Country
{
$record = $this->get($ipAddress);
return new Country($record['country'] ?? [], $this->language);
}
/**
* Returns the ASN information for an IP address.
*
* @param string $ipAddress the IP address to look up
*
* @return ASN the ASN object for the associated record
*
* @throws IncompleteRecord if the record for the given IP address does not contain the needed information
* @throws \InvalidArgumentException if something other than a single IP address is passed to the method
* @throws InvalidDatabaseException if the database is invalid or there is an error reading from it
*/
public function asn(string $ipAddress): ASN
{
$record = $this->get($ipAddress);
return new ASN($record);
}
}
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
/**
* Copyright 2022-2024 FOSSBilling
* Copyright 2011-2021 BoxBilling, Inc.
* SPDX-License-Identifier: Apache-2.0.
*
* @copyright FOSSBilling (https://www.fossbilling.org)
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
*/
namespace FOSSBilling;
use PrinsFrank\Standards\Language\LanguageAlpha2;
class StandardsHelper
{
public static function getLanguageObject(bool $exactMatch = false, string $locale = null): LanguageAlpha2
{
// Automatically select the locale that's currently in use if not otherwise specified.
if ($locale === null) {
$locale = i18n::getActiveLocale();
}
$original = $locale;
// Handle our locale tags and turn them into the closes Alpha 2 match.
if (!$exactMatch && str_contains($locale, '_')) {
$locale = explode('_', $locale)[0];
} elseif (str_contains($locale, '_')) {
throw new InformationException('Exact matches cannot be provided unless you provide an Alpha2 language code.');
}
if (strlen($locale) === 2) {
return LanguageAlpha2::from($locale);
}
throw new \ValueError("No matching Alpha2 language found for {$original}");
}
}
@@ -394,6 +394,12 @@ class UpdatePatcher implements InjectionAwareInterface
$ext_service->setConfig($config);
},
43 => function (): void {
$fileActions = [
PATH_LIBRARY . DIRECTORY_SEPARATOR . 'GeoLite2-Country.mmdb' => 'unlink',
];
$this->executeFileActions($fileActions);
},
];
ksort($patches, SORT_NATURAL);
Binary file not shown.
@@ -58,7 +58,7 @@
{% endif %}
</td>
<td>{{ event.message }}</td>
<td>{{ event.ip }}</td>
<td>{{ event.ip|iplookup }}</td>
<td>{{ event.ip|ipcountryname|default('Unknown') }}</td>
<td>{{ event.created_at|format_datetime }}</td>
<td>
@@ -9,7 +9,7 @@
{% block content %}
<div class="card overflow-auto">
<div class="card-body">
<h5>{{ 'Clients logins history'|trans }}</h5>
<h5>{{ 'Client login history'|trans }}</h5>
</div>
{% include 'partial_search.html.twig' %}
@@ -43,7 +43,7 @@
<td>
<a href="{{ 'client/manage'|alink }}/{{ event.client.id }}">{{ event.client.first_name }} {{ event.client.last_name }}</a>
</td>
<td>{{ event.ip }}</td>
<td>{{ event.ip|iplookup }}</td>
<td>{{ event.ip|ipcountryname|default('Unknown') }}</td>
<td>{{ event.created_at|format_datetime }}</td>
<td>
@@ -115,7 +115,7 @@
{% endif %}
<tr>
<td class="text-end">IP:</td>
<td>{{ client.ip|default('-') }} {{ client.ip|ipcountryname|default('Unknown') }}</td>
<td>{%if client.ip %}{{ client.ip|iplookup }}{% else %}{{ 'Unknown'|trans }}{% endif %}</td>
</tr>
<tr>
<td class="text-end">{{ 'API Key'|trans }}:</td>
@@ -724,7 +724,7 @@
<div class="tab-pane fade" id="tab-history" role="tabpanel" aria-labelledby="history-tab">
<div class="card-body">
<h5>{{ 'Logins history'|trans }}</h5>
<h5>{{ 'Login history'|trans }}</h5>
</div>
<div class="table-responsive">
@@ -741,7 +741,7 @@
{% set logins = admin.client_login_history_get_list({ 'per_page': 10, 'page': request.page, 'client_id': client.id }) %}
{% for i, login in logins.list %}
<tr>
<td>{{ login.ip }}</td>
<td>{{ login.ip|iplookup }}</td>
<td>{{ login.ip|ipcountryname|default('Unknown') }}</td>
<td>{{ login.created_at|format_datetime }}</td>
</tr>
+25
View File
@@ -0,0 +1,25 @@
<?php
/**
* Copyright 2022-2024 FOSSBilling
* Copyright 2011-2021 BoxBilling, Inc.
* SPDX-License-Identifier: Apache-2.0.
*
* @copyright FOSSBilling (https://www.fossbilling.org)
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
*/
namespace Box\Mod\Security\Api;
use FOSSBilling\InformationException;
class Admin extends \Api_Abstract
{
public function ip_lookup($data)
{
if (!isset($data['ip'])) {
throw new InformationException('You must specify an IP address to lookup.');
}
return $this->getService()->lookupIP($data['ip']);
}
}
+46
View File
@@ -0,0 +1,46 @@
<?php
/**
* Copyright 2022-2024 FOSSBilling
* Copyright 2011-2021 BoxBilling, Inc.
* SPDX-License-Identifier: Apache-2.0.
*
* @copyright FOSSBilling (https://www.fossbilling.org)
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
*/
namespace Box\Mod\Security\Controller;
class Admin implements \FOSSBilling\InjectionAwareInterface
{
protected ?\Pimple\Container $di = null;
public function setDi(\Pimple\Container $di): void
{
$this->di = $di;
}
public function getDi(): ?\Pimple\Container
{
return $this->di;
}
public function register(\Box_App &$app)
{
$app->get('/security/iplookup', 'ip_lookup', [], static::class);
}
public function ip_lookup(\Box_App $app)
{
$this->di['is_admin_logged'];
$record = [];
if (isset($_GET['ip']) && filter_var($_GET['ip'], FILTER_VALIDATE_IP)) {
try {
$record = $this->di['api']('admin')->Security_IP_Lookup(['ip' => $_GET['ip']]);
} catch (\Exception) {
}
}
return $app->render('mod_security_iplookup', ['record' => $record]);
}
}
+66
View File
@@ -0,0 +1,66 @@
<?php
/**
* Copyright 2022-2024 FOSSBilling
* Copyright 2011-2021 BoxBilling, Inc.
* SPDX-License-Identifier: Apache-2.0.
*
* @copyright FOSSBilling (https://www.fossbilling.org)
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0
*/
namespace Box\Mod\Security;
use FOSSBilling\GeoIP\IncompleteRecord;
class Service
{
protected ?\Pimple\Container $di = null;
public function setDi(\Pimple\Container $di): void
{
$this->di = $di;
}
public function getDi(): ?\Pimple\Container
{
return $this->di;
}
public function getModulePermissions(): array
{
return [
'can_always_access' => true,
'hide_permissions' => true,
];
}
public function lookupIP(string $ip)
{
if (!filter_var($ip, FILTER_VALIDATE_IP)) {
throw new \InvalidArgumentException('The provided input was not a valid IP address');
}
try {
$countryInfo = $this->di['geoip']->country($ip);
} catch (IncompleteRecord) {
$countryInfo = [];
}
try {
$asnReader = new \FOSSBilling\GeoIP\Reader(PATH_LIBRARY . '/FOSSBilling/GeoIP/Databases/PDDL-ASN.mmdb');
$asnInfo = $asnReader->asn($ip);
} catch (IncompleteRecord) {
$asnInfo = [];
}
return [
'ip' => [
'address' => $ip,
'type' => filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) ? 'IPv4' : 'IPv6',
],
'country' => json_decode(json_encode($countryInfo), true),
'asn' => json_decode(json_encode($asnInfo), true),
];
}
}
@@ -0,0 +1,83 @@
{% extends request.ajax ? 'layout_blank.html.twig' : 'layout_default.html.twig' %}
{% import 'macro_functions.html.twig' as mf %}
{% block meta_title %}{{ 'IP lookup'|trans }}{% endblock %}
{% set active_menu = 'system' %}
{% block content %}
<div class="card">
<div class="card-header">
<div>
<h3 class="card-title">{{ 'IP lookup'|trans }}</h3>
</div>
</div>
<div class="card-body border-bottom">
<span class="card-subtitle">{{ 'Lookup & discover info about IP addresses.'|trans }}</span>
</div>
<div class="card-body container">
<form method="post" action="{{'api/admin/security/ip_lookup'|link({ 'CSRFToken': CSRFToken }) }}"
class="api-form" data-api-jsonp="appendResult">
<div class="d-flex">
<input type="text" name="ip" class="form-control me-2" placeholder="IP address to lookup" {% if request.ip %}value="{{ request.ip }}"{% endif %}>
<button class="btn btn-primary" type="submit">{{ 'Submit'|trans }}</button>
</div>
</form>
<div class="table-responsive mt-4">
<table class="table table-striped" id="results">
<thead>
<tr>
<th scope="col">{{ 'IP Address'|trans }}</th>
<th scope="col">{{ 'Country'|trans }}</th>
<th scope="col">ASN #</th>
<th scope="col">{{ 'ASN Organization'|trans }}</th>
</tr>
</thead>
<tbody>
{% if record %}
<tr>
<td>{{ record.ip.address }} ({{ record.ip.type }})</td>
<td>{{ record.country.flag }} {{ record.country.name }}</td>
<td>{{ record.asn.asnNumber }}</td>
<td>{{ record.asn.asnOrg }}</td>
</tr>
{% endif %}
</tbody>
</table>
</div>
</div>
<div class="card-footer text-center">
<p>{{ 'ASN stands for autonomous system number. IP address info may not always be accurate.'|trans }}</p>
</div>
</div>
{% endblock %}
{% block js %}
<script>
function appendResult(result) {
const tableBody = document.querySelector('#results tbody');
const newRow = document.createElement('tr');
const addressCell = document.createElement('td');
addressCell.textContent = `${result.ip.address} (${result.ip.type})`;
const countryCell = document.createElement('td');
countryCell.textContent = `${result.country.flag} ${result.country.name}`;
const asnNumCell = document.createElement('td');
asnNumCell.textContent = `${result.asn.asnNumber}`;
const asnOrgCell = document.createElement('td');
asnOrgCell.textContent = `${result.asn.asnOrg}`;
newRow.appendChild(addressCell);
newRow.appendChild(countryCell);
newRow.appendChild(asnNumCell);
newRow.appendChild(asnOrgCell);
tableBody.insertBefore(newRow, tableBody.firstChild);
}
</script>
{% endblock %}
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 24 24"><path d="M3,1H19A1,1 0 0,1 20,2V6A1,1 0 0,1 19,7H3A1,1 0 0,1 2,6V2A1,1 0 0,1 3,1M3,9H19A1,1 0 0,1 20,10V10.67L17.5,9.56L11,12.44V15H3A1,1 0 0,1 2,14V10A1,1 0 0,1 3,9M3,17H11C11.06,19.25 12,21.4 13.46,23H3A1,1 0 0,1 2,22V18A1,1 0 0,1 3,17M8,5H9V3H8V5M8,13H9V11H8V13M8,21H9V19H8V21M4,3V5H6V3H4M4,11V13H6V11H4M4,19V21H6V19H4M17.5,12L22,14V17C22,19.78 20.08,22.37 17.5,23C14.92,22.37 13,19.78 13,17V14L17.5,12M17.5,13.94L15,15.06V17.72C15,19.26 16.07,20.7 17.5,21.06V13.94Z" /></svg>

After

Width:  |  Height:  |  Size: 559 B

+8
View File
@@ -0,0 +1,8 @@
{
"id": "security",
"type": "mod",
"name": "Security",
"description": "FOSSBilling core module",
"icon_url": "icon.svg",
"version": "1.0.0"
}
@@ -9,7 +9,7 @@
{% block content %}
<div class="card overflow-auto">
<div class="card-body">
<h5>{{ 'Staff members logins history'|trans }}</h5>
<h5>{{ 'Staff members login history'|trans }}</h5>
</div>
{% include 'partial_search.html.twig' %}
@@ -45,7 +45,7 @@
{{ event.staff.name }}
</a>
</td>
<td>{{ event.ip }}</td>
<td>{{ event.ip|iplookup }}</td>
<td>{{ event.ip|ipcountryname|default('Unknown') }}</td>
<td>{{ event.created_at|format_datetime }}</td>
<td>