Skip to content

Commit

Permalink
Merge pull request #33031 from nextcloud/fix/improve-local-ip-detection
Browse files Browse the repository at this point in the history
Improve local IP detection
  • Loading branch information
come-nc authored Jul 26, 2022
2 parents 9f77aba + c5ffd7c commit 7615536
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
16 changes: 14 additions & 2 deletions lib/private/Http/Client/LocalAddressChecker.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@

use OCP\Http\Client\LocalServerException;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\IpUtils;

class LocalAddressChecker {
private LoggerInterface $logger;
Expand All @@ -36,7 +37,16 @@ public function __construct(LoggerInterface $logger) {
}

public function ThrowIfLocalIp(string $ip) : void {
if ((bool)filter_var($ip, FILTER_VALIDATE_IP) && !filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
$localRanges = [
'100.64.0.0/10', // See RFC 6598
'192.0.0.0/24', // See RFC 6890
];
if (
(bool)filter_var($ip, FILTER_VALIDATE_IP) &&
(
!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) ||
IpUtils::checkIp($ip, $localRanges)
)) {
$this->logger->warning("Host $ip was not connected to because it violates local access rules");
throw new LocalServerException('Host violates local access rules');
}
Expand All @@ -46,7 +56,9 @@ public function ThrowIfLocalIp(string $ip) : void {
$delimiter = strrpos($ip, ':'); // Get last colon
$ipv4Address = substr($ip, $delimiter + 1);

if (!filter_var($ipv4Address, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
if (
!filter_var($ipv4Address, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) ||
IpUtils::checkIp($ip, $localRanges)) {
$this->logger->warning("Host $ip was not connected to because it violates local access rules");
throw new LocalServerException('Host violates local access rules');
}
Expand Down
5 changes: 5 additions & 0 deletions tests/lib/Http/Client/LocalAddressCheckerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ public function dataInternalIPs() : array {
['10.0.0.1'],
['::'],
['::1'],
['100.100.100.200'],
['192.0.0.1'],
];
}

Expand All @@ -116,6 +118,9 @@ public function dataPreventLocalAddress():array {
['another-host.local'],
['service.localhost'],
['!@#$'], // test invalid url
['100.100.100.200'],
['192.0.0.1'],
['randomdomain.internal'],
];
}

Expand Down

0 comments on commit 7615536

Please sign in to comment.