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
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
Expand All @@ -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
{
Expand Down Expand Up @@ -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);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
/// <summary>
/// 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.
/// </summary>
/// <returns>True if this call created the file, false if it already existed, in which case the existing file is left untouched.</returns>
bool AtomicCreateFileWithUserReadWriteAccessOnly(string filePath, byte[] contents);

string ReadAllText(string scriptFile);
Expand Down
66 changes: 25 additions & 41 deletions source/Octopus.Tentacle.Core/Util/OctopusPhysicalFileSystem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand All @@ -306,17 +266,41 @@ 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())
{
options.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite;
}

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)
{
Expand Down
81 changes: 79 additions & 2 deletions source/Octopus.Tentacle.Core/Util/UnixFile.cs
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public void WhenCommandIsStartedThenTheConfigurationIsUpgradedBeforeHalibutStart
// Assert
Received.InOrder(() =>
{
configurationUpgrade.Run();
configurationUpgrade.TryUpgrade();
halibut.Start();
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<ISystemLog>(), fileSystem, LinuxGeneratedMachineKey.KeyFilePathFor("Tentacle"));
return MachineKeyEncryptor.CreateLinuxEncryptor(Substitute.For<ISystemLog>(), fileSystem, ConfigurationEncryptionKey.KeyFilePathFor("Tentacle"));
}

[TestCaseSource(nameof(WrittenWithTheMachineIdKey))]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<ISystemLog>();
fileSystem = new OctopusPhysicalFileSystem(log);
}
Expand All @@ -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");
}

Expand All @@ -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();

Expand All @@ -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");
}
Expand Down
Loading