<commit_before>// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//
//  Application white listing policies such as AppLocker and DeviceGuard UMCI are only implemented on Windows OSs
//
#if !UNIX

using System.Management.Automation.Internal;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;

namespace System.Management.Automation.Security
{
    /// <summary>
    /// How the policy is being enforced.
    /// </summary>
    // Internal Note: Current code that consumes this enum assumes that anything but 'Enforce' means
    // that the script is allowed, and that a system lockdown policy that is anything but 'None' means
    // that the API should be called again for individual files. If any elements are added to this enum,
    // callers of the GetLockdownPolicy() should be reviewed.
    public enum SystemEnforcementMode
    {
        /// Not enforced at all
        None = 0,

        /// Enabled - allow, but audit
        Audit = 1,

        /// Enabled, enforce restrictions
        Enforce = 2
    }

    /// <summary>
    /// Support class for dealing with the Windows Lockdown Policy,
    /// Device Guard, and Constrained PowerShell.
    /// </summary>
    public sealed class SystemPolicy
    {
        private SystemPolicy()
        {
        }

        /// <summary>
        /// Gets the system lockdown policy.
        /// </summary>
        /// <returns>An EnforcementMode that describes the system policy.</returns>
        public static SystemEnforcementMode GetSystemLockdownPolicy()
        {
            if (s_systemLockdownPolicy == null)
            {
                lock (s_systemLockdownPolicyLock)
                {
                    if (s_systemLockdownPolicy == null)
                    {
                        s_systemLockdownPolicy = GetLockdownPolicy(path: null, handle: null);
                    }
                }
            }
            else if (s_allowDebugOverridePolicy)
            {
                lock (s_systemLockdownPolicyLock)
                {
                    s_systemLockdownPolicy = GetDebugLockdownPolicy(path: null);
                }
            }

            return s_systemLockdownPolicy.Value;
        }

        private static object s_systemLockdownPolicyLock = new object();
        private static SystemEnforcementMode? s_systemLockdownPolicy = null;
        private static bool s_allowDebugOverridePolicy = false;

        /// <summary>
        /// Gets lockdown policy as applied to a file.
        /// </summary>
        /// <returns>An EnforcementMode that describes policy.</returns>
        public static SystemEnforcementMode GetLockdownPolicy(string path, SafeHandle handle)
        {
            // Check the WLDP API
            SystemEnforcementMode lockdownPolicy = GetWldpPolicy(path, handle);
            if (lockdownPolicy == SystemEnforcementMode.Enforce)
            {
                return lockdownPolicy;
            }

            // At this point, LockdownPolicy = Audit or Allowed.
            // If there was a WLDP policy, but WLDP didn't block it,
            // then it was explicitly allowed. Therefore, return the result for the file.
            SystemEnforcementMode systemWldpPolicy = s_cachedWldpSystemPolicy.GetValueOrDefault(SystemEnforcementMode.None);
            if ((systemWldpPolicy == SystemEnforcementMode.Enforce) ||
                (systemWldpPolicy == SystemEnforcementMode.Audit))
            {
                return lockdownPolicy;
            }

            // Check the AppLocker API
            lockdownPolicy = GetAppLockerPolicy(path, handle);
            if (lockdownPolicy == SystemEnforcementMode.Enforce)
            {
                return lockdownPolicy;
            }

            // If there was a system-wide AppLocker policy, but AppLocker didn't block it,
            // then return AppLocker's status.
            if (s_cachedSaferSystemPolicy.GetValueOrDefault(SaferPolicy.Allowed) ==
                SaferPolicy.Disallowed)
            {
                return lockdownPolicy;
            }

            // If it's not set to 'Enforce' by the platform, allow debug overrides
            return GetDebugLockdownPolicy(path);
        }

        [SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods",
            MessageId = "System.Runtime.InteropServices.SafeHandle.DangerousGetHandle")]
        private static SystemEnforcementMode GetWldpPolicy(string path, SafeHandle handle)
        {
            // If the WLDP assembly is missing (such as windows 7 or down OS), return default/None to skip WLDP validation
            if (s_hadMissingWldpAssembly)
            {
                return s_cachedWldpSystemPolicy.GetValueOrDefault(SystemEnforcementMode.None);
            }

            // If path is NULL, see if we have the cached system-wide lockdown policy.
            if (string.IsNullOrEmpty(path))
            {
                if ((s_cachedWldpSystemPolicy != null) && (!InternalTestHooks.BypassAppLockerPolicyCaching))
                {
                    return s_cachedWldpSystemPolicy.Value;
                }
            }

            try
            {
                WLDP_HOST_INFORMATION hostInformation = new WLDP_HOST_INFORMATION();
                hostInformation.dwRevision = WldpNativeConstants.WLDP_HOST_INFORMATION_REVISION;
                hostInformation.dwHostId = WLDP_HOST_ID.WLDP_HOST_ID_POWERSHELL;
<commit_msg>Make AppLocker Enforce mode take precedence over UMCI Audit mode (#14353)<commit_after>// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//
//  Application white listing policies such as AppLocker and DeviceGuard UMCI are only implemented on Windows OSs
//
#if !UNIX

using System.Management.Automation.Internal;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;

namespace System.Management.Automation.Security
{
    /// <summary>
    /// How the policy is being enforced.
    /// </summary>
    // Internal Note: Current code that consumes this enum assumes that anything but 'Enforce' means
    // that the script is allowed, and that a system lockdown policy that is anything but 'None' means
    // that the API should be called again for individual files. If any elements are added to this enum,
    // callers of the GetLockdownPolicy() should be reviewed.
    public enum SystemEnforcementMode
    {
        /// Not enforced at all
        None = 0,

        /// Enabled - allow, but audit
        Audit = 1,

        /// Enabled, enforce restrictions
        Enforce = 2
    }

    /// <summary>
    /// Support class for dealing with the Windows Lockdown Policy,
    /// Device Guard, and Constrained PowerShell.
    /// </summary>
    public sealed class SystemPolicy
    {
        private SystemPolicy()
        {
        }

        /// <summary>
        /// Gets the system lockdown policy.
        /// </summary>
        /// <returns>An EnforcementMode that describes the system policy.</returns>
        public static SystemEnforcementMode GetSystemLockdownPolicy()
        {
            if (s_systemLockdownPolicy == null)
            {
                lock (s_systemLockdownPolicyLock)
                {
                    if (s_systemLockdownPolicy == null)
                    {
                        s_systemLockdownPolicy = GetLockdownPolicy(path: null, handle: null);
                    }
                }
            }
            else if (s_allowDebugOverridePolicy)
            {
                lock (s_systemLockdownPolicyLock)
                {
                    s_systemLockdownPolicy = GetDebugLockdownPolicy(path: null);
                }
            }

            return s_systemLockdownPolicy.Value;
        }

        private static object s_systemLockdownPolicyLock = new object();
        private static SystemEnforcementMode? s_systemLockdownPolicy = null;
        private static bool s_allowDebugOverridePolicy = false;

        /// <summary>
        /// Gets lockdown policy as applied to a file.
        /// </summary>
        /// <returns>An EnforcementMode that describes policy.</returns>
        public static SystemEnforcementMode GetLockdownPolicy(string path, SafeHandle handle)
        {
            // Check the WLDP File policy via API
            var wldpFilePolicy = GetWldpPolicy(path, handle);
            if (wldpFilePolicy == SystemEnforcementMode.Enforce)
            {
                return wldpFilePolicy;
            }

            // Check the AppLocker File policy via API
            // This needs to be checked before WLDP audit policy
            // So, that we don't end up in Audit mode,
            // when we should be enforce mode.
            var appLockerFilePolicy = GetAppLockerPolicy(path, handle);
            if (appLockerFilePolicy == SystemEnforcementMode.Enforce)
            {
                return appLockerFilePolicy;
            }

            // At this point, LockdownPolicy = Audit or Allowed.
            // If there was a WLDP policy, but WLDP didn't block it,
            // then it was explicitly allowed. Therefore, return the result for the file.
            SystemEnforcementMode systemWldpPolicy = s_cachedWldpSystemPolicy.GetValueOrDefault(SystemEnforcementMode.None);
            if ((systemWldpPolicy == SystemEnforcementMode.Audit) ||
                (systemWldpPolicy == SystemEnforcementMode.Enforce))
            {
                return wldpFilePolicy;
            }

            // If there was a system-wide AppLocker policy, but AppLocker didn't block it,
            // then return AppLocker's status.
            if (s_cachedSaferSystemPolicy.GetValueOrDefault(SaferPolicy.Allowed) ==
                SaferPolicy.Disallowed)
            {
                return appLockerFilePolicy;
            }

            // If it's not set to 'Enforce' by the platform, allow debug overrides
            return GetDebugLockdownPolicy(path);
        }

        [SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods",
            MessageId = "System.Runtime.InteropServices.SafeHandle.DangerousGetHandle")]
        private static SystemEnforcementMode GetWldpPolicy(string path, SafeHandle handle)
        {
            // If the WLDP assembly is missing (such as windows 7 or down OS), return default/None to skip WLDP validation
            if (s_hadMissingWldpAssembly)
            {
                return s_cachedWldpSystemPolicy.GetValueOrDefault(SystemEnforcementMode.None);
            }

            // If path is NULL, see if we have the cached system-wide lockdown policy.
            if (string.IsNullOrEmpty(path))
            {
                if ((s_cachedWldpSystemPolicy != null) && (!InternalTestHooks.BypassAppLockerPolicyCaching))
                {
                    return s_cachedWldpSystemPolicy.Value;
                }
            }

            try
            {
                WLDP_HOST_INFORMATION hostInformation = new WLDP_HOST_INFORMATION();
                hostInformation.dwRevision = WldpNativeConstants.WLDP_HOST_INFORMATION_REVISION;
                hostInformation.dwHostId = WLDP_HOST_ID.WLDP_HOST_ID_POWERSHELL;

{'fraction_non_alphanumeric': 0.07125657718719344, 'fraction_numerical': 0.0018728261838936947, 'mean_word_length': 1.9127272727272728, 'pattern_counts': {'":': 0, '<': 27, '<?xml version=': 0, '>': 27, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5526310', 'n_tokens_mistral': 2897, 'n_tokens_neox': 2730, 'n_words': 811}