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
@@ -0,0 +1,41 @@
#if NET
using System;
using System.IO;
using System.Linq;
using System.Runtime.Versioning;
using System.Threading.Tasks;
using FluentAssertions;
using NUnit.Framework;
using Octopus.Tentacle.CommonTestUtils.Diagnostics;
using Octopus.Tentacle.Configuration;
using Octopus.Tentacle.Tests.Integration.Support.TestAttributes;
using Octopus.Tentacle.Tests.Integration.Util;
using Octopus.Tentacle.Util;

namespace Octopus.Tentacle.Tests.Integration.Configuration
{
[TestFixture]
[LinuxTest]
[NonParallelizable]
[UnsupportedOSPlatform("windows")]
public class ConfigurationFilePermissionsFixture
{
[Test]
[RequiresSudoOnLinux]
public async Task WhenRestrictedToTheServiceUserThenOnlyThatUserOwnsAndCanReadTheConfig()
{
var user = new LinuxTestUserPrincipal("octo-config-perm-test");
var configurationFile = Path.GetTempFileName();
File.SetUnixFileMode(configurationFile, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead | UnixFileMode.OtherRead);
var log = new InMemoryLog();

ConfigurationFilePermissions.RestrictToServiceUser(configurationFile, user.UserName, log);

log.GetLog().Should().NotContain("Unable to restrict");
File.GetUnixFileMode(configurationFile).Should().Be(ConfigurationFilePermissions.OwnerOnly);
var owner = await new CommandLineInvocation("/bin/bash", $"-c \"stat -c '%U' {configurationFile}\"").ExecuteCommandAsync();
owner.Infos.Single().Should().Be(user.UserName);
}
}
}
#endif
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
#if NET
using System;
using System.IO;
using System.Runtime.Versioning;
using FluentAssertions;
using NUnit.Framework;
using Octopus.Tentacle.Configuration;
using Octopus.Tentacle.Tests.Support;
using Octopus.Tentacle.Util;

namespace Octopus.Tentacle.Tests.Configuration
{
[TestFixture]
[UnsupportedOSPlatform("windows")]
public class ConfigurationFilePermissionsFixture
{
[SetUp]
public void SkipOnWindows()
{
if (OperatingSystem.IsWindows())
{
Assert.Ignore("Unix file modes only");
}
}

[Test]
public void WhenAWorldReadableConfigIsRestrictedThenOnlyItsOwnerCanReadIt()
{
var configurationFile = Path.GetTempFileName();
File.SetUnixFileMode(configurationFile, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.GroupRead | UnixFileMode.OtherRead);

ConfigurationFilePermissions.RestrictToOwner(configurationFile, new InMemoryLog());

File.GetUnixFileMode(configurationFile).Should().Be(ConfigurationFilePermissions.OwnerOnly);
}

[Test]
public void WhenAnEmptyConfigIsCreatedThenOnlyItsOwnerCanReadIt()
{
var configurationFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

ConfigurationFilePermissions.CreateEmpty(new OctopusPhysicalFileSystem(new InMemoryLog()), configurationFile, "<octopus-settings />");

File.GetUnixFileMode(configurationFile).Should().Be(ConfigurationFilePermissions.OwnerOnly);
}

[Test]
public void WhenTheConfigIsASymlinkThenItIsNotGivenToTheServiceUser()
{
var target = Path.GetTempFileName();
var configurationFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
File.CreateSymbolicLink(configurationFile, target);
var log = new InMemoryLog();

ConfigurationFilePermissions.RestrictToServiceUser(configurationFile, "nobody", log);

log.GetLog().Should().Contain("symbolic link");
}
}
}
#endif
1 change: 1 addition & 0 deletions source/Octopus.Tentacle/Commands/RunAgentCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ protected override void Start()
Environment.SetEnvironmentVariable(EnvironmentVariables.TentacleProxyPort, proxyConfiguration.Value.CustomProxyPort.ToString());

LogWarningIfNotRunningAsAdministrator();
ConfigurationFilePermissions.RestrictToOwner(selector.Current.ConfigurationPath, log);

proxyInitializer.Value.InitializeProxy();

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
using System;
using System.IO;
using Octopus.Tentacle.Core.Diagnostics;
using Octopus.Tentacle.Util;
#if NET
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using Microsoft.Win32.SafeHandles;
#endif

namespace Octopus.Tentacle.Configuration
{
// The config holds protected settings, so only its owner may read it. The service user must therefore own it.
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)
{
#if NET
if (!OperatingSystem.IsWindows())
{
using var stream = new FileStream(configurationPath, new FileStreamOptions
{
Mode = FileMode.CreateNew,
Access = FileAccess.Write,
UnixCreateMode = OwnerOnly
});
using var writer = new StreamWriter(stream);
writer.Write(contents);
return;
}
#endif
fileSystem.OverwriteFile(configurationPath, contents);
}

public static void RestrictToOwner(string? configurationPath, ISystemLog log)
{
#if NET
if (OperatingSystem.IsWindows() || string.IsNullOrWhiteSpace(configurationPath) || !File.Exists(configurationPath))
{
return;
}

try
{
var previousMode = File.GetUnixFileMode(configurationPath);
if (previousMode != OwnerOnly)
{
File.SetUnixFileMode(configurationPath, OwnerOnly);
log.Info($"Restricted `{configurationPath}` from {Convert.ToString((int)previousMode, 8).PadLeft(4, '0')} to 0600");
}
}
catch (Exception ex) when (ex is UnauthorizedAccessException or IOException)
{
log.Warn($"Unable to restrict `{configurationPath}` to its owner, so other users may be able to read it: {ex.Message}");
}
#endif
}

public static void RestrictToServiceUser(string? configurationPath, string? userName, ISystemLog log)
{
#if NET
if (OperatingSystem.IsWindows()
|| string.IsNullOrWhiteSpace(configurationPath)
|| string.IsNullOrWhiteSpace(userName)
|| userName == "root")
{
return;
}

var error = TryRestrictToServiceUser(configurationPath, userName);
if (error != null)
{
log.Warn($"Unable to restrict `{configurationPath}` to `{userName}`: {error.TrimEnd('.')}. Only the service user should be able to read and write the configuration file, so check its owner and permissions.");
}
#endif
}

#if NET
[UnsupportedOSPlatform("windows")]
static string? TryRestrictToServiceUser(string configurationPath, string userName)
{
try
{
if (new FileInfo(configurationPath).LinkTarget != null)
{
return $"`{configurationPath}` is a symbolic link.";
}

var userId = GetUserId(userName);
if (userId == null)
{
return $"Unable to find the user `{userName}`.";
Comment on lines +90 to +98

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Agent's comment, endorsed by Rhys

Nit: braces on these guards, and on the StartsWith("-") guard at line 46 if that survives the getpwnam change.

Suggested change
if (new FileInfo(configurationPath).LinkTarget != null)
return $"`{configurationPath}` is a symbolic link.";
var userId = UserId(userName);
if (userId == null)
return $"Unable to find the user `{userName}`.";
if (new FileInfo(configurationPath).LinkTarget != null)
{
return $"`{configurationPath}` is a symbolic link.";
}
var userId = UserId(userName);
if (userId == null)
{
return $"Unable to find the user `{userName}`.";
}

Rhys: I've always held this stance, but feel free to disagree.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lets do it.

}

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();
}
catch (Exception ex)
{
return ex.Message;
}
}

static uint? GetUserId(string userName)
{
if (userName.StartsWith("-", StringComparison.Ordinal))
{
return null;
}

try
{
var startInfo = new ProcessStartInfo("id") { UseShellExecute = false, RedirectStandardOutput = true };
startInfo.ArgumentList.Add("-u");
startInfo.ArgumentList.Add(userName);
using var process = Process.Start(startInfo)!;
var output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
return process.ExitCode == 0 && uint.TryParse(output.Trim(), out var userId) ? userId : null;
}
catch (Exception)
{
return null;
}
}

[DllImport("libc", SetLastError = true)]
static extern int fchown(SafeFileHandle fd, uint owner, uint group);
#endif
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ void EnsureConfigurationFileExists(string configurationFile, string homeDirector
if (!fileSystem.FileExists(configurationFile))
{
log.Info("Creating empty configuration file: " + configurationFile);
fileSystem.OverwriteFile(configurationFile, @"<?xml version='1.0' encoding='UTF-8' ?><octopus-settings></octopus-settings>");
ConfigurationFilePermissions.CreateEmpty(fileSystem, configurationFile, @"<?xml version='1.0' encoding='UTF-8' ?><octopus-settings></octopus-settings>");
}
else
{
Expand Down
5 changes: 5 additions & 0 deletions source/Octopus.Tentacle/Startup/ServiceCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,11 @@ protected override void Start()
serviceDescription,
serviceConfigurationState);
}

if (serviceConfigurationState.Install || serviceConfigurationState.Reconfigure)
{
ConfigurationFilePermissions.RestrictToServiceUser(instanceSelector.Current.ConfigurationPath, serviceConfigurationState.Username, log);
}
}
}
}
Expand Down