Skip to content

Commit

Permalink
#5 Improve folder permissions and AppPool/Website naming.
Browse files Browse the repository at this point in the history
  • Loading branch information
sevensolutions committed Jul 25, 2023
1 parent 2b32db5 commit 4c43ceb
Show file tree
Hide file tree
Showing 5 changed files with 90 additions and 16 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ Feel free to use it as-is or as a reference implementation for your own C#-based
| enabled | bool | no | true | Enables/Disables the Nomad IIS Plugin |
| stats_interval | string | no | 3s | Defines the interval how often the plugin should report driver statistics to Nomad. The smallest possible value is 1s. |
| fingerprint_interval | string | no | 30s | Defines the interval how often the plugin should report the driver's fingerprint to Nomad. The smallest possible value is 10s. |
| directory_security | bool | no | true | Enables Directory Permission Management for [Filesystem Isolation](#-filesystem-isolation). |

**Example**

Expand Down
26 changes: 25 additions & 1 deletion src/NomadIIS/Services/ConfigSchemas.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,31 @@ public static class ConfigSchemas
Required = false
}
}
}
},
{
"directory_security", new Spec()
{
Default = new Default()
{
Primary = new Spec()
{
Attr = new Attr()
{
Name = "directory_security",
Type = "bool",
Required = false
}
},
Default_ = new Spec()
{
Literal = new Literal()
{
Value = "true"
}
}
}
}
},
}
}
};
Expand Down
6 changes: 5 additions & 1 deletion src/NomadIIS/Services/Grpc/BaseService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ public override Task<SetConfigResponse> SetConfig ( SetConfigRequest request, Se
_logger.LogInformation( nameof( SetConfig ) );

var enabled = true;
var directorySecurity = true;
TimeSpan? statsInterval = null;
TimeSpan? fingerprintInterval = null;

Expand Down Expand Up @@ -90,9 +91,12 @@ public override Task<SetConfigResponse> SetConfig ( SetConfigRequest request, Se

fingerprintInterval = interval.Value;
}

if ( config.TryGetValue( "directory_security", out var rawDirectorySecurity ) && rawEnabled is bool vDirectorySecurity )
directorySecurity = vDirectorySecurity;
}

_managementService.Configure( enabled, statsInterval, fingerprintInterval );
_managementService.Configure( enabled, statsInterval, fingerprintInterval, directorySecurity );

return Task.FromResult( new SetConfigResponse() );
}
Expand Down
68 changes: 55 additions & 13 deletions src/NomadIIS/Services/IisTaskHandle.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
using System.Linq;
using System.Security.AccessControl;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

Expand Down Expand Up @@ -190,7 +192,8 @@ await _owner.LockAsync( async serverManager =>
}
} );

SetupDirectoryPermissions();
if ( _owner.DirectorySecurity )
SetupDirectoryPermissions();

await SendTaskEventAsync( $"Application started, Name: {_appPoolName}" );

Expand Down Expand Up @@ -390,7 +393,25 @@ public void Dispose ()
}

private static string GetAppPoolName ( TaskConfig taskConfig )
=> $"{taskConfig.AllocId}-{taskConfig.Name}";
{
var rawName = $"{taskConfig.AllocId}-{taskConfig.Name}";

var invalidChars = ApplicationPoolCollection.InvalidApplicationPoolNameCharacters()
.Union( SiteCollection.InvalidSiteNameCharacters() )
.ToArray();

var sb = new StringBuilder();

foreach ( var c in rawName )
{
if ( invalidChars.Contains( c ) )
sb.Append( '_' );
else
sb.Append( c );
}

return sb.ToString();
}

private ApplicationPool GetApplicationPool ( ServerManager serverManager )
=> FindApplicationPool( serverManager ) ?? throw new KeyNotFoundException( $"No AppPool with name {_appPoolName} found." );
Expand Down Expand Up @@ -421,21 +442,23 @@ private async Task SendTaskEventAsync ( string message )
private void SetupDirectoryPermissions ()
{
// https://developer.hashicorp.com/nomad/docs/concepts/filesystem
// https://learn.microsoft.com/en-us/troubleshoot/developer/webapps/iis/www-authentication-authorization/default-permissions-user-rights
// https://stackoverflow.com/questions/51277338/remove-users-group-permission-for-folder-inside-programdata

#pragma warning disable CA1416 // Plattformkompatibilität überprüfen

var identity = $"IIS AppPool\\{_appPoolName}";

var allocDir = new DirectoryInfo( _taskConfig!.AllocDir );

SetupDirectory( @"alloc\data", FileSystemRights.FullControl );
SetupDirectory( @"alloc\logs", FileSystemRights.FullControl );
SetupDirectory( @"alloc\tmp", FileSystemRights.FullControl );
SetupDirectory( $@"{_taskConfig.Name}\local", FileSystemRights.FullControl );
SetupDirectory( $@"{_taskConfig.Name}\secrets", FileSystemRights.Read );
SetupDirectory( $@"{_taskConfig.Name}\tmp", FileSystemRights.FullControl );

void SetupDirectory( string subDirectory, FileSystemRights fileSystemRights )
SetupDirectory( @"alloc\data", FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit );
SetupDirectory( @"alloc\logs", FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit );
SetupDirectory( @"alloc\tmp", FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit );
SetupDirectory( $@"{_taskConfig.Name}\local", FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit );
SetupDirectory( $@"{_taskConfig.Name}\secrets", FileSystemRights.Read, InheritanceFlags.ObjectInherit );
SetupDirectory( $@"{_taskConfig.Name}\tmp", FileSystemRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit );

void SetupDirectory( string subDirectory, FileSystemRights fileSystemRights, InheritanceFlags inheritanceFlags )
{
var directory = allocDir;

Expand All @@ -447,11 +470,30 @@ void SetupDirectory( string subDirectory, FileSystemRights fileSystemRights )

var acl = directory.GetAccessControl();

// Disable Inheritance and copy existing rules
acl.SetAccessRuleProtection( true, true );
directory.SetAccessControl( acl );

// Re-read the ACL
acl = directory.GetAccessControl();

// Remove unwanted BuiltIn-users/groups which allow access to everyone
var builtinUsersSid = new SecurityIdentifier( WellKnownSidType.BuiltinUsersSid, null );
var authenticatedUserSid = new SecurityIdentifier( WellKnownSidType.AuthenticatedUserSid, null );

foreach ( FileSystemAccessRule rule in acl.GetAccessRules( true, false, typeof( SecurityIdentifier ) ) )
{
if ( rule.IdentityReference == builtinUsersSid || rule.IdentityReference == authenticatedUserSid )
acl.RemoveAccessRule( rule );
}

// Add new Rules
acl.AddAccessRule( new FileSystemAccessRule(
identity, fileSystemRights, InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow ) );
acl.AddAccessRule( new FileSystemAccessRule(
identity, fileSystemRights, InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow ) );
identity, fileSystemRights, inheritanceFlags, PropagationFlags.InheritOnly, AccessControlType.Allow ) );
//acl.AddAccessRule( new FileSystemAccessRule(
// identity, fileSystemRights, InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow ) );

// Apply the new ACL
directory.SetAccessControl( acl );
}

Expand Down
5 changes: 4 additions & 1 deletion src/NomadIIS/Services/ManagementService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ public sealed class ManagementService
private bool _driverEnabled;
private TimeSpan _statsInterval = TimeSpan.FromSeconds( 3 );
private TimeSpan _fingerprintInterval = TimeSpan.FromSeconds( 30 );
private bool _directorySecurity;
private readonly ConcurrentDictionary<string, IisTaskHandle> _handles = new();
private readonly SemaphoreSlim _lock = new( 1, 1 );
private readonly Channel<DriverTaskEvent> _eventsChannel = Channel.CreateUnbounded<DriverTaskEvent>( new UnboundedChannelOptions()
Expand All @@ -33,12 +34,14 @@ public ManagementService ( ILogger<ManagementService> logger )
public bool DriverEnabled => _driverEnabled;
public TimeSpan StatsInterval => _statsInterval;
public TimeSpan FingerprintInterval => _fingerprintInterval;
public bool DirectorySecurity => _directorySecurity;

public void Configure ( bool enabled, TimeSpan? statsInterval, TimeSpan? fingerprintInterval )
public void Configure ( bool enabled, TimeSpan? statsInterval, TimeSpan? fingerprintInterval, bool directorySecurity )
{
_driverEnabled = enabled;
_statsInterval = statsInterval ?? _statsInterval;
_fingerprintInterval = fingerprintInterval ?? _fingerprintInterval;
_directorySecurity = directorySecurity;
}

public IisTaskHandle CreateHandle ( string taskId )
Expand Down

0 comments on commit 4c43ceb

Please sign in to comment.