Skip to content

Commit

Permalink
Customization: Add general system and virtualization feature settings (
Browse files Browse the repository at this point in the history
…#3268)

* Windows Customization: Add general system and virtualization feature settings

    - Updates `ManagementInfrastructureHelper.cs` for enhanced Windows feature management, including a refactored method for checking feature availability with modifications to return more detailed feature information.
    - Introduced a `RestartHelper.cs` class with a method to restart the computer immediately, to avoid disruption I did not point existing callers from Environments to this method since they have additional telemetry for this space. I can file an issue to track consolidation here.
    - Updated `WindowsIdentityHelper.cs` with a new method to check for whether a user has the capability to acquire administrative privileges, not just whether the current process is running elevated.
    - Added `WindowsOptionalFeatures.cs` and `WindowsOptionalFeatureState.cs` to represent Windows optional features, including a new static class for feature names and descriptions and a class to represent the state of an optional feature, specifically for UI.
    - Introduced `ModifyLongPathsSetting.cs` and `ModifyWindowsOptionalFeatures.cs` for enabling/disabling Windows settings and optional features through PowerShell scripts which require elevation. This allows the full script content to be visible to the user when accepting or rejecting the UAC prompt providing extra transparency, this is done in the same way as environments feature management. There are limitations here in that if scripts are blocked on the machine we're unable to make this changes, but until we finish security review on the elevated server, this is the best we've got.
    - Expanded Windows Customization with new views and dialogs for managing general system settings and virtualization features, including `GeneralSystemView`, `ModifyFeaturesDialog`, and `VirtualizationFeatureManagementPage`, alongside updates to existing views to accommodate these new features.
  • Loading branch information
nieubank authored Jun 25, 2024
1 parent 569d533 commit 7f01cdc
Show file tree
Hide file tree
Showing 29 changed files with 1,530 additions and 61 deletions.
22 changes: 20 additions & 2 deletions common/Helpers/ManagementInfrastructureHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System;
using Microsoft.Management.Infrastructure;
using Serilog;
using static DevHome.Common.Helpers.WindowsOptionalFeatures;

namespace DevHome.Common.Helpers;

Expand All @@ -22,6 +23,11 @@ public static class ManagementInfrastructureHelper
private static readonly ILogger _log = Log.ForContext("SourceContext", nameof(ManagementInfrastructureHelper));

public static FeatureAvailabilityKind IsWindowsFeatureAvailable(string featureName)
{
return GetWindowsFeatureDetails(featureName)?.AvailabilityKind ?? FeatureAvailabilityKind.Unknown;
}

public static FeatureInfo? GetWindowsFeatureDetails(string featureName)
{
try
{
Expand All @@ -36,7 +42,19 @@ public static FeatureAvailabilityKind IsWindowsFeatureAvailable(string featureNa
var featureAvailability = GetAvailabilityKindFromState(installState);

_log.Information($"Found feature: '{featureName}' with enablement state: '{featureAvailability}'");
return featureAvailability;

// Most optional features do not have a description, so we provide one for known features
var description = featureInstance.CimInstanceProperties["Description"]?.Value as string ?? string.Empty;
if (string.IsNullOrEmpty(description) && WindowsOptionalFeatures.FeatureDescriptions.TryGetValue(featureName, out var featureDescription))
{
description = featureDescription;
}

return new FeatureInfo(
featureName,
featureInstance.CimInstanceProperties["Caption"]?.Value as string ?? featureName,
description,
featureAvailability);
}
}
}
Expand All @@ -46,7 +64,7 @@ public static FeatureAvailabilityKind IsWindowsFeatureAvailable(string featureNa
}

_log.Information($"Unable to get state of {featureName} feature");
return FeatureAvailabilityKind.Unknown;
return null;
}

private static FeatureAvailabilityKind GetAvailabilityKindFromState(uint state)
Expand Down
29 changes: 29 additions & 0 deletions common/Helpers/RestartHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.Diagnostics;
using CommunityToolkit.Mvvm.Input;

namespace DevHome.Common.Helpers;

public partial class RestartHelper
{
[RelayCommand]
public static void RestartComputer()
{
var startInfo = new ProcessStartInfo
{
WindowStyle = ProcessWindowStyle.Hidden,
FileName = Environment.SystemDirectory + "\\shutdown.exe",
Arguments = "-r -t 0",
Verb = string.Empty,
};

var process = new Process
{
StartInfo = startInfo,
};
process.Start();
}
}
10 changes: 10 additions & 0 deletions common/Helpers/WindowsIdentityHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,14 @@ public virtual bool IsUserHyperVAdmin()
{
return _currentUserIdentity?.Name;
}

// Returns true if the current user has the built-in Administrators claim indicating that
// they could elevate to an administrator role via UAC if needed. Does not check if the process
// is running elevated.
public virtual bool IsUserAdministrator()
{
using WindowsIdentity identity = WindowsIdentity.GetCurrent();
var adminSid = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null).Value;
return identity.Claims.Any(c => c.Value == adminSid);
}
}
77 changes: 77 additions & 0 deletions common/Helpers/WindowsOptionalFeatures.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System.Collections.Generic;
using DevHome.Common.Environments.Helpers;

namespace DevHome.Common.Helpers;

public static class WindowsOptionalFeatures
{
// If changes are made to the set of features here, consider updating ModifyWindowsOptionalFeatures' valid feature set.
public const string Containers = "Containers";
public const string GuardedHost = "HostGuardian";
public const string HyperV = "Microsoft-Hyper-V-All";
public const string HyperVManagementTools = "Microsoft-Hyper-V-Tools-All";
public const string HyperVPlatform = "Microsoft-Hyper-V";
public const string VirtualMachinePlatform = "VirtualMachinePlatform";
public const string WindowsHypervisorPlatform = "HypervisorPlatform";
public const string WindowsSandbox = "Containers-DisposableClientVM";
public const string WindowsSubsystemForLinux = "Microsoft-Windows-Subsystem-Linux";

public static IEnumerable<string> VirtualMachineFeatures => new[]
{
Containers,
GuardedHost,
HyperV,
HyperVManagementTools,
HyperVPlatform,
VirtualMachinePlatform,
WindowsHypervisorPlatform,
WindowsSandbox,
WindowsSubsystemForLinux,
};

public static readonly Dictionary<string, string> FeatureDescriptions = new()
{
{ Containers, GetFeatureDescription(nameof(Containers)) },
{ GuardedHost, GetFeatureDescription(nameof(GuardedHost)) },
{ HyperV, GetFeatureDescription(nameof(HyperV)) },
{ HyperVManagementTools, GetFeatureDescription(nameof(HyperVManagementTools)) },
{ HyperVPlatform, GetFeatureDescription(nameof(HyperVPlatform)) },
{ VirtualMachinePlatform, GetFeatureDescription(nameof(VirtualMachinePlatform)) },
{ WindowsHypervisorPlatform, GetFeatureDescription(nameof(WindowsHypervisorPlatform)) },
{ WindowsSandbox, GetFeatureDescription(nameof(WindowsSandbox)) },
{ WindowsSubsystemForLinux, GetFeatureDescription(nameof(WindowsSubsystemForLinux)) },
};

private static string GetFeatureDescription(string featureName)
{
return StringResourceHelper.GetResource(featureName + "Description");
}

public class FeatureInfo
{
public string FeatureName { get; set; }

public string DisplayName { get; set; }

public string Description { get; set; }

public bool IsEnabled { get; set; }

public bool IsAvailable { get; set; }

public FeatureAvailabilityKind AvailabilityKind { get; set; }

public FeatureInfo(string featureName, string displayName, string description, FeatureAvailabilityKind availabilityKind)
{
FeatureName = featureName;
DisplayName = displayName;
Description = description;
AvailabilityKind = availabilityKind;
IsEnabled = AvailabilityKind == FeatureAvailabilityKind.Enabled;
IsAvailable = AvailabilityKind == FeatureAvailabilityKind.Enabled || AvailabilityKind == FeatureAvailabilityKind.Disabled;
}
}
}
28 changes: 28 additions & 0 deletions common/Models/WindowsOptionalFeatureState.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using CommunityToolkit.Mvvm.ComponentModel;
using static DevHome.Common.Helpers.WindowsOptionalFeatures;

namespace DevHome.Common.Models;

public partial class WindowsOptionalFeatureState : ObservableObject
{
public FeatureInfo Feature { get; }

[ObservableProperty]
private bool _isModifiable;

[ObservableProperty]
[NotifyPropertyChangedFor(nameof(HasChanged))]
private bool _isEnabled;

public bool HasChanged => IsEnabled != Feature.IsEnabled;

public WindowsOptionalFeatureState(FeatureInfo feature, bool modifiable)
{
Feature = feature;
IsEnabled = feature.IsEnabled;
IsModifiable = modifiable;
}
}
69 changes: 69 additions & 0 deletions common/Scripts/ModifyLongPathsSetting.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.Diagnostics;
using Serilog;

namespace DevHome.Common.Scripts;

public static class ModifyLongPathsSetting
{
public static ExitCode ModifyLongPaths(bool enabled, ILogger? log = null)
{
var scriptString = enabled ? EnableScript : DisableScript;
var process = new Process
{
StartInfo = new ProcessStartInfo
{
WindowStyle = ProcessWindowStyle.Hidden,
FileName = "powershell.exe",
Arguments = $"-ExecutionPolicy Bypass -Command {scriptString}",
UseShellExecute = true,
Verb = "runas",
},
};

try
{
process.Start();
process.WaitForExit();

return FromExitCode(process.ExitCode);
}
catch (Exception ex)
{
log?.Error(ex, "Failed to modify Long Paths setting");
return ExitCode.Failure;
}
}

public enum ExitCode
{
Success = 0,
Failure = 1,
}

private static ExitCode FromExitCode(int exitCode)
{
return exitCode switch
{
0 => ExitCode.Success,
_ => ExitCode.Failure,
};
}

private const string EnableScript =
@"
$ErrorActionPreference='stop'
Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem' -Name 'LongPathsEnabled' -Value 1
if ($?) { exit 0 } else { exit 1 }
";

private const string DisableScript =
@"
$ErrorActionPreference='stop'
Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem' -Name 'LongPathsEnabled' -Value 0
if ($?) { exit 0 } else { exit 1 }
";
}
Loading

0 comments on commit 7f01cdc

Please sign in to comment.