Skip to content

Commit

Permalink
Fixed bug (#10)
Browse files Browse the repository at this point in the history
  • Loading branch information
Gitii authored Feb 23, 2022
1 parent 3020acb commit 8d100ca
Show file tree
Hide file tree
Showing 9 changed files with 76 additions and 21 deletions.
2 changes: 2 additions & 0 deletions MakePolicyFromApp/MakePolicyFromApp.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
<PackageLicenseFile>LICENSE</PackageLicenseFile>
<PackageRequireLicenseAcceptance>True</PackageRequireLicenseAcceptance>
<Platforms>AnyCPU;ARM64;ARM32;x64;x86</Platforms>
<EnableUnsafeBinaryFormatterSerialization>true</EnableUnsafeBinaryFormatterSerialization>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
Expand Down Expand Up @@ -57,6 +58,7 @@
<PackageReference Include="ConsoleTables" Version="2.4.2" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="5.0.0" />
<PackageReference Include="Microsoft.PowerShell.SDK" Version="7.1.4" />
<PackageReference Include="ObjectPrinter" Version="2.0.35" />
<PackageReference Include="System.CommandLine" Version="2.0.0-beta3.22114.1" />
<PackageReference Include="System.CommandLine.NamingConventionBinder" Version="2.0.0-beta3.22114.1" />
<PackageReference Include="System.IO.Compression.ZipFile" Version="4.3.0" />
Expand Down
6 changes: 5 additions & 1 deletion MakePolicyFromApp/Operations/Generate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,16 @@ public async Task StartAsync(GenerateArguments args)

var generatedPolicy = await Policy.GenerateAsync(rootDirectory).ConfigureAwait(false);

var contextName = args.ContextName ?? GetContextNameFromFile(args.InputFile);
var contextName = string.IsNullOrEmpty(args.ContextName)
? GetContextNameFromFile(args.InputFile)
: args.ContextName;

var betterPolicy = await Policy
.MakePolicyHumanReadableAsync(generatedPolicy, rootDirectory, contextName)
.ConfigureAwait(false);

betterPolicy = Policy.RemoveRules(betterPolicy);

await WriteOutputAsync(betterPolicy, args.OutputFile).ConfigureAwait(false);
}
finally
Expand Down
5 changes: 3 additions & 2 deletions MakePolicyFromApp/Properties/PublishProfiles/win-arm64.pubxml
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ https://go.microsoft.com/fwlink/?LinkID=208121.
<PublishProtocol>FileSystem</PublishProtocol>
<TargetFramework>net6.0-windows10.0.20348.0</TargetFramework>
<RuntimeIdentifier>win-arm64</RuntimeIdentifier>
<SelfContained>false</SelfContained>
<PublishSingleFile>True</PublishSingleFile>
<SelfContained>true</SelfContained>
<PublishSingleFile>False</PublishSingleFile>
<PublishReadyToRun>True</PublishReadyToRun>
<PublishTrimmed>True</PublishTrimmed>
</PropertyGroup>
</Project>
11 changes: 6 additions & 5 deletions MakePolicyFromApp/Properties/PublishProfiles/win-x64.pubxml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
Expand All @@ -9,9 +9,10 @@ https://go.microsoft.com/fwlink/?LinkID=208121.
<PublishDir>bin\Release\publish\win-x64</PublishDir>
<PublishProtocol>FileSystem</PublishProtocol>
<TargetFramework>net6.0-windows10.0.20348.0</TargetFramework>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<SelfContained>false</SelfContained>
<PublishSingleFile>True</PublishSingleFile>
<RuntimeIdentifier>win10-x64</RuntimeIdentifier>
<SelfContained>true</SelfContained>
<PublishSingleFile>False</PublishSingleFile>
<PublishReadyToRun>True</PublishReadyToRun>
<PublishTrimmed>True</PublishTrimmed>
</PropertyGroup>
</Project>
</Project>
5 changes: 3 additions & 2 deletions MakePolicyFromApp/Properties/PublishProfiles/win-x86.pubxml
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ https://go.microsoft.com/fwlink/?LinkID=208121.
<PublishProtocol>FileSystem</PublishProtocol>
<TargetFramework>net6.0-windows10.0.20348.0</TargetFramework>
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
<SelfContained>false</SelfContained>
<PublishSingleFile>True</PublishSingleFile>
<SelfContained>true</SelfContained>
<PublishSingleFile>False</PublishSingleFile>
<PublishReadyToRun>True</PublishReadyToRun>
<PublishTrimmed>True</PublishTrimmed>
</PropertyGroup>
</Project>
2 changes: 2 additions & 0 deletions MakePolicyFromApp/Services/IPolicy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,6 @@ Task<string> MakePolicyHumanReadableAsync(
string contextDirectory,
string contextName
);

string RemoveRules(string policyContent);
}
13 changes: 13 additions & 0 deletions MakePolicyFromApp/Services/Policy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,19 @@ await _powershell
}
}

public string RemoveRules(string policyContent)
{
XDocument policyXml = XDocument.Parse(policyContent);

var siPolicy = policyXml.Root!;
var ns = siPolicy.Name.NamespaceName;
var rules = siPolicy.Element(XName.Get("Rules", ns))!;

rules.RemoveAll();

return policyXml.ToString();
}

public Task<string> MakePolicyHumanReadableAsync(
string policyContent,
string contextDirectory,
Expand Down
47 changes: 39 additions & 8 deletions MakePolicyFromApp/Services/Powershell.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,24 @@
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.PowerShell;
using ObjectPrinter;

namespace MakePolicyFromApp.Services;

public class Powershell : IPowershell
{
private readonly ILogger<IPowershell> _logger;

public Powershell(ILogger<IPowershell> logger)
{
_logger = logger;
}

#pragma warning disable MA0051 // Method is too long
public async Task ExecuteCommandAsync(
#pragma warning restore MA0051 // Method is too long
string command,
IDictionary<string, object> arguments,
IEnumerable<string> modules
Expand All @@ -20,7 +31,7 @@ IEnumerable<string> modules
InitialSessionState initialSessionState = InitialSessionState.CreateDefault();
initialSessionState.ExecutionPolicy = ExecutionPolicy.Unrestricted;

// Create a runspace and open it. This example uses C#8 simplified using statements
// Create a runspace and open it.
using Runspace runspace = RunspaceFactory.CreateRunspace(initialSessionState);
runspace.Open();

Expand Down Expand Up @@ -50,16 +61,36 @@ IEnumerable<string> modules

runtime.AddStatement();

await runtime.InvokeAsync().ConfigureAwait(false);

if (runtime.HadErrors)
try
{
await runtime.InvokeAsync().ConfigureAwait(false);
}
catch (RuntimeException runtimeException)
{
var stdError = String.Join(
Environment.NewLine,
runtime.Streams.Error.Select((o) => o.ToString())
_logger.Log(
LogLevel.Error,
"Runtime exception: {0}: {1}\n{2}\n{3}",
runtimeException.ErrorRecord.InvocationInfo.InvocationName,
runtimeException.Message,
runtimeException.ErrorRecord.Exception.DumpToString(),
runtimeException.ErrorRecord.ErrorDetails.DumpToString()
);
}
catch (Exception e)
{
_logger.Log(LogLevel.Error, $"Failed to invoke powershell session: {e.Message}\n{e}");
}
finally
{
if (runtime.HadErrors)
{
var stdError = String.Join(
Environment.NewLine,
runtime.Streams.Error.Select((o) => o.ToString())
);

throw new Exception($"Failed to execute powershell command {command}: " + stdError);
throw new Exception($"Failed to execute powershell command {command}: " + stdError);
}
}
}
}
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
<a href="https://github.com/Gitii/MakePolicyFromApp"><strong>Explore the docs »</strong></a>
<br />
<br />
<a href="https://github.com/Gitii/MakePolicyFromApp/issues">Report Bug</a>·
<a href="https://github.com/Gitii/MakePolicyFromApp/issues">Report Bug</a> ·
<a href="https://github.com/Gitii/MakePolicyFromApp/issues">Request Feature</a>
</p>
</p>
Expand Down Expand Up @@ -90,10 +90,10 @@ The values of `FriendlyName` & `ID` attributes will be changed for better readab
## Getting Started

To start using `MakePolicyFromApp` as fast as possible, [download](https://github.com/Gitii/MakePolicyFromApp/releases) the latest release from this project page.
.Net 6 is required and can be downloaded from the [official .Net SDK website](https://dotnet.microsoft.com/en-us/download/dotnet/6.0).
You do **not** need any runtime enviroment because it's a self-contained applications and framework-independent.

### Prerequisites
* Windows 10 10.0.17763.0 **Pro** or newer
* Windows 10 10.0.17763.0 **Pro** or higher

> **⚠️** WDAC is only supported on PRO or higher
Expand Down

0 comments on commit 8d100ca

Please sign in to comment.