Skip to content

Commit

Permalink
Merge pull request #43908 from nextcloud/feat/migrate-data-directory-…
Browse files Browse the repository at this point in the history
…setup-check

feat(settings): Migrate data directory protection check to `SetupCheck`
  • Loading branch information
susnux authored Feb 29, 2024
2 parents 1feb4f1 + ef2c312 commit 1e9f438
Show file tree
Hide file tree
Showing 11 changed files with 230 additions and 78 deletions.
1 change: 1 addition & 0 deletions apps/settings/composer/composer/autoload_classmap.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@
'OCA\\Settings\\SetupChecks\\CodeIntegrity' => $baseDir . '/../lib/SetupChecks/CodeIntegrity.php',
'OCA\\Settings\\SetupChecks\\CronErrors' => $baseDir . '/../lib/SetupChecks/CronErrors.php',
'OCA\\Settings\\SetupChecks\\CronInfo' => $baseDir . '/../lib/SetupChecks/CronInfo.php',
'OCA\\Settings\\SetupChecks\\DataDirectoryProtected' => $baseDir . '/../lib/SetupChecks/DataDirectoryProtected.php',
'OCA\\Settings\\SetupChecks\\DatabaseHasMissingColumns' => $baseDir . '/../lib/SetupChecks/DatabaseHasMissingColumns.php',
'OCA\\Settings\\SetupChecks\\DatabaseHasMissingIndices' => $baseDir . '/../lib/SetupChecks/DatabaseHasMissingIndices.php',
'OCA\\Settings\\SetupChecks\\DatabaseHasMissingPrimaryKeys' => $baseDir . '/../lib/SetupChecks/DatabaseHasMissingPrimaryKeys.php',
Expand Down
1 change: 1 addition & 0 deletions apps/settings/composer/composer/autoload_static.php
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ class ComposerStaticInitSettings
'OCA\\Settings\\SetupChecks\\CodeIntegrity' => __DIR__ . '/..' . '/../lib/SetupChecks/CodeIntegrity.php',
'OCA\\Settings\\SetupChecks\\CronErrors' => __DIR__ . '/..' . '/../lib/SetupChecks/CronErrors.php',
'OCA\\Settings\\SetupChecks\\CronInfo' => __DIR__ . '/..' . '/../lib/SetupChecks/CronInfo.php',
'OCA\\Settings\\SetupChecks\\DataDirectoryProtected' => __DIR__ . '/..' . '/../lib/SetupChecks/DataDirectoryProtected.php',
'OCA\\Settings\\SetupChecks\\DatabaseHasMissingColumns' => __DIR__ . '/..' . '/../lib/SetupChecks/DatabaseHasMissingColumns.php',
'OCA\\Settings\\SetupChecks\\DatabaseHasMissingIndices' => __DIR__ . '/..' . '/../lib/SetupChecks/DatabaseHasMissingIndices.php',
'OCA\\Settings\\SetupChecks\\DatabaseHasMissingPrimaryKeys' => __DIR__ . '/..' . '/../lib/SetupChecks/DatabaseHasMissingPrimaryKeys.php',
Expand Down
2 changes: 2 additions & 0 deletions apps/settings/lib/AppInfo/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
use OCA\Settings\SetupChecks\DatabaseHasMissingIndices;
use OCA\Settings\SetupChecks\DatabaseHasMissingPrimaryKeys;
use OCA\Settings\SetupChecks\DatabasePendingBigIntConversions;
use OCA\Settings\SetupChecks\DataDirectoryProtected;
use OCA\Settings\SetupChecks\DebugMode;
use OCA\Settings\SetupChecks\DefaultPhoneRegionSet;
use OCA\Settings\SetupChecks\EmailTestSuccessful;
Expand Down Expand Up @@ -183,6 +184,7 @@ public function register(IRegistrationContext $context): void {
$context->registerSetupCheck(DatabaseHasMissingIndices::class);
$context->registerSetupCheck(DatabaseHasMissingPrimaryKeys::class);
$context->registerSetupCheck(DatabasePendingBigIntConversions::class);
$context->registerSetupCheck(DataDirectoryProtected::class);
$context->registerSetupCheck(DebugMode::class);
$context->registerSetupCheck(DefaultPhoneRegionSet::class);
$context->registerSetupCheck(EmailTestSuccessful::class);
Expand Down
8 changes: 5 additions & 3 deletions apps/settings/lib/SetupChecks/CheckServerResponseTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -74,11 +74,12 @@ protected function getTestUrls(string $url): array {
* Run a HEAD request to check header
* @param string $url The relative URL to check
* @param bool $ignoreSSL Ignore SSL certificates
* @param bool $httpErrors Ignore requests with HTTP errors (will not yield if request has a 4xx or 5xx response)
* @return Generator<int, IResponse>
*/
protected function runHEAD(string $url, bool $ignoreSSL = true): Generator {
protected function runHEAD(string $url, bool $ignoreSSL = true, bool $httpErrors = true): Generator {
$client = $this->clientService->newClient();
$requestOptions = $this->getRequestOptions($ignoreSSL);
$requestOptions = $this->getRequestOptions($ignoreSSL, $httpErrors);

foreach ($this->getTestUrls($url) as $testURL) {
try {
Expand All @@ -89,9 +90,10 @@ protected function runHEAD(string $url, bool $ignoreSSL = true): Generator {
}
}

protected function getRequestOptions(bool $ignoreSSL): array {
protected function getRequestOptions(bool $ignoreSSL, bool $httpErrors): array {
$requestOptions = [
'connect_timeout' => 10,
'http_errors' => $httpErrors,
'nextcloud' => [
'allow_local_address' => true,
],
Expand Down
80 changes: 80 additions & 0 deletions apps/settings/lib/SetupChecks/DataDirectoryProtected.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<?php

declare(strict_types=1);

/**
* @copyright Copyright (c) 2024 Ferdinand Thiessen <opensource@fthiessen.de>
*
* @author Ferdinand Thiessen <opensource@fthiessen.de>
*
* @license AGPL-3.0-or-later
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Settings\SetupChecks;

use OCP\Http\Client\IClientService;
use OCP\IConfig;
use OCP\IL10N;
use OCP\IURLGenerator;
use OCP\SetupCheck\ISetupCheck;
use OCP\SetupCheck\SetupResult;
use Psr\Log\LoggerInterface;

/**
* Checks if the data directory can not be accessed from outside
*/
class DataDirectoryProtected implements ISetupCheck {
use CheckServerResponseTrait;

public function __construct(
protected IL10N $l10n,
protected IConfig $config,
protected IURLGenerator $urlGenerator,
protected IClientService $clientService,
protected LoggerInterface $logger,
) {
}

public function getCategory(): string {
return 'network';
}

public function getName(): string {
return $this->l10n->t('Data directory protected');
}

public function run(): SetupResult {
$datadir = str_replace(\OC::$SERVERROOT . '/', '', $this->config->getSystemValue('datadirectory', ''));

$dataUrl = $this->urlGenerator->getWebroot() . '/' . $datadir . '/.ocdata';

$noResponse = true;
foreach ($this->runHEAD($dataUrl, httpErrors:false) as $response) {
$noResponse = false;
if ($response->getStatusCode() === 200) {
return SetupResult::error($this->l10n->t('Your data directory and files are probably accessible from the internet. The .htaccess file is not working. It is strongly recommended that you configure your web server so that the data directory is no longer accessible, or move the data directory outside the web server document root.'));
} else {
$this->logger->debug('[expected] Could not access data directory from outside.', ['url' => $dataUrl]);
}
}

if ($noResponse) {
return SetupResult::warning($this->l10n->t('Could not check that the data directory is protected. Please check manually that your server does not allow access to the data directory.') . "\n" . $this->serverConfigHelp());
}
return SetupResult::success();

}
}
5 changes: 2 additions & 3 deletions apps/settings/src/admin.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,9 +108,8 @@ window.addEventListener('DOMContentLoaded', () => {
OC.SetupChecks.checkWellKnownUrl('PROPFIND', '/.well-known/carddav', OC.theme.docPlaceholderUrl, $('#postsetupchecks').data('check-wellknown') === true),
OC.SetupChecks.checkSetup(),
OC.SetupChecks.checkGeneric(),
OC.SetupChecks.checkDataProtected(),
).then((check1, check2, check3, check4, check5, check6, check7, check8) => {
const messages = [].concat(check1, check2, check3, check4, check5, check6, check7, check8)
).then((check1, check2, check3, check4, check5, check6, check7) => {
const messages = [].concat(check1, check2, check3, check4, check5, check6, check7)
const $el = $('#postsetupchecks')
$('#security-warning-state-loading').addClass('hidden')

Expand Down
136 changes: 136 additions & 0 deletions apps/settings/tests/SetupChecks/DataDirectoryProtectedTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
<?php

declare(strict_types=1);

/**
* @copyright Copyright (c) 2024 Ferdinand Thiessen <opensource@fthiessen.de>
*
* @author Ferdinand Thiessen <opensource@fthiessen.de>
*
* @license AGPL-3.0-or-later
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace OCA\Settings\Tests;

use OCA\Settings\SetupChecks\DataDirectoryProtected;
use OCP\Http\Client\IClientService;
use OCP\Http\Client\IResponse;
use OCP\IConfig;
use OCP\IL10N;
use OCP\IURLGenerator;
use OCP\SetupCheck\SetupResult;
use PHPUnit\Framework\MockObject\MockObject;
use Psr\Log\LoggerInterface;
use Test\TestCase;

class DataDirectoryProtectedTest extends TestCase {
private IL10N|MockObject $l10n;
private IConfig|MockObject $config;
private IURLGenerator|MockObject $urlGenerator;
private IClientService|MockObject $clientService;
private LoggerInterface|MockObject $logger;
private DataDirectoryProtected|MockObject $setupcheck;

protected function setUp(): void {
parent::setUp();

/** @var IL10N|MockObject */
$this->l10n = $this->getMockBuilder(IL10N::class)
->disableOriginalConstructor()->getMock();
$this->l10n->expects($this->any())
->method('t')
->willReturnCallback(function ($message, array $replace) {
return vsprintf($message, $replace);
});

$this->config = $this->createMock(IConfig::class);
$this->urlGenerator = $this->createMock(IURLGenerator::class);
$this->clientService = $this->createMock(IClientService::class);
$this->logger = $this->createMock(LoggerInterface::class);

$this->setupcheck = $this->getMockBuilder(DataDirectoryProtected::class)
->onlyMethods(['runHEAD'])
->setConstructorArgs([
$this->l10n,
$this->config,
$this->urlGenerator,
$this->clientService,
$this->logger,
])
->getMock();
}

/**
* @dataProvider dataTestStatusCode
*/
public function testStatusCode(array $status, string $expected): void {
$responses = array_map(function ($state) {
$response = $this->createMock(IResponse::class);
$response->expects($this->any())->method('getStatusCode')->willReturn($state);
return $response;
}, $status);

$this->setupcheck
->expects($this->once())
->method('runHEAD')
->will($this->generate($responses));

$this->config
->expects($this->once())
->method('getSystemValue')
->willReturn('');

$result = $this->setupcheck->run();
$this->assertEquals($expected, $result->getSeverity());
}

public function dataTestStatusCode(): array {
return [
'success: forbidden access' => [[403], SetupResult::SUCCESS],
'error: can access' => [[200], SetupResult::ERROR],
'error: one forbidden one can access' => [[403, 200], SetupResult::ERROR],
'warning: connection issue' => [[], SetupResult::WARNING],
];
}

public function testNoResponse(): void {
$response = $this->createMock(IResponse::class);
$response->expects($this->any())->method('getStatusCode')->willReturn(200);

$this->setupcheck
->expects($this->once())
->method('runHEAD')
->will($this->generate([]));

$this->config
->expects($this->once())
->method('getSystemValue')
->willReturn('');

$result = $this->setupcheck->run();
$this->assertEquals(SetupResult::WARNING, $result->getSeverity());
$this->assertMatchesRegularExpression('/^Could not check/', $result->getDescription());
}

/**
* Helper function creates a nicer interface for mocking Generator behavior
*/
protected function generate(array $yield_values) {
return $this->returnCallback(function () use ($yield_values) {
yield from $yield_values;
});
}
}
26 changes: 0 additions & 26 deletions core/js/setupchecks.js
Original file line number Diff line number Diff line change
Expand Up @@ -239,32 +239,6 @@
return deferred.promise();
},

checkDataProtected: function() {
var deferred = $.Deferred();
if(oc_dataURL === false){
return deferred.resolve([]);
}
var afterCall = function(xhr) {
var messages = [];
// .ocdata is an empty file in the data directory - if this is readable then the data dir is not protected
if (xhr.status === 200 && xhr.responseText === '') {
messages.push({
msg: t('core', 'Your data directory and files are probably accessible from the internet. The .htaccess file is not working. It is strongly recommended that you configure your web server so that the data directory is no longer accessible, or move the data directory outside the web server document root.'),
type: OC.SetupChecks.MESSAGE_TYPE_ERROR
});
}
deferred.resolve(messages);
};

$.ajax({
type: 'GET',
url: OC.linkTo('', oc_dataURL+'/.ocdata?t=' + (new Date()).getTime()),
complete: afterCall,
allowAuthErrors: true
});
return deferred.promise();
},

/**
* Runs check for some generic security headers on the server side
*
Expand Down
43 changes: 0 additions & 43 deletions core/js/tests/specs/setupchecksSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -107,49 +107,6 @@ describe('OC.SetupChecks tests', function() {
});
});

describe('checkDataProtected', function() {

oc_dataURL = "data";

it('should return an error if data directory is not protected', function(done) {
var async = OC.SetupChecks.checkDataProtected();

suite.server.requests[0].respond(200, {'Content-Type': 'text/plain'}, '');

async.done(function( data, s, x ){
expect(data).toEqual([
{
msg: 'Your data directory and files are probably accessible from the internet. The .htaccess file is not working. It is strongly recommended that you configure your web server so that the data directory is no longer accessible, or move the data directory outside the web server document root.',
type: OC.SetupChecks.MESSAGE_TYPE_ERROR
}]);
done();
});
});

it('should not return an error if data directory is protected', function(done) {
var async = OC.SetupChecks.checkDataProtected();

suite.server.requests[0].respond(403);

async.done(function( data, s, x ){
expect(data).toEqual([]);
done();
});
});

it('should return an error if data directory is a boolean', function(done) {

oc_dataURL = false;

var async = OC.SetupChecks.checkDataProtected();

async.done(function( data, s, x ){
expect(data).toEqual([]);
done();
});
});
});

describe('checkSetup', function() {
it('should return an error if server has no internet connection', function(done) {
var async = OC.SetupChecks.checkSetup();
Expand Down
Loading

0 comments on commit 1e9f438

Please sign in to comment.