diff --git a/source/Octopus.Manager.Tentacle/TentacleConfiguration/InstanceConfigurationLoader.cs b/source/Octopus.Manager.Tentacle/TentacleConfiguration/InstanceConfigurationLoader.cs
index 29c1b0e8e..fb6e13adb 100644
--- a/source/Octopus.Manager.Tentacle/TentacleConfiguration/InstanceConfigurationLoader.cs
+++ b/source/Octopus.Manager.Tentacle/TentacleConfiguration/InstanceConfigurationLoader.cs
@@ -3,6 +3,7 @@
using Octopus.Tentacle.Core.Diagnostics;
using Octopus.Tentacle;
using Octopus.Tentacle.Configuration;
+using Octopus.Tentacle.Configuration.Crypto;
using Octopus.Tentacle.Configuration.Instances;
using Octopus.Tentacle.Diagnostics;
using Octopus.Tentacle.Util;
@@ -52,13 +53,15 @@ public InstanceConfigurationLoader(
public InstanceConfiguration LoadConfiguration(ApplicationInstanceRecord applicationInstanceRecord)
{
- var keyStore = new XmlFileKeyValueStore(fileSystem, applicationInstanceRecord.ConfigurationFilePath);
+ var encryptor = MachineKeyEncryptor.ForKeyFile(fileSystem, ConfigurationEncryptionKey.KeyFilePathFor(applicationInstanceRecord.InstanceName));
+ var keyStore = new XmlFileKeyValueStore(fileSystem, applicationInstanceRecord.ConfigurationFilePath, encryptor);
var selector = new SimpleApplicationInstanceSelectorForTentacleManager(
instanceStrategies,
fileSystem,
systemLog,
- applicationInstanceRecord.ConfigurationFilePath);
+ applicationInstanceRecord.ConfigurationFilePath,
+ encryptor);
var homeConfig = new HomeConfiguration(selector);
var loggingConfig = new LoggingConfiguration(homeConfig);
@@ -80,18 +83,21 @@ class SimpleApplicationInstanceSelectorForTentacleManager : IApplicationInstance
readonly ISystemLog log;
readonly string configFilePath;
+ readonly IMachineKeyEncryptor encryptor;
readonly bool canLoadCurrentInstance;
public SimpleApplicationInstanceSelectorForTentacleManager(
IApplicationConfigurationContributor[] instanceStrategies,
IOctopusFileSystem fileSystem,
ISystemLog log,
- string configFilePath)
+ string configFilePath,
+ IMachineKeyEncryptor encryptor)
{
this.instanceStrategies = instanceStrategies;
this.fileSystem = fileSystem;
this.log = log;
this.configFilePath = configFilePath;
+ this.encryptor = encryptor;
try
{
@@ -120,7 +126,7 @@ ApplicationInstanceConfiguration LoadInstance()
EnsureConfigurationExists(configurationPath);
log.Verbose($"Loading configuration from {configurationPath}");
- var writable = new XmlFileKeyValueStore(fileSystem, configurationPath);
+ var writable = new XmlFileKeyValueStore(fileSystem, configurationPath, encryptor);
return (ContributeAdditionalConfiguration(writable), writable);
}
diff --git a/source/Octopus.Tentacle.Core/Util/FileSystem/IOctopusFileSystem.cs b/source/Octopus.Tentacle.Core/Util/FileSystem/IOctopusFileSystem.cs
index 20a63e78c..f75710d0a 100644
--- a/source/Octopus.Tentacle.Core/Util/FileSystem/IOctopusFileSystem.cs
+++ b/source/Octopus.Tentacle.Core/Util/FileSystem/IOctopusFileSystem.cs
@@ -37,7 +37,12 @@ public interface IOctopusFileSystem
void WriteAllBytes(string filePath, byte[] data);
void WriteAllText(string filePath, string contents);
- // Returns false, leaving the existing file untouched, if another process created it first.
+ ///
+ /// Creates a file at filePath with contents IF it doesn't exist.
+ /// The operation is as atomic as it can be for the FileSystem.
+ /// The resulting file has permissions 0600 for linux.
+ ///
+ /// True if this call created the file, false if it already existed, in which case the existing file is left untouched.
bool AtomicCreateFileWithUserReadWriteAccessOnly(string filePath, byte[] contents);
string ReadAllText(string scriptFile);
diff --git a/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs b/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs
index a4fd34f6e..edeca02b6 100644
--- a/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs
+++ b/source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs
@@ -250,53 +250,13 @@ public void WriteAllText(string path, string contents)
File.WriteAllText(path, contents);
}
-#if NETFRAMEWORK
- public bool AtomicCreateFileWithUserReadWriteAccessOnly(string path, byte[] contents)
- {
- var temporaryPath = TemporaryPathBeside(path);
- try
- {
- File.WriteAllBytes(temporaryPath, contents);
- try
- {
- // MoveFile never replaces an existing file.
- File.Move(temporaryPath, path);
- return true;
- }
- catch (IOException) when (File.Exists(path))
- {
- return false;
- }
- }
- finally
- {
- DeleteIfExists(temporaryPath);
- }
- }
-#else
public bool AtomicCreateFileWithUserReadWriteAccessOnly(string path, byte[] contents)
{
var temporaryPath = TemporaryPathBeside(path);
try
{
CreateFileWithUserReadWriteAccessOnly(temporaryPath, contents);
-
- // File.Move(overwrite: false) checks then renames, so on Unix two racing processes could each keep their own file.
- if (!OperatingSystem.IsWindows() && UnixFile.TryLinkWithoutReplacing(temporaryPath, path))
- {
- return true;
- }
- if (File.Exists(path))
- {
- return false;
- }
-
- File.Move(temporaryPath, path, overwrite: false);
- return true;
- }
- catch (IOException) when (File.Exists(path))
- {
- return false;
+ return PublishWithoutReplacing(temporaryPath, path);
}
finally
{
@@ -306,6 +266,9 @@ public bool AtomicCreateFileWithUserReadWriteAccessOnly(string path, byte[] cont
static void CreateFileWithUserReadWriteAccessOnly(string path, byte[] contents)
{
+#if NETFRAMEWORK
+ using var stream = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None);
+#else
var options = new FileStreamOptions { Mode = FileMode.CreateNew, Access = FileAccess.Write, Share = FileShare.None };
if (!OperatingSystem.IsWindows())
{
@@ -313,10 +276,31 @@ static void CreateFileWithUserReadWriteAccessOnly(string path, byte[] contents)
}
using var stream = new FileStream(path, options);
+#endif
stream.Write(contents, 0, contents.Length);
stream.Flush(flushToDisk: true);
}
+
+ static bool PublishWithoutReplacing(string temporaryPath, string path)
+ {
+#if !NETFRAMEWORK
+ if (!PlatformDetection.IsRunningOnWindows)
+ {
+ // Unlike File.Move, link(2) is atomic about not replacing: two racing processes cannot each keep their own file.
+ return UnixFile.TryLinkWithoutReplacing(temporaryPath, path);
+ }
#endif
+ try
+ {
+ // MoveFile never replaces an existing file.
+ File.Move(temporaryPath, path);
+ return true;
+ }
+ catch (IOException) when (File.Exists(path))
+ {
+ return false;
+ }
+ }
static void DeleteIfExists(string path)
{
diff --git a/source/Octopus.Tentacle.Core/Util/UnixFile.cs b/source/Octopus.Tentacle.Core/Util/UnixFile.cs
index 040ea8d90..6b6227f08 100644
--- a/source/Octopus.Tentacle.Core/Util/UnixFile.cs
+++ b/source/Octopus.Tentacle.Core/Util/UnixFile.cs
@@ -1,16 +1,93 @@
#if !NETFRAMEWORK
+using System.IO;
using System.Runtime.InteropServices;
+using Microsoft.Win32.SafeHandles;
namespace Octopus.Tentacle.Core.Util
{
- static class UnixFile
+ public static class UnixFile
{
+ const uint UnchangedGroup = uint.MaxValue;
+ const int FileExistsError = 17;
+
// Unlike rename(2), link(2) never replaces an existing file.
public static bool TryLinkWithoutReplacing(string existingPath, string newPath)
- => link(existingPath, newPath) == 0;
+ {
+ if (link(existingPath, newPath) == 0)
+ {
+ return true;
+ }
+
+ return Marshal.GetLastPInvokeError() == FileExistsError
+ ? false
+ : throw new IOException($"Unable to create `{newPath}`: {Marshal.GetLastPInvokeErrorMessage()}");
+ }
+
+ public static uint OwnerOf(string path)
+ {
+ return SystemNative_Stat(path, out var status) == 0
+ ? status.Uid
+ : throw new IOException($"Unable to find the owner of `{path}`: {Marshal.GetLastPInvokeErrorMessage()}");
+ }
+
+ public static void SetOwnerIfRunningAsRoot(uint owner, string path)
+ {
+ if (geteuid() != 0 || OwnerOf(path) == owner)
+ {
+ return;
+ }
+
+ if (lchown(path, owner, UnchangedGroup) != 0)
+ {
+ throw new IOException($"Unable to change the owner of `{path}`: {Marshal.GetLastPInvokeErrorMessage()}");
+ }
+ }
+
+ public static void GiveTo(SafeFileHandle file, uint owner)
+ {
+ if (fchown(file, owner, UnchangedGroup) != 0)
+ {
+ throw new IOException(Marshal.GetLastPInvokeErrorMessage());
+ }
+ }
[DllImport("libc", SetLastError = true)]
static extern int link(string oldpath, string newpath);
+
+ [DllImport("libc")]
+ static extern uint geteuid();
+
+ [DllImport("libc", SetLastError = true)]
+ static extern int lchown(string path, uint owner, uint group);
+
+ [DllImport("libc", SetLastError = true)]
+ static extern int fchown(SafeFileHandle fd, uint owner, uint group);
+
+ // The .NET runtime has no public API for a file's owner; its own stat shim has one struct layout on every libc and architecture.
+ [DllImport("libSystem.Native", SetLastError = true)]
+ static extern int SystemNative_Stat(string path, out FileStatus output);
+
+ [StructLayout(LayoutKind.Sequential)]
+ struct FileStatus
+ {
+ public int Flags;
+ public int Mode;
+ public uint Uid;
+ public uint Gid;
+ public long Size;
+ public long ATime;
+ public long ATimeNsec;
+ public long MTime;
+ public long MTimeNsec;
+ public long CTime;
+ public long CTimeNsec;
+ public long BirthTime;
+ public long BirthTimeNsec;
+ public long Dev;
+ public long RDev;
+ public long Ino;
+ public uint UserFlags;
+ }
}
}
#endif
diff --git a/source/Octopus.Tentacle.Tests.Integration/Support/SharedTentacleCryptoState.cs b/source/Octopus.Tentacle.Tests.Integration/Support/SharedTentacleCryptoState.cs
index 502d3dcc2..0a52bdb51 100644
--- a/source/Octopus.Tentacle.Tests.Integration/Support/SharedTentacleCryptoState.cs
+++ b/source/Octopus.Tentacle.Tests.Integration/Support/SharedTentacleCryptoState.cs
@@ -1,6 +1,9 @@
using System;
+using System.IO;
using System.Linq;
+using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
+using System.Text;
using Octopus.Tentacle.CommonTestUtils;
using Octopus.Tentacle.Configuration;
using Octopus.Tentacle.Configuration.Crypto;
@@ -74,10 +77,25 @@ static void CreateTheFallbackKeyEarlierVersionsShare(SystemLog log)
}
catch (InvalidOperationException)
{
- new LinuxGeneratedMachineKey(log, fileSystem, LinuxGeneratedMachineKey.LegacyKeyFilePathForThisHost).CreateIfMissing();
+ CreateLegacyMachineKeyIfMissing(fileSystem, LinuxGeneratedMachineKey.LegacyKeyFilePathForThisHost);
}
}
+ static void CreateLegacyMachineKeyIfMissing(OctopusPhysicalFileSystem fileSystem, string path)
+ {
+ if (fileSystem.FileExists(path))
+ {
+ return;
+ }
+
+ using var aes = Aes.Create();
+ aes.GenerateIV();
+ aes.GenerateKey();
+ var contents = Convert.ToBase64String(aes.Key) + "." + Convert.ToBase64String(aes.IV);
+ fileSystem.EnsureDirectoryExists(Path.GetDirectoryName(path)!);
+ fileSystem.AtomicCreateFileWithUserReadWriteAccessOnly(path, Encoding.ASCII.GetBytes(contents));
+ }
+
// A Tentacle only reuses the stored certificate when it comes back with its private key.
// Otherwise it adds it to the store again, which is the concurrent write this avoids.
static void VerifyTheStoreHoldsTheCertificateWithItsPrivateKey()
diff --git a/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandFixture.cs
index 2b94a7b9c..c1356222d 100644
--- a/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandFixture.cs
+++ b/source/Octopus.Tentacle.Tests/Commands/CreateInstanceCommandFixture.cs
@@ -27,7 +27,7 @@ public override void SetUp()
[Test]
public void ANamedInstanceFailsWhenItsKeyCannotBeCreated()
{
- configurationUpgrade.When(u => u.CreateKey()).Do(_ => throw new IOException("Permission denied"));
+ configurationUpgrade.When(u => u.PrepareKey()).Do(_ => throw new IOException("Permission denied"));
Action start = () => Start("--instance=Tentacle", "--config=/etc/octopus/tentacle.config");
diff --git a/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs b/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs
index bd43cb327..0dbe2a71b 100644
--- a/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs
+++ b/source/Octopus.Tentacle.Tests/Commands/RunAgentCommandFixture.cs
@@ -77,7 +77,7 @@ public void WhenCommandIsStartedThenTheConfigurationIsUpgradedBeforeHalibutStart
// Assert
Received.InOrder(() =>
{
- configurationUpgrade.Run();
+ configurationUpgrade.TryUpgrade();
halibut.Start();
});
}
diff --git a/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceSelectorFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceSelectorFixture.cs
index d297785c5..492df010a 100644
--- a/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceSelectorFixture.cs
+++ b/source/Octopus.Tentacle.Tests/Configuration/ApplicationInstanceSelectorFixture.cs
@@ -108,7 +108,7 @@ public void GivenARegisteredInstanceUsesTheConfiguration_WhenRequestingConfigura
new ApplicationInstanceRecord("Registered", filePath)
});
- mock.Current.KeyFilePath.Should().Be(LinuxGeneratedMachineKey.KeyFilePathFor("Registered"));
+ mock.Current.KeyFilePath.Should().Be(ConfigurationEncryptionKey.KeyFilePathFor("Registered"));
}
[Test]
diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityFixture.cs
index 8eb4b7406..cd6a9a4bc 100644
--- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityFixture.cs
+++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LegacyCiphertextCompatibilityFixture.cs
@@ -73,7 +73,7 @@ IMachineKeyEncryptor CreateEncryptorAsComposedInProduction(bool machineIdPresent
fileSystem.FileExists(LinuxMachineIdKey.FileName).Returns(machineIdPresent);
fileSystem.ReadAllLines(LinuxMachineIdKey.FileName).Returns(new[] { MachineId });
- return MachineKeyEncryptor.CreateLinuxEncryptor(Substitute.For(), fileSystem, LinuxGeneratedMachineKey.KeyFilePathFor("Tentacle"));
+ return MachineKeyEncryptor.CreateLinuxEncryptor(Substitute.For(), fileSystem, ConfigurationEncryptionKey.KeyFilePathFor("Tentacle"));
}
[TestCaseSource(nameof(WrittenWithTheMachineIdKey))]
diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs
index 2bfdd0dc1..b5f4d9b14 100644
--- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs
+++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxConfigurationFileSecurityFixture.cs
@@ -31,7 +31,7 @@ public class LinuxConfigurationFileSecurityFixture
public void SetUp()
{
directory = Path.Combine(Path.GetTempPath(), "octopus-config-encryption-key-" + Guid.NewGuid());
- keyFilePath = Path.Combine(directory, LinuxGeneratedMachineKey.KeyFileName);
+ keyFilePath = Path.Combine(directory, ConfigurationEncryptionKey.KeyFileName);
log = Substitute.For();
fileSystem = new OctopusPhysicalFileSystem(log);
}
@@ -49,16 +49,16 @@ public void TearDown()
public void WhenTheKeyIsCreatedThenOnlyItsOwnerCanReadIt()
{
// Arrange
- var keySource = new LinuxGeneratedMachineKey(log, fileSystem, keyFilePath);
+ var keySource = new ConfigurationEncryptionKey(log, fileSystem, keyFilePath);
// Act
keySource.CreateIfMissing();
- var (key, iv) = keySource.Load();
+ var key = keySource.Load();
// Assert
File.Exists(keyFilePath).Should().BeTrue("the directory is created on demand, as it always was");
File.GetUnixFileMode(keyFilePath).Should().Be(OwnerReadWrite);
- File.ReadAllText(keyFilePath).Should().Be(Convert.ToBase64String(key) + "." + Convert.ToBase64String(iv));
+ File.ReadAllText(keyFilePath).Should().Be(Convert.ToBase64String(key));
Directory.GetFiles(directory).Should().ContainSingle("the temporary file the key is written to first is not left behind");
}
@@ -72,9 +72,9 @@ public async Task WhenManyProcessesCreateTheKeyAtOnceThenTheyAllGetTheSameKey()
.Select(_ => Task.Run(() =>
{
start.Wait();
- var keySource = new LinuxGeneratedMachineKey(log, new OctopusPhysicalFileSystem(log), keyFilePath);
+ var keySource = new ConfigurationEncryptionKey(log, new OctopusPhysicalFileSystem(log), keyFilePath);
keySource.CreateIfMissing();
- return keySource.Load().Key;
+ return keySource.Load();
}))
.ToArray();
@@ -83,7 +83,7 @@ public async Task WhenManyProcessesCreateTheKeyAtOnceThenTheyAllGetTheSameKey()
var keys = await Task.WhenAll(loads);
// Assert
- var onDisk = Convert.FromBase64String(File.ReadAllText(keyFilePath).Split('.')[0]);
+ var onDisk = Convert.FromBase64String(File.ReadAllText(keyFilePath));
keys.Should().AllSatisfy(k => k.Should().Equal(onDisk));
Directory.GetFiles(directory).Should().ContainSingle("no racer's temporary file is left behind");
}
diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxGeneratedMachineKeyFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxGeneratedMachineKeyFixture.cs
index 4bf67d003..3be7b2b4b 100644
--- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxGeneratedMachineKeyFixture.cs
+++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxGeneratedMachineKeyFixture.cs
@@ -53,7 +53,7 @@ public void GivenMachineIdFileIsValidLength_ThenReturnsKeys()
[Test]
public void KeyFileIsKeptPerInstanceOutsideTheConfigurationDirectory()
{
- LinuxGeneratedMachineKey.KeyFilePathFor("Tentacle").Should().Be("/var/octopus/tentacle/keys/Tentacle/config-encryption.key");
+ ConfigurationEncryptionKey.KeyFilePathFor("Tentacle").Should().Be("/var/octopus/tentacle/keys/Tentacle/config-encryption.key");
}
[TestCase("")]
@@ -62,7 +62,7 @@ public void KeyFileIsKeptPerInstanceOutsideTheConfigurationDirectory()
[TestCase("a\\b")]
public void InstanceNamesThatAreNotASingleDirectoryNameAreRejected(string instanceName)
{
- Assert.Throws(() => LinuxGeneratedMachineKey.KeyFilePathFor(instanceName));
+ Assert.Throws(() => ConfigurationEncryptionKey.KeyFilePathFor(instanceName));
}
}
}
diff --git a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorFixture.cs
index 4516297a7..5aee06c92 100644
--- a/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorFixture.cs
+++ b/source/Octopus.Tentacle.Tests/Configuration/Crypto/LinuxMachineKeyEncryptorFixture.cs
@@ -14,7 +14,7 @@ namespace Octopus.Tentacle.Tests.Configuration.Crypto
public class LinuxMachineKeyEncryptorFixture
{
readonly ISystemLog systemLog = Substitute.For();
- readonly InMemoryCryptoKeyNixSource generatedKey = new();
+ readonly ConfigurationEncryptionKey generatedKey = InMemoryConfigurationEncryptionKey.Create();
LinuxMachineKeyEncryptor CreateEncryptor(params ICryptoKeyNixSource[] legacyKeySources)
=> new(systemLog, generatedKey, legacyKeySources);
@@ -38,9 +38,9 @@ public void WhenAValueIsEncryptedThenItIsVersionedAndDecrypts()
public void WhenACurrentValueWasEncryptedWithAnotherKeyThenALegacyKeyIsNotTried()
{
// Arrange
- var otherKey = new InMemoryCryptoKeyNixSource();
+ var otherKey = InMemoryConfigurationEncryptionKey.Create();
var encryptedWithOtherKey = new LinuxMachineKeyEncryptor(systemLog, otherKey, Array.Empty()).Encrypt("FooBar");
- var encryptor = CreateEncryptor(otherKey);
+ var encryptor = CreateEncryptor(new InMemoryCryptoKeyNixSource());
// Act
Action decrypt = () => encryptor.Decrypt(encryptedWithOtherKey);
diff --git a/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs
index 5173f7fe1..249dcb482 100644
--- a/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs
+++ b/source/Octopus.Tentacle.Tests/Configuration/TentacleConfigurationUpgradeFixture.cs
@@ -52,13 +52,13 @@ public void TearDown()
public void WhenTheKeyIsMissingThenItIsCreatedAndLegacyValuesAreReEncrypted()
{
// Arrange
- var keyFilePath = Path.Combine(directory, "keys", "Tentacle", LinuxGeneratedMachineKey.KeyFileName);
+ var keyFilePath = Path.Combine(directory, "keys", "Tentacle", ConfigurationEncryptionKey.KeyFileName);
var store = CreateStore(keyFilePath);
store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey);
RawCertificate().Should().NotStartWith(LinuxMachineKeyEncryptor.ProtectedValuePrefix, "without a key, values are written the way earlier versions wrote them");
// Act
- CreateUpgrade(store, keyFilePath).Run();
+ CreateUpgrade(store, keyFilePath).Upgrade();
// Assert
File.Exists(keyFilePath).Should().BeTrue();
@@ -71,7 +71,7 @@ public void WhenTheKeyIsMissingThenItIsCreatedAndLegacyValuesAreReEncrypted()
public void WhenOnlyTheKeyIsPreparedThenItIsCreatedAndValuesStayLegacy()
{
// Arrange
- var keyFilePath = Path.Combine(directory, "keys", "Tentacle", LinuxGeneratedMachineKey.KeyFileName);
+ var keyFilePath = Path.Combine(directory, "keys", "Tentacle", ConfigurationEncryptionKey.KeyFileName);
var store = CreateStore(keyFilePath);
store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey);
var legacyValue = RawCertificate();
@@ -86,37 +86,33 @@ public void WhenOnlyTheKeyIsPreparedThenItIsCreatedAndValuesStayLegacy()
}
[Test]
- public void WhenTheKeyCannotBeCreatedThenTentacleKeepsWorkingOnTheLegacyKey()
+ public void WhenTheKeyCannotBeCreatedThenRunFailsAndValuesStayLegacy()
{
// Arrange
- var keyFilePath = Path.Combine(configurationFile, "not-a-directory", LinuxGeneratedMachineKey.KeyFileName);
+ var keyFilePath = Path.Combine(configurationFile, "not-a-directory", ConfigurationEncryptionKey.KeyFileName);
var store = CreateStore(keyFilePath);
store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey);
var legacyValue = RawCertificate();
// Act
- CreateUpgrade(store, keyFilePath).Run();
- store.Set(ProxyConfiguration.ProxyPasswordSettingName, "secret", ProtectionLevel.MachineKey);
+ Action run = () => CreateUpgrade(store, keyFilePath).Upgrade();
// Assert
- log.Received().Warn(Arg.Any(), Arg.Any());
+ run.Should().Throw();
RawCertificate().Should().Be(legacyValue);
- var reloaded = CreateStore(keyFilePath);
- reloaded.Get(TentacleConfiguration.CertificateSettingName, protectionLevel: ProtectionLevel.MachineKey).Should().Be(Certificate);
- reloaded.Get(ProxyConfiguration.ProxyPasswordSettingName, protectionLevel: ProtectionLevel.MachineKey).Should().Be("secret");
}
[Test]
public void WhenTheConfigurationIsNotInTheRegistryThenNoKeyIsCreatedAndValuesStayLegacy()
{
// Arrange
- var keyFilePath = Path.Combine(directory, "keys", "Tentacle", LinuxGeneratedMachineKey.KeyFileName);
+ var keyFilePath = Path.Combine(directory, "keys", "Tentacle", ConfigurationEncryptionKey.KeyFileName);
var store = CreateStore(keyFilePath);
store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey);
var legacyValue = RawCertificate();
// Act
- CreateUpgrade(store, keyFilePath: null, instanceName: null).Run();
+ CreateUpgrade(store, keyFilePath: null, instanceName: null).Upgrade();
// Assert
File.Exists(keyFilePath).Should().BeFalse();
@@ -128,7 +124,7 @@ public void WhenTheConfigurationIsNotInTheRegistryThenNoKeyIsCreatedAndValuesSta
public void UpgradeConfigurationEncryptionCreatesTheKeyAndReEncryptsLegacyValues()
{
// Arrange
- var keyFilePath = Path.Combine(directory, "keys", "Tentacle", LinuxGeneratedMachineKey.KeyFileName);
+ var keyFilePath = Path.Combine(directory, "keys", "Tentacle", ConfigurationEncryptionKey.KeyFileName);
var store = CreateStore(keyFilePath);
store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey);
@@ -145,7 +141,7 @@ public void UpgradeConfigurationEncryptionCreatesTheKeyAndReEncryptsLegacyValues
public void UpgradeConfigurationEncryptionFailsForAConfigurationNotInTheRegistry()
{
// Arrange
- var store = CreateStore(Path.Combine(directory, "keys", "Tentacle", LinuxGeneratedMachineKey.KeyFileName));
+ var store = CreateStore(Path.Combine(directory, "keys", "Tentacle", ConfigurationEncryptionKey.KeyFileName));
store.Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey);
var legacyValue = RawCertificate();
@@ -161,11 +157,11 @@ public void UpgradeConfigurationEncryptionFailsForAConfigurationNotInTheRegistry
public void AValueProtectedWithTheKeyIsNeverRewrittenWithALegacyKey()
{
// Arrange
- var keyFilePath = Path.Combine(directory, "my-key", LinuxGeneratedMachineKey.KeyFileName);
- new LinuxGeneratedMachineKey(log, fileSystem, keyFilePath).CreateIfMissing();
+ var keyFilePath = Path.Combine(directory, "my-key", ConfigurationEncryptionKey.KeyFileName);
+ new ConfigurationEncryptionKey(log, fileSystem, keyFilePath).CreateIfMissing();
CreateStore(keyFilePath).Set(TentacleConfiguration.CertificateSettingName, Certificate, ProtectionLevel.MachineKey);
var protectedValue = RawCertificate();
- var storeWithoutKey = CreateStore(Path.Combine(directory, "missing", LinuxGeneratedMachineKey.KeyFileName));
+ var storeWithoutKey = CreateStore(Path.Combine(directory, "missing", ConfigurationEncryptionKey.KeyFileName));
// Act
Action set = () => storeWithoutKey.Set(TentacleConfiguration.CertificateSettingName, "another certificate", ProtectionLevel.MachineKey);
@@ -178,7 +174,7 @@ public void AValueProtectedWithTheKeyIsNeverRewrittenWithALegacyKey()
readonly InMemoryCryptoKeyNixSource legacyKey = new();
XmlFileKeyValueStore CreateStore(string keyFilePath)
- => new(fileSystem, configurationFile, encryptor: new LinuxMachineKeyEncryptor(log, new LinuxGeneratedMachineKey(log, fileSystem, keyFilePath), new[] { legacyKey }));
+ => new(fileSystem, configurationFile, encryptor: new LinuxMachineKeyEncryptor(log, new ConfigurationEncryptionKey(log, fileSystem, keyFilePath), new[] { legacyKey }));
TentacleConfigurationUpgrade CreateUpgrade(XmlFileKeyValueStore store, string? keyFilePath, string? instanceName = "Tentacle")
=> new(CreateSelector(store, keyFilePath, instanceName), fileSystem, log);
diff --git a/source/Octopus.Tentacle.Tests/Configuration/XmlFileKeyValueStoreReEncryptionFixture.cs b/source/Octopus.Tentacle.Tests/Configuration/XmlFileKeyValueStoreReEncryptionFixture.cs
index a5e58c5df..c53a3983d 100644
--- a/source/Octopus.Tentacle.Tests/Configuration/XmlFileKeyValueStoreReEncryptionFixture.cs
+++ b/source/Octopus.Tentacle.Tests/Configuration/XmlFileKeyValueStoreReEncryptionFixture.cs
@@ -32,7 +32,7 @@ public void SetUp()
fileSystem.OverwriteFile(configurationFile, @"");
legacyKey = new InMemoryCryptoKeyNixSource();
- encryptor = new LinuxMachineKeyEncryptor(Substitute.For(), new InMemoryCryptoKeyNixSource(), new[] { legacyKey });
+ encryptor = new LinuxMachineKeyEncryptor(Substitute.For(), InMemoryConfigurationEncryptionKey.Create(), new[] { legacyKey });
// Writes what an earlier version would have left in the file...
legacyStore = new XmlFileKeyValueStore(fileSystem, configurationFile, encryptor: new LegacySchemeEncryptor(legacyKey));
diff --git a/source/Octopus.Tentacle.Tests/Support/TestMachineKeyEncryptor.cs b/source/Octopus.Tentacle.Tests/Support/TestMachineKeyEncryptor.cs
index 79adeab1e..9e13874bb 100644
--- a/source/Octopus.Tentacle.Tests/Support/TestMachineKeyEncryptor.cs
+++ b/source/Octopus.Tentacle.Tests/Support/TestMachineKeyEncryptor.cs
@@ -4,6 +4,7 @@
using Octopus.Tentacle.Configuration;
using Octopus.Tentacle.Configuration.Crypto;
using Octopus.Tentacle.Core.Diagnostics;
+using Octopus.Tentacle.Util;
using PlatformDetection = Octopus.Tentacle.Util.PlatformDetection;
namespace Octopus.Tentacle.Tests.Support
@@ -14,7 +15,7 @@ public static class TestMachineKeyEncryptor
{
public static readonly IMachineKeyEncryptor Current = PlatformDetection.IsRunningOnWindows
? new WindowsMachineKeyEncryptor()
- : new LinuxMachineKeyEncryptor(Substitute.For(), new InMemoryCryptoKeyNixSource(), Array.Empty());
+ : new LinuxMachineKeyEncryptor(Substitute.For(), InMemoryConfigurationEncryptionKey.Create(), Array.Empty());
}
public class InMemoryCryptoKeyNixSource : ICryptoKeyNixSource
@@ -35,10 +36,17 @@ public InMemoryCryptoKeyNixSource()
{
return (Key, IV);
}
+ }
- public (byte[] Key, byte[] IV)? TryLoad()
+ public static class InMemoryConfigurationEncryptionKey
+ {
+ public static ConfigurationEncryptionKey Create()
{
- return Load();
+ const string path = "/in-memory/config-encryption.key";
+ var fileSystem = Substitute.For();
+ fileSystem.FileExists(path).Returns(true);
+ fileSystem.ReadAllText(path).Returns(Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)));
+ return new ConfigurationEncryptionKey(Substitute.For(), fileSystem, path);
}
}
}
diff --git a/source/Octopus.Tentacle/Commands/CreateInstanceCommand.cs b/source/Octopus.Tentacle/Commands/CreateInstanceCommand.cs
index fa38b0e87..f1e1adef7 100644
--- a/source/Octopus.Tentacle/Commands/CreateInstanceCommand.cs
+++ b/source/Octopus.Tentacle/Commands/CreateInstanceCommand.cs
@@ -33,7 +33,7 @@ protected override void Start()
instanceManager.CreateInstance(instanceName, config, home);
}
- configurationUpgrade.Value.CreateKey();
+ configurationUpgrade.Value.PrepareKey();
}
}
}
diff --git a/source/Octopus.Tentacle/Commands/RunAgentCommand.cs b/source/Octopus.Tentacle/Commands/RunAgentCommand.cs
index 3c282dcca..2c74704af 100644
--- a/source/Octopus.Tentacle/Commands/RunAgentCommand.cs
+++ b/source/Octopus.Tentacle/Commands/RunAgentCommand.cs
@@ -101,7 +101,7 @@ protected override void Start()
return;
}
- configurationUpgrade.Value.Run();
+ configurationUpgrade.Value.TryUpgrade();
var currentPath = typeof(RunAgentCommand).Assembly.FullLocalPath();
var exePath = PlatformDetection.IsRunningOnWindows
diff --git a/source/Octopus.Tentacle/Commands/UpgradeConfigurationEncryptionCommand.cs b/source/Octopus.Tentacle/Commands/UpgradeConfigurationEncryptionCommand.cs
index ef2b9e5f0..76e5121b7 100644
--- a/source/Octopus.Tentacle/Commands/UpgradeConfigurationEncryptionCommand.cs
+++ b/source/Octopus.Tentacle/Commands/UpgradeConfigurationEncryptionCommand.cs
@@ -42,7 +42,7 @@ protected override void Start()
+ $"Register it with `create-instance --instance --config {instance.ConfigurationPath}`, then run this command again.");
}
- configurationUpgrade.Value.RunOrThrow();
+ configurationUpgrade.Value.Upgrade();
log.Info($"The configuration is protected with the encryption key `{instance.KeyFilePath}`.");
}
}
diff --git a/source/Octopus.Tentacle/Configuration/ConfigurationFilePermissions.cs b/source/Octopus.Tentacle/Configuration/ConfigurationFilePermissions.cs
index 1db32e708..d0aa1afc4 100644
--- a/source/Octopus.Tentacle/Configuration/ConfigurationFilePermissions.cs
+++ b/source/Octopus.Tentacle/Configuration/ConfigurationFilePermissions.cs
@@ -4,9 +4,8 @@
using Octopus.Tentacle.Util;
#if NET
using System.Diagnostics;
-using System.Runtime.InteropServices;
using System.Runtime.Versioning;
-using Microsoft.Win32.SafeHandles;
+using Octopus.Tentacle.Core.Util;
#endif
namespace Octopus.Tentacle.Configuration
@@ -16,7 +15,6 @@ static class ConfigurationFilePermissions
{
#if NET
public const UnixFileMode OwnerOnly = UnixFileMode.UserRead | UnixFileMode.UserWrite;
- const uint UnchangedGroup = uint.MaxValue;
#endif
public static void CreateEmpty(IOctopusFileSystem fileSystem, string configurationPath, string contents)
@@ -100,9 +98,8 @@ public static void RestrictToServiceUser(string? configurationPath, string? user
using var stream = new FileStream(configurationPath, FileMode.Open, FileAccess.Read);
File.SetUnixFileMode(stream.SafeFileHandle, OwnerOnly);
- return fchown(stream.SafeFileHandle, userId.Value, UnchangedGroup) == 0
- ? null
- : Marshal.GetLastPInvokeErrorMessage();
+ UnixFile.GiveTo(stream.SafeFileHandle, userId.Value);
+ return null;
}
catch (Exception ex)
{
@@ -132,9 +129,6 @@ public static void RestrictToServiceUser(string? configurationPath, string? user
return null;
}
}
-
- [DllImport("libc", SetLastError = true)]
- static extern int fchown(SafeFileHandle fd, uint owner, uint group);
#endif
}
}
diff --git a/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs
new file mode 100644
index 000000000..6b25c530b
--- /dev/null
+++ b/source/Octopus.Tentacle/Configuration/Crypto/ConfigurationEncryptionKey.cs
@@ -0,0 +1,145 @@
+using System;
+using System.Security.Cryptography;
+using System.Text;
+using Octopus.Tentacle.Core.Diagnostics;
+using Octopus.Tentacle.Core.Util;
+using Octopus.Tentacle.Util;
+
+namespace Octopus.Tentacle.Configuration.Crypto
+{
+ // The per-instance AES-256 key that protects a configuration file on Linux, stored as base64(key).
+ public class ConfigurationEncryptionKey
+ {
+ public const string KeyFileName = "config-encryption.key";
+
+ // Kept apart from /etc/octopus so that a copy of the configuration does not also carry the key that decrypts it.
+ public const string DefaultKeysDirectory = "/var/octopus/tentacle/keys";
+
+ const int KeySizeInBytes = 32;
+
+ static string KeysDirectory
+ => Environment.GetEnvironmentVariable(EnvironmentVariables.TentacleConfigurationKeysDirectory) is { Length: > 0 } directory ? directory : DefaultKeysDirectory;
+
+ readonly ISystemLog log;
+ readonly IOctopusFileSystem fileSystem;
+ byte[]? loaded;
+
+ // A null path means the configuration has no key, for example because it is not registered as an instance.
+ public ConfigurationEncryptionKey(ISystemLog log, IOctopusFileSystem fileSystem, string? keyFilePath)
+ {
+ this.log = log;
+ this.fileSystem = fileSystem;
+ KeyFilePath = keyFilePath;
+ }
+
+ public string? KeyFilePath { get; }
+
+ public string? KeyDirectory => KeyFilePath == null ? null : LinuxDirectoryOf(KeyFilePath);
+
+ public static string KeyFilePathFor(string instanceName)
+ {
+ if (string.IsNullOrWhiteSpace(instanceName)
+ || instanceName.IndexOfAny(new[] { '/', '\\', '\0' }) >= 0
+ || instanceName == "."
+ || instanceName == "..")
+ {
+ throw new ArgumentException($"The instance name `{instanceName}` cannot be used as a key directory name.", nameof(instanceName));
+ }
+
+ return JoinLinuxPath(JoinLinuxPath(KeysDirectory, instanceName), KeyFileName);
+ }
+
+ public byte[] Load()
+ => TryLoad() ?? throw new InvalidOperationException(KeyFilePath == null
+ ? "The configuration encryption key for this configuration is not available. Register the configuration with `create-instance --instance `."
+ : $"The configuration encryption key file `{KeyFilePath}` does not exist, so the values it protected cannot be decrypted. Restore it from a backup.");
+
+ public byte[]? TryLoad()
+ {
+ if (loaded != null)
+ {
+ return loaded;
+ }
+
+ if (KeyFilePath == null || !fileSystem.FileExists(KeyFilePath))
+ {
+ return null;
+ }
+
+ loaded = LoadFromFile(KeyFilePath);
+ return loaded;
+ }
+
+ // Only the configuration upgrade creates the key, so that it can then give the key to the configuration's owner.
+ public void CreateIfMissing()
+ {
+ var path = KeyFilePath ?? throw new InvalidOperationException("There is no key file path to create the configuration encryption key at.");
+ if (fileSystem.FileExists(path))
+ {
+ return;
+ }
+
+ var raw = Convert.ToBase64String(RandomKey());
+
+ fileSystem.EnsureDirectoryExists(KeyDirectory!);
+
+ // Several instances starting at once after an upgrade must all end up with the same key.
+ if (!fileSystem.AtomicCreateFileWithUserReadWriteAccessOnly(path, Encoding.ASCII.GetBytes(raw)))
+ {
+ log.Verbose($"Another process created the configuration encryption key `{path}` first; using its key.");
+ return;
+ }
+
+ log.Info($"Generated a new configuration encryption key at `{path}`. Back it up with the configuration file it protects: the configuration cannot be decrypted without it.");
+ }
+
+ static byte[] RandomKey()
+ {
+ var key = new byte[KeySizeInBytes];
+ using var random = RandomNumberGenerator.Create();
+ random.GetBytes(key);
+ return key;
+ }
+
+ byte[] LoadFromFile(string path)
+ {
+ string contents;
+ try
+ {
+ contents = fileSystem.ReadAllText(path);
+ }
+ catch (UnauthorizedAccessException e)
+ {
+ var user = Environment.UserName;
+ var directory = LinuxDirectoryOf(path);
+ throw new InvalidOperationException($"The configuration encryption key file `{path}` exists but the user Tentacle is running as ({user}) cannot read it. "
+ + $"It must be owned by and readable only by that user, for example: `sudo chown -R {user} {directory} && sudo chmod 700 {directory} && sudo chmod 600 {path}`.", e);
+ }
+
+ try
+ {
+ var key = Convert.FromBase64String(contents.Trim());
+ if (key.Length == KeySizeInBytes)
+ {
+ return key;
+ }
+ }
+ catch (FormatException)
+ {
+ }
+
+ throw new InvalidOperationException($"The configuration encryption key file `{path}` is corrupt: it must hold a base64-encoded {KeySizeInBytes * 8}-bit key. "
+ + "Restore it from a backup; values encrypted with a lost key cannot be recovered.");
+ }
+
+ // Always Linux paths, even when unit tests run on Windows.
+ static string JoinLinuxPath(string directory, string fileName)
+ => directory.EndsWith("/", StringComparison.Ordinal) ? directory + fileName : directory + "/" + fileName;
+
+ static string LinuxDirectoryOf(string path)
+ {
+ var lastSeparator = path.LastIndexOf('/');
+ return lastSeparator <= 0 ? "/" : path.Substring(0, lastSeparator);
+ }
+ }
+}
diff --git a/source/Octopus.Tentacle/Configuration/Crypto/ICryptoKeyNixSource.cs b/source/Octopus.Tentacle/Configuration/Crypto/ICryptoKeyNixSource.cs
index 43c5d891c..0cd958ea2 100644
--- a/source/Octopus.Tentacle/Configuration/Crypto/ICryptoKeyNixSource.cs
+++ b/source/Octopus.Tentacle/Configuration/Crypto/ICryptoKeyNixSource.cs
@@ -5,7 +5,5 @@ namespace Octopus.Tentacle.Configuration.Crypto
public interface ICryptoKeyNixSource
{
(byte[] Key, byte[] IV) Load();
-
- (byte[] Key, byte[] IV)? TryLoad();
}
}
\ No newline at end of file
diff --git a/source/Octopus.Tentacle/Configuration/Crypto/LinuxGeneratedMachineKey.cs b/source/Octopus.Tentacle/Configuration/Crypto/LinuxGeneratedMachineKey.cs
index 438483cf9..aac2ffc1f 100644
--- a/source/Octopus.Tentacle/Configuration/Crypto/LinuxGeneratedMachineKey.cs
+++ b/source/Octopus.Tentacle/Configuration/Crypto/LinuxGeneratedMachineKey.cs
@@ -1,130 +1,42 @@
using System;
-using System.Security.Cryptography;
-using System.Text;
-using Octopus.Tentacle.Core.Diagnostics;
+using System.IO;
using Octopus.Tentacle.Core.Util;
using Octopus.Tentacle.Util;
namespace Octopus.Tentacle.Configuration.Crypto
{
- // The legacy machinekey file was world-readable, so it is only ever read to decrypt what earlier versions wrote and is
- // never adopted as the current key. Both files are base64(key).base64(iv); the IV is only used by the legacy scheme.
+ // The key file earlier versions generated on first use, as base64(key).base64(iv). It is only read, to decrypt what they wrote.
public class LinuxGeneratedMachineKey : ICryptoKeyNixSource
{
- public const string KeyFileName = "config-encryption.key";
public const string LegacyKeyFileName = "machinekey";
public const string LegacyKeyFilePath = "/etc/octopus/" + LegacyKeyFileName;
- // Kept apart from /etc/octopus so that a copy of the configuration does not also carry the key that decrypts it.
- public const string DefaultKeysDirectory = "/var/octopus/tentacle/keys";
-
- static string KeysDirectory
- => Environment.GetEnvironmentVariable(EnvironmentVariables.TentacleConfigurationKeysDirectory) is { Length: > 0 } directory ? directory : DefaultKeysDirectory;
-
- readonly ISystemLog log;
readonly IOctopusFileSystem fileSystem;
- (byte[] Key, byte[] IV)? loaded;
- public LinuxGeneratedMachineKey(ISystemLog log, IOctopusFileSystem fileSystem, string keyFilePath)
+ public LinuxGeneratedMachineKey(IOctopusFileSystem fileSystem)
{
- this.log = log;
this.fileSystem = fileSystem;
- KeyFilePath = keyFilePath;
- }
-
- public string KeyFilePath { get; }
-
- public string KeyDirectory => LinuxDirectoryOf(KeyFilePath);
-
- public static string KeyFilePathFor(string instanceName)
- {
- if (string.IsNullOrWhiteSpace(instanceName)
- || instanceName.IndexOfAny(new[] { '/', '\\', '\0' }) >= 0
- || instanceName == "."
- || instanceName == "..")
- {
- throw new ArgumentException($"The instance name `{instanceName}` cannot be used as a key directory name.", nameof(instanceName));
- }
-
- return JoinLinuxPath(JoinLinuxPath(KeysDirectory, instanceName), KeyFileName);
}
public static string LegacyKeyFilePathForThisHost
=> KubernetesSupportDetection.IsRunningAsKubernetesAgent
- ? JoinLinuxPath(Environment.GetEnvironmentVariable(EnvironmentVariables.TentacleHome)!, LegacyKeyFileName)
+ //if we are running in K8S, the machine key is in the home directory, which is likely on a network drive
+ ? Path.Combine(Environment.GetEnvironmentVariable(EnvironmentVariables.TentacleHome)!, LegacyKeyFileName)
: LegacyKeyFilePath;
public (byte[] Key, byte[] IV) Load()
- => TryLoad() ?? throw new InvalidOperationException($"There is no machine key file at `{KeyFilePath}`.");
-
- public (byte[] Key, byte[] IV)? TryLoad()
- {
- if (loaded.HasValue)
- {
- return loaded;
- }
-
- if (!fileSystem.FileExists(KeyFilePath))
- {
- return null;
- }
-
- loaded = LoadFromFile(KeyFilePath);
- return loaded;
- }
-
- // Only the configuration upgrade creates the key, so that it can then give the key to the configuration's owner.
- public void CreateIfMissing()
{
- if (fileSystem.FileExists(KeyFilePath))
- {
- return;
- }
-
- using var aes = Aes.Create();
- aes.KeySize = 256;
- aes.GenerateIV();
- aes.GenerateKey();
- var raw = Convert.ToBase64String(aes.Key) + "." + Convert.ToBase64String(aes.IV);
-
- fileSystem.EnsureDirectoryExists(KeyDirectory);
-
- // Several instances starting at once after an upgrade must all end up with the same key.
- if (!fileSystem.AtomicCreateFileWithUserReadWriteAccessOnly(KeyFilePath, Encoding.ASCII.GetBytes(raw)))
+ var path = LegacyKeyFilePathForThisHost;
+ if (!fileSystem.FileExists(path))
{
- log.Verbose($"Another process created the machine key file `{KeyFilePath}` first; using its key.");
- return;
+ throw new InvalidOperationException($"There is no machine key file at `{path}`.");
}
- log.Info($"Generated a new machine key at `{KeyFilePath}`. Back it up with the configuration file it protects: the configuration cannot be decrypted without it.");
- }
-
- (byte[] Key, byte[] IV) LoadFromFile(string path)
- {
- string contents;
try
{
- contents = fileSystem.ReadAllText(path);
- }
- catch (UnauthorizedAccessException e)
- {
- var user = Environment.UserName;
- var directory = LinuxDirectoryOf(path);
- throw new InvalidOperationException($"The machine key file `{path}` exists but the user Tentacle is running as ({user}) cannot read it. "
- + $"It must be owned by and readable only by that user, for example: `sudo chown -R {user} {directory} && sudo chmod 700 {directory} && sudo chmod 600 {path}`.", e);
- }
-
- try
- {
- var content = contents.Split('.');
- var key = Convert.FromBase64String(content[0]);
- var iv = Convert.FromBase64String(content[1]);
- if (key.Length == 0)
- {
- throw new FormatException("The key is empty.");
- }
- return (key, iv);
+ var content = fileSystem.ReadAllText(path).Split('.');
+ return (Convert.FromBase64String(content[0]), Convert.FromBase64String(content[1]));
}
catch (Exception ex) when (ex is FormatException || ex is IndexOutOfRangeException)
{
@@ -133,15 +45,5 @@ public void CreateIfMissing()
+ $"Remove the file `{path}` and allow Octopus to regenerate the key.");
}
}
-
- // Always Linux paths, even when unit tests run on Windows.
- static string JoinLinuxPath(string directory, string fileName)
- => directory.EndsWith("/", StringComparison.Ordinal) ? directory + fileName : directory + "/" + fileName;
-
- static string LinuxDirectoryOf(string path)
- {
- var lastSeparator = path.LastIndexOf('/');
- return lastSeparator <= 0 ? "/" : path.Substring(0, lastSeparator);
- }
}
}
diff --git a/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineIdKey.cs b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineIdKey.cs
index 0327f2d84..c6d286e9c 100644
--- a/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineIdKey.cs
+++ b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineIdKey.cs
@@ -29,11 +29,6 @@ public LinuxMachineIdKey(IOctopusFileSystem fileSystem)
return (GetMachineId(), Iv);
}
- public (byte[] Key, byte[] IV)? TryLoad()
- {
- return fileSystem.FileExists(FileName) ? Load() : null;
- }
-
byte[] GetMachineId()
{
if (!fileSystem.FileExists(FileName))
diff --git a/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs
index 5b2becc03..74777b9cd 100644
--- a/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs
+++ b/source/Octopus.Tentacle/Configuration/Crypto/LinuxMachineKeyEncryptor.cs
@@ -14,7 +14,6 @@ public class LinuxMachineKeyEncryptor : IMachineKeyEncryptor
// $ is not a base64 character, so a value without this prefix is unambiguously a legacy one.
public const string ProtectedValuePrefix = "$OctopusMachineKeyV1$";
- const int KeySizeInBytes = 32;
const int NonceSizeInBytes = 12;
const int TagSizeInBytes = 16;
@@ -24,13 +23,13 @@ public class LinuxMachineKeyEncryptor : IMachineKeyEncryptor
static readonly Encoding StrictUtf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
readonly ISystemLog log;
- readonly ICryptoKeyNixSource keySource;
+ readonly ConfigurationEncryptionKey configurationKey;
readonly IReadOnlyList legacyKeySources;
- public LinuxMachineKeyEncryptor(ISystemLog log, ICryptoKeyNixSource keySource, IEnumerable legacyKeySources)
+ public LinuxMachineKeyEncryptor(ISystemLog log, ConfigurationEncryptionKey configurationKey, IEnumerable legacyKeySources)
{
this.log = log;
- this.keySource = keySource;
+ this.configurationKey = configurationKey;
this.legacyKeySources = legacyKeySources.ToArray();
}
@@ -45,7 +44,7 @@ public string Encrypt(string raw)
{
try
{
- var currentKey = TryLoadCurrentKey();
+ var currentKey = configurationKey.TryLoad();
return currentKey == null ? EncryptLegacy(raw) : EncryptCurrent(currentKey, raw);
}
catch (Exception e)
@@ -71,17 +70,26 @@ static string EncryptCurrent(byte[] key, string raw)
}
string EncryptLegacy(string raw)
+ {
+ var (encrypted, errors) = TryEachLegacyKey(legacy =>
+ {
+ using var aes = Aes.Create();
+ using var encryptor = aes.CreateEncryptor(legacy.Key, legacy.IV);
+ var plaintext = Encoding.UTF8.GetBytes(raw);
+ return Convert.ToBase64String(encryptor.TransformFinalBlock(plaintext, 0, plaintext.Length));
+ });
+
+ return encrypted ?? throw new AggregateException("There is no configuration encryption key yet, and none of the keys earlier versions used is available.", errors);
+ }
+
+ (string? Result, List Errors) TryEachLegacyKey(Func<(byte[] Key, byte[] IV), string> use)
{
var errors = new List();
foreach (var source in legacyKeySources)
{
try
{
- var (key, iv) = source.Load();
- using var aes = Aes.Create();
- using var encryptor = aes.CreateEncryptor(key, iv);
- var plaintext = Encoding.UTF8.GetBytes(raw);
- return Convert.ToBase64String(encryptor.TransformFinalBlock(plaintext, 0, plaintext.Length));
+ return (use(source.Load()), errors);
}
catch (Exception e)
{
@@ -90,30 +98,26 @@ string EncryptLegacy(string raw)
}
}
- throw new AggregateException("There is no configuration encryption key yet, and none of the keys earlier versions used is available.", errors);
+ return (null, errors);
}
- byte[]? TryLoadCurrentKey()
+ public string Decrypt(string encrypted)
+ => IsLegacyCiphertext(encrypted)
+ ? DecryptLegacy(encrypted)
+ : DecryptCurrent(encrypted);
+
+ string DecryptCurrent(string encrypted)
{
+ byte[] key;
try
{
- var existing = keySource.TryLoad();
- return existing == null ? null : CheckSize(existing.Value.Key);
+ key = configurationKey.Load();
}
catch (Exception e)
{
- log.Verbose($"Unable to use the configuration encryption key, so using the key earlier versions used: {e.Message}");
- return null;
+ throw new CryptographicException(e.Message, e);
}
- }
-
- public string Decrypt(string encrypted)
- => IsLegacyCiphertext(encrypted)
- ? DecryptLegacy(encrypted)
- : DecryptCurrent(encrypted);
- string DecryptCurrent(string encrypted)
- {
try
{
var payload = Convert.FromBase64String(encrypted.Substring(ProtectedValuePrefix.Length));
@@ -122,13 +126,9 @@ string DecryptCurrent(string encrypted)
throw new FormatException("The encrypted value is too short to contain a nonce and an authentication tag.");
}
- var plaintext = Gcm.Decrypt(LoadCurrentKey(), payload, AssociatedData);
+ var plaintext = Gcm.Decrypt(key, payload, AssociatedData);
return StrictUtf8.GetString(plaintext);
}
- catch (InvalidOperationException e) when (e.InnerException is UnauthorizedAccessException)
- {
- throw new CryptographicException(e.Message, e);
- }
catch (Exception e)
{
// No fallback to the legacy keys: they could never have written a value with the prefix.
@@ -138,37 +138,20 @@ string DecryptCurrent(string encrypted)
}
}
- byte[] LoadCurrentKey()
- => CheckSize(keySource.Load().Key);
-
- static byte[] CheckSize(byte[] key)
+ string DecryptLegacy(string encrypted)
{
- if (key.Length != KeySizeInBytes)
+ var (decrypted, errors) = TryEachLegacyKey(legacy =>
{
- throw new CryptographicException($"The machine key must be {KeySizeInBytes * 8} bits, but is {key.Length * 8}.");
- }
- return key;
- }
+ using var aes = Aes.Create();
+ using var decryptor = aes.CreateDecryptor(legacy.Key, legacy.IV);
+ var payload = Convert.FromBase64String(encrypted);
+ var plaintext = decryptor.TransformFinalBlock(payload, 0, payload.Length);
+ return StrictUtf8.GetString(plaintext);
+ });
- string DecryptLegacy(string encrypted)
- {
- var errors = new List();
- foreach (var source in legacyKeySources)
+ if (decrypted != null)
{
- try
- {
- var (key, iv) = source.Load();
- using var aes = Aes.Create();
- using var decryptor = aes.CreateDecryptor(key, iv);
- var payload = Convert.FromBase64String(encrypted);
- var plaintext = decryptor.TransformFinalBlock(payload, 0, payload.Length);
- return StrictUtf8.GetString(plaintext);
- }
- catch (Exception e)
- {
- log.Verbose(e.Message);
- errors.Add(e);
- }
+ return decrypted;
}
throw new CryptographicException("Unable to decrypt a value that was protected by an earlier version of Tentacle with any of the keys it could have used. "
diff --git a/source/Octopus.Tentacle/Configuration/Crypto/MachineKeyEncryptor.cs b/source/Octopus.Tentacle/Configuration/Crypto/MachineKeyEncryptor.cs
index 6a7db8cd4..2d105f740 100644
--- a/source/Octopus.Tentacle/Configuration/Crypto/MachineKeyEncryptor.cs
+++ b/source/Octopus.Tentacle/Configuration/Crypto/MachineKeyEncryptor.cs
@@ -1,5 +1,4 @@
-using System;
-using System.Collections.Generic;
+using System.Collections.Generic;
using Octopus.Tentacle.Core.Diagnostics;
using Octopus.Tentacle.Diagnostics;
using Octopus.Tentacle.Util;
@@ -13,31 +12,18 @@ public static class MachineKeyEncryptor
public static IMachineKeyEncryptor ForKeyFile(IOctopusFileSystem fileSystem, string? keyFilePath)
=> PlatformDetection.IsRunningOnWindows
? new WindowsMachineKeyEncryptor()
- : keyFilePath == null
- ? CreateLinuxEncryptor(Log, fileSystem, new NoConfigurationEncryptionKey())
- : CreateLinuxEncryptor(Log, fileSystem, keyFilePath);
+ : CreateLinuxEncryptor(Log, fileSystem, keyFilePath);
- internal static IMachineKeyEncryptor CreateLinuxEncryptor(ISystemLog log, IOctopusFileSystem fileSystem, string keyFilePath)
- => CreateLinuxEncryptor(log, fileSystem, new LinuxGeneratedMachineKey(log, fileSystem, keyFilePath));
-
- static IMachineKeyEncryptor CreateLinuxEncryptor(ISystemLog log, IOctopusFileSystem fileSystem, ICryptoKeyNixSource generatedKey)
+ internal static IMachineKeyEncryptor CreateLinuxEncryptor(ISystemLog log, IOctopusFileSystem fileSystem, string? keyFilePath)
{
// The keys earlier versions used, in the order they tried them. Only read, never created or changed.
var legacyKeySources = new List
{
new LinuxMachineIdKey(fileSystem),
- new LinuxGeneratedMachineKey(log, fileSystem, LinuxGeneratedMachineKey.LegacyKeyFilePathForThisHost)
+ new LinuxGeneratedMachineKey(fileSystem)
};
- return new LinuxMachineKeyEncryptor(log, generatedKey, legacyKeySources);
- }
-
- class NoConfigurationEncryptionKey : ICryptoKeyNixSource
- {
- public (byte[] Key, byte[] IV) Load()
- => throw new InvalidOperationException("The configuration encryption key for this configuration is not available. Register the configuration with `create-instance --instance `.");
-
- public (byte[] Key, byte[] IV)? TryLoad() => null;
+ return new LinuxMachineKeyEncryptor(log, new ConfigurationEncryptionKey(log, fileSystem, keyFilePath), legacyKeySources);
}
}
}
diff --git a/source/Octopus.Tentacle/Configuration/FlatDictionaryKeyValueStore.cs b/source/Octopus.Tentacle/Configuration/FlatDictionaryKeyValueStore.cs
index b1e8ff781..354246a98 100644
--- a/source/Octopus.Tentacle/Configuration/FlatDictionaryKeyValueStore.cs
+++ b/source/Octopus.Tentacle/Configuration/FlatDictionaryKeyValueStore.cs
@@ -22,7 +22,6 @@ protected FlatDictionaryKeyValueStore(JsonSerializerSettings jsonSerializerSetti
if (name == null) throw new ArgumentNullException(nameof(name));
string? valueAsString = null;
- var decrypting = false;
try
{
var data = Read(name);
@@ -33,11 +32,7 @@ protected FlatDictionaryKeyValueStore(JsonSerializerSettings jsonSerializerSetti
return defaultValue;
if (protectionLevel == ProtectionLevel.MachineKey)
- {
- decrypting = true;
- data = Encryptor.Decrypt(valueAsString);
- decrypting = false;
- }
+ data = Decrypt(name, valueAsString);
if (typeof(TData) == typeof(string))
return (TData)data;
@@ -48,13 +43,8 @@ protected FlatDictionaryKeyValueStore(JsonSerializerSettings jsonSerializerSetti
return JsonConvert.DeserializeObject((string)data, JsonSerializerSettings);
}
- catch (Exception e)
+ catch (Exception e) when (e is not DecryptionFailedException)
{
- // The console does not always print inner messages, and this one says how to recover.
- if (decrypting)
- {
- throw new FormatException($"Unable to decrypt the protected configuration setting '{name}'. {e.Message}", e);
- }
if (protectionLevel == ProtectionLevel.None)
throw new FormatException($"Unable to parse configuration key '{name}' as a '{typeof(TData).Name}'. Value was '{valueAsString}'.", e);
throw new FormatException($"Unable to parse configuration key '{name}' as a '{typeof(TData).Name}'.", e);
@@ -66,7 +56,6 @@ protected FlatDictionaryKeyValueStore(JsonSerializerSettings jsonSerializerSetti
if (name == null) throw new ArgumentNullException(nameof(name));
string? valueAsString = null;
- var decrypting = false;
try
{
var data = Read(name);
@@ -77,11 +66,7 @@ protected FlatDictionaryKeyValueStore(JsonSerializerSettings jsonSerializerSetti
return (false, default!);
if (protectionLevel == ProtectionLevel.MachineKey)
- {
- decrypting = true;
- data = Encryptor.Decrypt(valueAsString);
- decrypting = false;
- }
+ data = Decrypt(name, valueAsString);
if (typeof(TData) == typeof(string))
return (true, (TData)data);
@@ -92,18 +77,34 @@ protected FlatDictionaryKeyValueStore(JsonSerializerSettings jsonSerializerSetti
return (true, JsonConvert.DeserializeObject((string)data, JsonSerializerSettings));
}
- catch (Exception e)
+ catch (Exception e) when (e is not DecryptionFailedException)
{
- if (decrypting)
- {
- throw new FormatException($"Unable to decrypt the protected configuration setting '{name}'. {e.Message}", e);
- }
if (protectionLevel == ProtectionLevel.None)
throw new FormatException($"Unable to parse configuration key '{name}' as a '{typeof(TData).Name}'. Value was '{valueAsString}'.", e);
throw new FormatException($"Unable to parse configuration key '{name}' as a '{typeof(TData).Name}'.", e);
}
}
+ string Decrypt(string name, string value)
+ {
+ try
+ {
+ return Encryptor.Decrypt(value);
+ }
+ catch (Exception e)
+ {
+ // The console does not always print inner messages, and this one says how to recover.
+ throw new DecryptionFailedException($"Unable to decrypt the protected configuration setting '{name}'. {e.Message}", e);
+ }
+ }
+
+ class DecryptionFailedException : FormatException
+ {
+ public DecryptionFailedException(string message, Exception inner) : base(message, inner)
+ {
+ }
+ }
+
public override bool Set(string name, TData value, ProtectionLevel protectionLevel = ProtectionLevel.None)
{
if (name == null) throw new ArgumentNullException(nameof(name));
@@ -134,7 +135,7 @@ public override bool Set(string name, TData value, ProtectionLevel protec
string EncryptWithoutDowngrading(string name, string raw)
{
var encrypted = Encryptor.Encrypt(raw);
- if (Encryptor.RequiresReEncryption(encrypted) && Read(name) is string previous && !string.IsNullOrWhiteSpace(previous) && !Encryptor.RequiresReEncryption(previous))
+ if (Encryptor.RequiresReEncryption(encrypted) && Read(name) is string previous && !Encryptor.RequiresReEncryption(previous))
{
throw new CryptographicException($"Unable to update the protected setting '{name}': it is protected with the configuration encryption key, which is not available. Make sure the key file exists and is readable.");
}
diff --git a/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceSelector.cs b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceSelector.cs
index 8ceeb90c0..14f50c9d8 100644
--- a/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceSelector.cs
+++ b/source/Octopus.Tentacle/Configuration/Instances/ApplicationInstanceSelector.cs
@@ -87,7 +87,7 @@ ApplicationInstanceConfiguration LoadInstance()
}
var name = appInstance.instanceName ?? RegisteredInstanceNameFor(appInstance.configurationpath);
- return name == null ? null : LinuxGeneratedMachineKey.KeyFilePathFor(name);
+ return name == null ? null : ConfigurationEncryptionKey.KeyFilePathFor(name);
}
string? RegisteredInstanceNameFor(string? configurationPath)
@@ -124,7 +124,7 @@ ApplicationInstanceConfiguration LoadInstance()
EnsureConfigurationExists(appInstance.instanceName, appInstance.configurationpath);
log.Verbose($"Loading configuration from {appInstance.configurationpath}");
- var writable = new XmlFileKeyValueStore(fileSystem, appInstance.configurationpath!, keyFilePath: keyFilePath);
+ var writable = new XmlFileKeyValueStore(fileSystem, appInstance.configurationpath!, MachineKeyEncryptor.ForKeyFile(fileSystem, keyFilePath));
return (ContributeAdditionalConfiguration(writable), writable);
}
diff --git a/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs b/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs
index 05cf2ebfd..daa7272a7 100644
--- a/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs
+++ b/source/Octopus.Tentacle/Configuration/TentacleConfigurationUpgrade.cs
@@ -1,10 +1,10 @@
using System;
using System.Collections.Generic;
using System.IO;
-using System.Runtime.InteropServices;
using Octopus.Tentacle.Configuration.Crypto;
using Octopus.Tentacle.Configuration.Instances;
using Octopus.Tentacle.Core.Diagnostics;
+using Octopus.Tentacle.Core.Util;
using Octopus.Tentacle.Util;
namespace Octopus.Tentacle.Configuration
@@ -14,17 +14,15 @@ public interface ITentacleConfigurationUpgrade
// Creates the configuration encryption key if it is missing, and gives it to the configuration's owner when running as root.
void PrepareKey();
- // As PrepareKey, but fails when the key cannot be created.
- void CreateKey();
-
// Prepares the key, then re-encrypts protected settings written with the keys earlier versions used.
- void Run();
+ void Upgrade();
- // As Run, but fails when the key cannot be created or a setting cannot be re-encrypted.
- void RunOrThrow();
+ // As PrepareKey and Upgrade, but a failure is logged as a warning and Tentacle carries on with the keys earlier versions used.
+ void TryPrepareKey();
+ void TryUpgrade();
}
- // Until Run succeeds, Tentacle keeps working on the keys earlier versions used.
+ // Until Upgrade succeeds, Tentacle keeps working on the keys earlier versions used.
public class TentacleConfigurationUpgrade : ITentacleConfigurationUpgrade
{
public static readonly IReadOnlyList ProtectedSettingNames = new[]
@@ -48,36 +46,29 @@ public TentacleConfigurationUpgrade(IApplicationInstanceSelector instanceSelecto
}
public void PrepareKey()
- {
- try
- {
- TryPrepareKey();
- }
- catch (Exception e)
- {
- log.Warn(e, "Unable to prepare the configuration encryption key, " + StillOnLegacyKeys);
- }
- }
+ => PrepareInstanceKey();
+
+ public void TryPrepareKey()
+ => WarnOnFailure(PrepareKey, "Unable to prepare the configuration encryption key");
- public void CreateKey()
- => TryPrepareKey();
+ public void TryUpgrade()
+ => WarnOnFailure(Upgrade, "Unable to move the configuration to its own encryption key");
- public void Run()
+ void WarnOnFailure(Action action, string failure)
{
try
{
- RunOrThrow();
+ action();
}
catch (Exception e)
{
- log.Warn(e, "Unable to move the configuration to its own encryption key, " + StillOnLegacyKeys);
+ log.Warn(e, $"{failure}, {StillOnLegacyKeys}");
}
}
- public void RunOrThrow()
+ public void Upgrade()
{
-#if NET
- var prepared = TryPrepareKey();
+ var prepared = PrepareInstanceKey();
if (prepared == null)
{
return;
@@ -92,13 +83,12 @@ public void RunOrThrow()
log.Info($"Re-encrypted the protected setting '{name}' with the configuration encryption key.");
}
}
-#endif
}
-#if NET
- (LinuxGeneratedMachineKey Key, XmlFileKeyValueStore Store)? TryPrepareKey()
+ // Null when the instance has no key to prepare.
+ (ConfigurationEncryptionKey Key, XmlFileKeyValueStore Store)? PrepareInstanceKey()
{
- if (OperatingSystem.IsWindows())
+ if (PlatformDetection.IsRunningOnWindows)
{
return null;
}
@@ -117,78 +107,16 @@ public void RunOrThrow()
return null;
}
- var key = new LinuxGeneratedMachineKey(log, fileSystem, instance.KeyFilePath);
+ var key = new ConfigurationEncryptionKey(log, fileSystem, instance.KeyFilePath);
key.CreateIfMissing();
- var configurationOwner = UnixOwnership.OwnerOf(instance.ConfigurationPath);
- UnixOwnership.GiveToIfRoot(configurationOwner, key.KeyDirectory);
- UnixOwnership.GiveToIfRoot(configurationOwner, key.KeyFilePath);
-
- return (key, store);
- }
-#else
- void TryPrepareKey()
- {
- }
-#endif
-
#if NET
- static class UnixOwnership
- {
- const uint UnchangedGroup = uint.MaxValue;
-
- public static uint OwnerOf(string path)
- {
- return SystemNative_Stat(path, out var status) == 0
- ? status.Uid
- : throw new IOException($"Unable to find the owner of `{path}`: {Marshal.GetLastPInvokeErrorMessage()}");
- }
-
- public static void GiveToIfRoot(uint owner, string path)
- {
- if (geteuid() != 0 || OwnerOf(path) == owner)
- {
- return;
- }
-
- if (lchown(path, owner, UnchangedGroup) != 0)
- {
- throw new IOException($"Unable to change the owner of `{path}`: {Marshal.GetLastPInvokeErrorMessage()}");
- }
- }
-
- [DllImport("libc")]
- static extern uint geteuid();
-
- [DllImport("libc", SetLastError = true)]
- static extern int lchown(string path, uint owner, uint group);
-
- // The .NET runtime's own stat shim: one struct layout on every libc and architecture.
- [DllImport("libSystem.Native", SetLastError = true)]
- static extern int SystemNative_Stat(string path, out FileStatus output);
+ var configurationOwner = UnixFile.OwnerOf(instance.ConfigurationPath);
+ UnixFile.SetOwnerIfRunningAsRoot(configurationOwner, key.KeyDirectory!);
+ UnixFile.SetOwnerIfRunningAsRoot(configurationOwner, key.KeyFilePath!);
+#endif
- [StructLayout(LayoutKind.Sequential)]
- struct FileStatus
- {
- public int Flags;
- public int Mode;
- public uint Uid;
- public uint Gid;
- public long Size;
- public long ATime;
- public long ATimeNsec;
- public long MTime;
- public long MTimeNsec;
- public long CTime;
- public long CTimeNsec;
- public long BirthTime;
- public long BirthTimeNsec;
- public long Dev;
- public long RDev;
- public long Ino;
- public uint UserFlags;
- }
+ return (key, store);
}
-#endif
}
}
diff --git a/source/Octopus.Tentacle/Configuration/XmlFileKeyValueStore.cs b/source/Octopus.Tentacle/Configuration/XmlFileKeyValueStore.cs
index 841375f0b..ab1d365ad 100644
--- a/source/Octopus.Tentacle/Configuration/XmlFileKeyValueStore.cs
+++ b/source/Octopus.Tentacle/Configuration/XmlFileKeyValueStore.cs
@@ -13,10 +13,9 @@ public class XmlFileKeyValueStore : XmlKeyValueStore
public XmlFileKeyValueStore(IOctopusFileSystem fileSystem,
string configurationFile,
+ IMachineKeyEncryptor encryptor,
bool autoSaveOnSet = true,
- bool isWriteOnly = false,
- IMachineKeyEncryptor? encryptor = null,
- string? keyFilePath = null) : base(encryptor ?? MachineKeyEncryptor.ForKeyFile(fileSystem, keyFilePath), autoSaveOnSet, isWriteOnly)
+ bool isWriteOnly = false) : base(encryptor, autoSaveOnSet, isWriteOnly)
{
this.fileSystem = fileSystem;
this.configurationFile = fileSystem.GetFullPath(configurationFile);
diff --git a/source/Octopus.Tentacle/Startup/ServiceCommand.cs b/source/Octopus.Tentacle/Startup/ServiceCommand.cs
index c3bf502ca..3eb479805 100644
--- a/source/Octopus.Tentacle/Startup/ServiceCommand.cs
+++ b/source/Octopus.Tentacle/Startup/ServiceCommand.cs
@@ -129,7 +129,7 @@ protected override void Start()
ConfigurationFilePermissions.RestrictToServiceUser(instanceSelector.Current.ConfigurationPath, serviceConfigurationState.Username, log);
// A non-root service cannot create its key under /var/octopus, so it is created here while running as root.
- configurationUpgrade.Value.PrepareKey();
+ configurationUpgrade.Value.TryPrepareKey();
}
}
}