-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWindowsSecurityService.cs
More file actions
76 lines (63 loc) · 2.98 KB
/
WindowsSecurityService.cs
File metadata and controls
76 lines (63 loc) · 2.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
using System.Diagnostics;
namespace FlatCopyProfileExporter;
internal sealed record BitLockerCheckResult(
bool CheckedSuccessfully,
bool IsProtected,
string VolumeRoot,
string Details);
internal static class WindowsSecurityService
{
public static BitLockerCheckResult GetBitLockerProtectionStatus(string destinationRoot)
{
string volumeRoot = GetVolumeRoot(destinationRoot);
if (string.IsNullOrWhiteSpace(volumeRoot))
{
return new BitLockerCheckResult(false, false, destinationRoot, "The destination drive root could not be determined.");
}
try
{
ProcessStartInfo startInfo = new()
{
FileName = "powershell.exe",
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
startInfo.ArgumentList.Add("-NoProfile");
startInfo.ArgumentList.Add("-NonInteractive");
startInfo.ArgumentList.Add("-ExecutionPolicy");
startInfo.ArgumentList.Add("Bypass");
startInfo.ArgumentList.Add("-Command");
startInfo.ArgumentList.Add($"$ErrorActionPreference='Stop'; $vol = Get-BitLockerVolume -MountPoint '{volumeRoot.Replace("'", "''")}'; if ($null -eq $vol) {{ '-1' }} else {{ [int]$vol.ProtectionStatus }}");
using Process process = Process.Start(startInfo)
?? throw new InvalidOperationException("Unable to start PowerShell for BitLocker verification.");
string standardOutput = process.StandardOutput.ReadToEnd().Trim();
string standardError = process.StandardError.ReadToEnd().Trim();
process.WaitForExit();
if (process.ExitCode != 0)
{
return new BitLockerCheckResult(false, false, volumeRoot, string.IsNullOrWhiteSpace(standardError) ? "BitLocker verification command failed." : standardError);
}
bool isProtected = standardOutput == "1";
bool checkedSuccessfully = standardOutput is "0" or "1";
string details = checkedSuccessfully
? (isProtected ? "BitLocker protection is enabled on the destination drive." : "BitLocker protection is not enabled on the destination drive.")
: $"Unexpected BitLocker status value: {standardOutput}";
return new BitLockerCheckResult(checkedSuccessfully, isProtected, volumeRoot, details);
}
catch (Exception exception)
{
return new BitLockerCheckResult(false, false, volumeRoot, exception.Message);
}
}
private static string GetVolumeRoot(string path)
{
if (string.IsNullOrWhiteSpace(path))
{
return string.Empty;
}
string fullPath = Path.GetFullPath(path);
return Path.GetPathRoot(fullPath)?.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) ?? string.Empty;
}
}