Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,8 @@ Credential sources are vault, credential file, and instance identity ([ADR 0007]
| Google Cloud | Service account JSON key; only `client_email`, `private_key`, and `private_key_id` are used | Metadata server (phase 3) |
| Azure | Tenant ID, client ID, client secret | Managed identity (phase 4) |

A credential file must sit inside the Credential File Directory, a Cloud setting on Cacti's Settings page. Only full administrators can change it, and it is empty by default, which refuses credential files. Cloud Admin picks an account's file, so without this limit it could name any file the Cacti user can read, the vault key included, and have the collector send it to the provider. A path outside the directory is refused before the file is opened, so the refusal reveals nothing about the file.

Short-lived tokens are cached per collector run. When a provider limits how often tokens can be issued, they are cached in the vault with their expiry.

## Security
Expand Down
44 changes: 43 additions & 1 deletion lib/CredentialFile.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,40 @@ public static function pathAcceptable(string $path): bool {
return SecureFile::pathAcceptable($path);
}

/**
* Whether $path names a file inside $directory, the credential directory a
* full administrator set on Cacti's Settings page. Cloud Admin chooses an
* account's file, so without this it could name any file the Cacti user
* can read and have it sent to the provider. An empty or root directory
* allows nothing. Only directories are resolved; the file itself is not
* touched, and SecureFile refuses a link at the last component.
*/
public static function within(string $path, string $directory): bool {
if (!SecureFile::pathAcceptable($path) || !SecureFile::pathAcceptable($directory)) {
return false;
}

$root = realpath($directory);
$parent = realpath(dirname($path));

return $root !== false && $root !== '/' && $parent !== false
&& str_starts_with($parent . '/', rtrim($root, '/') . '/');
}

/**
* @throws CredentialError
*/
public static function read(string $path): Secret {
public static function check(string $path, string $directory): void {
self::guard($path, $directory);
SecureFile::check($path, self::MAX_BYTES);
}

/**
* @throws CredentialError
*/
public static function read(string $path, string $directory): Secret {
self::guard($path, $directory);

$content = trim(SecureFile::read($path, self::MAX_BYTES));

if ($content === '') {
Expand All @@ -41,4 +71,16 @@ public static function read(string $path): Secret {

return new Secret($content);
}

/**
* Refuse a path outside the directory before opening it, so the reason
* says nothing about files there.
*
* @throws CredentialError
*/
private static function guard(string $path, string $directory): void {
if (!self::within($path, $directory)) {
throw CredentialError::because('the file is not in the credential directory set in the Cloud settings');
}
}
}
17 changes: 16 additions & 1 deletion lib/CredentialStore.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ final class CredentialStore {
public function __construct(
private readonly SecretRepository $secrets,
private readonly string $keyFile,
private readonly string $credentialDir,
) {
}

Expand All @@ -38,7 +39,7 @@ public function __construct(
*/
public function credentialFor(Account $account): Secret {
return match ($account->credentialSource) {
CredentialSource::File => CredentialFile::read($account->credentialFile),
CredentialSource::File => $this->fromFile($account->credentialFile),
CredentialSource::Vault => $this->fromVault($account->id),
CredentialSource::Instance => throw CredentialError::because('instance identity is not available for this provider'),
};
Expand Down Expand Up @@ -72,6 +73,20 @@ public function forget(int $accountId): void {
/**
* @throws CredentialError
*/
/**
* @throws CredentialError
*/
private function fromFile(string $path): Secret {
// The vault key may share the directory; it is never a credential.
$file = realpath($path);

if ($file !== false && $file === realpath($this->keyFile)) {
throw CredentialError::because('the file is the vault key file');
}

return CredentialFile::read($path, $this->credentialDir);
}

private function fromVault(int $accountId): Secret {
$entry = $this->secrets->load($accountId, SecretRepository::CREDENTIAL);

Expand Down
9 changes: 5 additions & 4 deletions lib/HealthWarnings.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@
final class HealthWarnings {
/**
* @param \Closure(string): void $keyCheck throws CredentialError for an unusable key file
* @param \Closure(string): void $fileCheck throws CredentialError for an unusable credential file
* @param \Closure(string, string): void $fileCheck throws CredentialError for an unusable credential
* file, given its path and the credential directory
*/
public function __construct(
private readonly \Closure $keyCheck,
Expand All @@ -44,8 +45,8 @@ public static function production(): self {
static function (string $path): void {
VaultKey::fromFile($path);
},
static function (string $path): void {
SecureFile::check($path, CredentialFile::MAX_BYTES);
static function (string $path, string $directory): void {
CredentialFile::check($path, $directory);
},
);
}
Expand Down Expand Up @@ -78,7 +79,7 @@ public function for(Settings $settings, array $accounts, int $pollerInterval): a

if ($account->credentialSource === CredentialSource::File) {
try {
($this->fileCheck)($account->credentialFile);
($this->fileCheck)($account->credentialFile, $settings->credentialDir);
} catch (CredentialError $e) {
$warnings[] = [
'message' => __('%s: the credential file cannot be used: %s.', $account->name, $e->getMessage(), 'cloud'),
Expand Down
14 changes: 14 additions & 0 deletions lib/Settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
final readonly class Settings {
public const NAMES = [
'cloud_vault_key_file',
'cloud_credential_dir',
'cloud_collector_budget',
'cloud_uninstall_keep_tables',
];
Expand All @@ -39,6 +40,7 @@ public function __construct(
public string $vaultKeyFile,
public int $collectorBudget,
public bool $keepTablesOnUninstall,
public string $credentialDir = '',
) {
}

Expand All @@ -59,6 +61,7 @@ public static function fromRow(array $row): self {
$row,
'cloud_uninstall_keep_tables'
) : true,
credentialDir: Row::string($row, 'cloud_credential_dir'),
);
}

Expand Down Expand Up @@ -88,6 +91,17 @@ public static function form(): array {
'max_length' => '255',
'size' => '60',
],
'cloud_credential_dir' => [
'friendly_name' => __('Credential File Directory', 'cloud'),
'description' => __(
'Absolute path to the directory that holds credential files. An account can read its credential from a file only inside it, never the vault key file. Empty, the default, refuses credential files. Cloud Admin chooses the file, so keep only cloud credentials here.',
'cloud'
),
'method' => 'textbox',
'default' => '',
'max_length' => '255',
'size' => '60',
],
'cloud_header_collector' => [
'friendly_name' => __('Collector', 'cloud'),
'method' => 'spacer',
Expand Down
8 changes: 8 additions & 0 deletions locales/po/cacti.pot
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,14 @@ msgstr ""
msgid "Absolute path to the 32-byte key that encrypts stored credentials. Create it yourself, outside the web root, readable only by the web server and poller user, in a directory that only root and that user can write (the same applies to credential files); the plugin never creates or writes it. Back it up with the database: without it, stored credentials must be entered again."
msgstr ""

#: lib/Settings.php
msgid "Credential File Directory"
msgstr ""

#: lib/Settings.php
msgid "Absolute path to the directory that holds credential files. An account can read its credential from a file only inside it, never the vault key file. Empty, the default, refuses credential files. Cloud Admin chooses the file, so keep only cloud credentials here."
msgstr ""

#: lib/Settings.php
msgid "Collector"
msgstr ""
Expand Down
3 changes: 2 additions & 1 deletion setup.php
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,8 @@ function cloud_require_post(string $page, array $actions): void {
function cloud_credentials(): \Somethingwithproof\Cloud\CredentialStore {
return new \Somethingwithproof\Cloud\CredentialStore(
new \Somethingwithproof\Cloud\SecretRepository(false, new \Somethingwithproof\Cloud\SystemClock()),
cloud_settings()->vaultKeyFile
cloud_settings()->vaultKeyFile,
cloud_settings()->credentialDir
);
}

Expand Down
6 changes: 3 additions & 3 deletions tests/Unit/DriverContractTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ function cloud_verify_with(?int $status, string $source = 'file'): VerifyStatus
$clock = new FixedClock(1_800_000_000);
$verifier = new Verifier(
$drivers,
new CredentialStore(new SecretRepository(false, $clock), $dir . '/missing.key'),
new CredentialStore(new SecretRepository(false, $clock), $dir . '/missing.key', $dir),
new AccountRepository(false, $clock)
);
$result = $verifier->verify($account, 1);
Expand Down Expand Up @@ -175,7 +175,7 @@ function cloud_verify_with(?int $status, string $source = 'file'): VerifyStatus
$clock = new FixedClock(1);
$verifier = new Verifier(
new Drivers(cloud_canned(200)),
new CredentialStore(new SecretRepository(false, $clock), '/nonexistent'),
new CredentialStore(new SecretRepository(false, $clock), '/nonexistent', ''),
new AccountRepository(false, $clock)
);

Expand All @@ -193,7 +193,7 @@ function cloud_verify_with(?int $status, string $source = 'file'): VerifyStatus
$clock = new FixedClock(1);
$verifier = new Verifier(
$drivers,
new CredentialStore(new SecretRepository(false, $clock), '/nonexistent'),
new CredentialStore(new SecretRepository(false, $clock), '/nonexistent', ''),
new AccountRepository(false, $clock)
);

Expand Down
5 changes: 4 additions & 1 deletion tests/Unit/HealthWarningsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,10 @@ function cloud_warn_account(array $row = []): Account {
}

function cloud_warnings(string $key, array $accounts, int $poller = 300): array {
return HealthWarnings::production()->for(Settings::fromRow(['cloud_vault_key_file' => $key]), $accounts, $poller);
// Credential files live beside the key in these fixtures.
$settings = Settings::fromRow(['cloud_vault_key_file' => $key, 'cloud_credential_dir' => dirname($key)]);

return HealthWarnings::production()->for($settings, $accounts, $poller);
}

it('has no warnings for a usable key, safe files, and matching intervals', function () {
Expand Down
76 changes: 66 additions & 10 deletions tests/Unit/VaultTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,14 @@
* more details.
*/

use Somethingwithproof\Cloud\Account;
use Somethingwithproof\Cloud\CredentialError;
use Somethingwithproof\Cloud\CredentialFile;
use Somethingwithproof\Cloud\CredentialStore;
use Somethingwithproof\Cloud\FixedClock;
use Somethingwithproof\Cloud\Redactor;
use Somethingwithproof\Cloud\Secret;
use Somethingwithproof\Cloud\SecretRepository;
use Somethingwithproof\Cloud\Vault;
use Somethingwithproof\Cloud\VaultEntry;
use Somethingwithproof\Cloud\VaultKey;
Expand Down Expand Up @@ -149,18 +153,70 @@ function cloud_refusal(callable $read): string {
it('refuses credential files that fail a check', function () {
$dir = $this->dir;
symlink(cloud_file($dir, 'real', CLOUD_TEST_SECRET), $dir . '/link');

expect(CredentialFile::read(cloud_file($dir, 'ok', CLOUD_TEST_SECRET . "\n"))->reveal())->toBe(CLOUD_TEST_SECRET)
->and(cloud_refusal(fn () => CredentialFile::read('token')))->toContain('absolute path')
->and(cloud_refusal(fn () => CredentialFile::read($dir . '/link')))->toContain('symbolic link')
->and(cloud_refusal(fn () => CredentialFile::read($dir)))->toContain('not a regular file')
->and(
cloud_refusal(fn () => CredentialFile::read(cloud_file($dir, 'open', CLOUD_TEST_SECRET, 0644)))
)->toContain('other users')
->and(cloud_refusal(fn () => CredentialFile::read(cloud_file($dir, 'empty', "\n"))))->toContain('empty')
mkdir($dir . '/sub');
$read = fn (string $path): Secret => CredentialFile::read($path, $dir);

expect($read(cloud_file($dir, 'ok', CLOUD_TEST_SECRET . "\n"))->reveal())->toBe(CLOUD_TEST_SECRET)
->and(cloud_refusal(fn () => $read('token')))->toContain('credential directory')
->and(cloud_refusal(fn () => $read($dir . '/link')))->toContain('symbolic link')
->and(cloud_refusal(fn () => $read($dir . '/sub')))->toContain('not a regular file')
->and(cloud_refusal(fn () => $read(cloud_file($dir, 'open', CLOUD_TEST_SECRET, 0644))))->toContain('other users')
->and(cloud_refusal(fn () => $read(cloud_file($dir, 'empty', "\n"))))->toContain('empty')
->and(
cloud_refusal(fn () => CredentialFile::read(cloud_file($dir, 'big', str_repeat('a', CredentialFile::MAX_BYTES + 1))))
cloud_refusal(fn () => $read(cloud_file($dir, 'big', str_repeat('a', CredentialFile::MAX_BYTES + 1))))
)->toContain('larger than allowed');

rmdir($dir . '/sub');
});

it('reads credential files only inside the directory a full administrator set', function () {
$dir = $this->dir;
$token = cloud_file($dir, 'token', CLOUD_TEST_SECRET);
mkdir($dir . '/nested');
$deep = cloud_file($dir . '/nested', 'token', CLOUD_TEST_SECRET);
mkdir($dir . '/other');
$other = cloud_file($dir . '/other', 'token', CLOUD_TEST_SECRET);
symlink($dir . '/other', $dir . '/nested/escape');

$reason = 'the file is not in the credential directory set in the Cloud settings';

expect(CredentialFile::read($token, $dir)->reveal())->toBe(CLOUD_TEST_SECRET)
->and(CredentialFile::read($deep, $dir)->reveal())->toBe(CLOUD_TEST_SECRET)
->and(CredentialFile::read($deep, $dir . '/nested/')->reveal())->toBe(CLOUD_TEST_SECRET)
// No directory set, the root, a sibling, or a link out of it: refused.
->and(cloud_refusal(fn () => CredentialFile::read($token, '')))->toBe($reason)
->and(cloud_refusal(fn () => CredentialFile::read($token, '/')))->toBe($reason)
->and(cloud_refusal(fn () => CredentialFile::read($other, $dir . '/nested')))->toBe($reason)
->and(cloud_refusal(fn () => CredentialFile::read($dir . '/nested/escape/token', $dir . '/nested')))->toBe($reason)
->and(cloud_refusal(fn () => CredentialFile::read($dir . '/nestedx/token', $dir . '/nested')))->toBe($reason)
// Outside, a missing file and an unsafe one are refused alike.
->and(cloud_refusal(fn () => CredentialFile::read($dir . '/other/none', $dir . '/nested')))->toBe($reason)
->and(cloud_refusal(fn () => CredentialFile::check($other, $dir . '/nested')))->toBe($reason);

foreach (['nested/escape', 'nested/token', 'other/token'] as $file) {
unlink($dir . '/' . $file);
}

rmdir($dir . '/nested');
rmdir($dir . '/other');
});

it('never uses the vault key file as a credential', function () {
$key = cloud_file($this->dir, 'vault.key', bin2hex(random_bytes(32)));
$store = new CredentialStore(new SecretRepository(false, new FixedClock(1)), $key, $this->dir);
$row = [
'id' => 4,
'provider' => 'digitalocean',
'name' => 'Ops',
'credential_source' => 'file',
'credential_file' => $key,
'admin_state' => 'enabled',
];

expect(cloud_refusal(fn () => $store->credentialFor(Account::fromRow($row))))->toBe('the file is the vault key file')
->and($store->credentialFor(
Account::fromRow(['credential_file' => cloud_file($this->dir, 'tok', CLOUD_TEST_SECRET)] + $row)
)->reveal())->toBe(CLOUD_TEST_SECRET);
});

it('never puts secret material in a refusal message', function () {
Expand Down
2 changes: 1 addition & 1 deletion tests/bin/collector-flow.php
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ function flow_collector($clock, $holder) {

return new Collector(
new \Somethingwithproof\Cloud\AccountRepository(false, $clock), $drivers,
new CredentialStore(new SecretRepository(false, $clock), '/nonexistent'),
new CredentialStore(new SecretRepository(false, $clock), '/nonexistent', $GLOBALS['flow_dir']),
new LeaseRepository(false, $clock), new ResourceRepository(false, $clock), new SeriesRepository(false),
new ObservationRepository(false), new HealthRepository(false), new Redactor(), $clock, $holder
);
Expand Down
2 changes: 1 addition & 1 deletion tests/bin/collector-restart.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ function restart_collector(FixedClock $clock, string $holder): Collector {

return new Collector(
new \Somethingwithproof\Cloud\AccountRepository(false, $clock), $drivers,
new CredentialStore(new SecretRepository(false, $clock), '/nonexistent'),
new CredentialStore(new SecretRepository(false, $clock), '/nonexistent', dirname($GLOBALS['restart_token'])),
new LeaseRepository(false, $clock), new ResourceRepository(false, $clock), new SeriesRepository(false),
new ObservationRepository(false), new HealthRepository(false), new Redactor(), $clock, $holder
);
Expand Down
2 changes: 1 addition & 1 deletion tests/bin/discover.php
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ public function estimate(array $requests, int $intervalSeconds): UsageEstimate {
$result = (new Collector(
new \Somethingwithproof\Cloud\AccountRepository(false, $discover_clock),
$discover_drivers,
new CredentialStore(new \Somethingwithproof\Cloud\SecretRepository(false, $discover_clock), '/nonexistent'),
new CredentialStore(new \Somethingwithproof\Cloud\SecretRepository(false, $discover_clock), '/nonexistent', $discover_dir),
new \Somethingwithproof\Cloud\LeaseRepository(false, $discover_clock),
new \Somethingwithproof\Cloud\ResourceRepository(false, $discover_clock),
new \Somethingwithproof\Cloud\SeriesRepository(false),
Expand Down
3 changes: 2 additions & 1 deletion tests/bin/lifecycle.php
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,8 @@
$accounts = new \Somethingwithproof\Cloud\AccountRepository(false, $clock);
$store = new \Somethingwithproof\Cloud\CredentialStore(
new \Somethingwithproof\Cloud\SecretRepository(false, $clock),
$keyFile
$keyFile,
''
);
$input = array(
'provider' => 'digitalocean',
Expand Down
Loading
Loading