如何使用.NET应用Windows组策略?

发布于 2024-08-21 03:38:06 字数 365 浏览 4 评论 0原文

是否可以使用 .NET 应用(和删除)Windows 组策略设置?

我正在开发一个应用程序,该应用程序需要暂时将机器置于受限的、类似信息亭的状态。我需要控制的事情之一是对 USB 驱动器的访问,我相信我可以通过组策略来做到这一点。我希望我的应用程序在启动时设置策略并在退出时恢复更改...这是我可以通过 .NET 框架调用执行的操作吗?

这些是我的主要要求:

  • 在我的控制台应用程序启动时应用组策略设置。
  • 识别策略何时拒绝用户操作并将其记录下来。
    • 可以记录到系统安全日志。
  • 当我的应用程序停止时恢复我的策略更改。

Is it possible to apply (and remove) Windows group policy settings using .NET?

I am working on an application that needs to temporarily put a machine into a restricted, kiosk-like state. One of the things I need to control is access to USB drives which I believe I can do through group policy. I'd like my app to set the policy when it starts and revert the change when it exits... is this something I can do through .NET framework calls?

These are my primary requirements:

  • Apply group policy settings when my console app is started.
  • Identify when a user action is denied by the policy and log it.
    • Logging to the system security log is acceptable.
  • Revert my policy changes when my app stops.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

尝试使用 IGroupPolicyObject

bool SetGroupPolicy(HKEY hKey, LPCTSTR subKey, LPCTSTR valueName, DWORD dwType, const BYTE* szkeyValue, DWORD dwkeyValue)
{
    CoInitialize(NULL);
    HKEY ghKey, ghSubKey, hSubKey;
    LPDWORD flag = NULL;
    IGroupPolicyObject *pGPO = NULL;
    HRESULT hr = CoCreateInstance(CLSID_GroupPolicyObject, NULL, CLSCTX_ALL, IID_IGroupPolicyObject, (LPVOID*)&pGPO);

    if(!SUCCEEDED(hr))
    {
        MessageBox(NULL, L"Failed to initialize GPO", L"", S_OK);
    }

    if (RegCreateKeyEx(hKey, subKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hSubKey, flag) != ERROR_SUCCESS)
    {
        return false;
        CoUninitialize();
    }

    if(dwType == REG_SZ)
    {
        if(RegSetValueEx(hSubKey, valueName, 0, dwType, szkeyValue, strlen((char*)szkeyValue) + 1) != ERROR_SUCCESS)
        {
            RegCloseKey(hSubKey);
            CoUninitialize();
            return false;
        }
    }

    else if(dwType == REG_DWORD)
    {
        if(RegSetValueEx(hSubKey, valueName, 0, dwType, (BYTE*)&dwkeyValue, sizeof(dwkeyValue)) != ERROR_SUCCESS)
        {
            RegCloseKey(hSubKey);
            CoUninitialize();
            return false;
        }
    }

    if(!SUCCEEDED(hr))
    {
        MessageBox(NULL, L"Failed to initialize GPO", L"", S_OK);
        CoUninitialize();
        return false;
    }

    if(pGPO->OpenLocalMachineGPO(GPO_OPEN_LOAD_REGISTRY) != S_OK)
    {
        MessageBox(NULL, L"Failed to get the GPO mapping", L"", S_OK);
        CoUninitialize();
        return false;
    }

    if(pGPO->GetRegistryKey(GPO_SECTION_USER,&ghKey) != S_OK)
    {
        MessageBox(NULL, L"Failed to get the root key", L"", S_OK);
        CoUninitialize();
        return false;
    }

    if(RegCreateKeyEx(ghKey, subKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &ghSubKey, flag) != ERROR_SUCCESS)
    {
        RegCloseKey(ghKey);
        MessageBox(NULL, L"Cannot create key", L"", S_OK);
        CoUninitialize();
        return false;
    }

    if(dwType == REG_SZ)
    {
        if(RegSetValueEx(ghSubKey, valueName, 0, dwType, szkeyValue, strlen((char*)szkeyValue) + 1) != ERROR_SUCCESS)
        {
            RegCloseKey(ghKey);
            RegCloseKey(ghSubKey);
            MessageBox(NULL, L"Cannot create sub key", L"", S_OK);
            CoUninitialize();
            return false;
        }
    }

    else if(dwType == REG_DWORD)
    {
        if(RegSetValueEx(ghSubKey, valueName, 0, dwType, (BYTE*)&dwkeyValue, sizeof(dwkeyValue)) != ERROR_SUCCESS)
        {
            RegCloseKey(ghKey);
            RegCloseKey(ghSubKey);
            MessageBox(NULL, L"Cannot set value", L"", S_OK);
            CoUninitialize();
            return false;
        }
    }

    if(pGPO->Save(false, true, const_cast<GUID*>(&EXTENSION_GUID), const_cast<GUID*>(&CLSID_GPESnapIn)) != S_OK)
    {
        RegCloseKey(ghKey);
        RegCloseKey(ghSubKey);
        MessageBox(NULL, L"Save failed", L"", S_OK);
        CoUninitialize();
        return false;
    }

    pGPO->Release();
    RegCloseKey(ghKey);
    RegCloseKey(ghSubKey);
    CoUninitialize();
    return true;
}

您可以像这样调用此函数这..

// Remove the Log Off in start menu
SetGroupPolicy(HKEY_CURRENT_USER,
    L"Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer",
    L"StartMenuLogOff", REG_DWORD, NULL, 1);

Try using IGroupPolicyObject

bool SetGroupPolicy(HKEY hKey, LPCTSTR subKey, LPCTSTR valueName, DWORD dwType, const BYTE* szkeyValue, DWORD dwkeyValue)
{
    CoInitialize(NULL);
    HKEY ghKey, ghSubKey, hSubKey;
    LPDWORD flag = NULL;
    IGroupPolicyObject *pGPO = NULL;
    HRESULT hr = CoCreateInstance(CLSID_GroupPolicyObject, NULL, CLSCTX_ALL, IID_IGroupPolicyObject, (LPVOID*)&pGPO);

    if(!SUCCEEDED(hr))
    {
        MessageBox(NULL, L"Failed to initialize GPO", L"", S_OK);
    }

    if (RegCreateKeyEx(hKey, subKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hSubKey, flag) != ERROR_SUCCESS)
    {
        return false;
        CoUninitialize();
    }

    if(dwType == REG_SZ)
    {
        if(RegSetValueEx(hSubKey, valueName, 0, dwType, szkeyValue, strlen((char*)szkeyValue) + 1) != ERROR_SUCCESS)
        {
            RegCloseKey(hSubKey);
            CoUninitialize();
            return false;
        }
    }

    else if(dwType == REG_DWORD)
    {
        if(RegSetValueEx(hSubKey, valueName, 0, dwType, (BYTE*)&dwkeyValue, sizeof(dwkeyValue)) != ERROR_SUCCESS)
        {
            RegCloseKey(hSubKey);
            CoUninitialize();
            return false;
        }
    }

    if(!SUCCEEDED(hr))
    {
        MessageBox(NULL, L"Failed to initialize GPO", L"", S_OK);
        CoUninitialize();
        return false;
    }

    if(pGPO->OpenLocalMachineGPO(GPO_OPEN_LOAD_REGISTRY) != S_OK)
    {
        MessageBox(NULL, L"Failed to get the GPO mapping", L"", S_OK);
        CoUninitialize();
        return false;
    }

    if(pGPO->GetRegistryKey(GPO_SECTION_USER,&ghKey) != S_OK)
    {
        MessageBox(NULL, L"Failed to get the root key", L"", S_OK);
        CoUninitialize();
        return false;
    }

    if(RegCreateKeyEx(ghKey, subKey, 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &ghSubKey, flag) != ERROR_SUCCESS)
    {
        RegCloseKey(ghKey);
        MessageBox(NULL, L"Cannot create key", L"", S_OK);
        CoUninitialize();
        return false;
    }

    if(dwType == REG_SZ)
    {
        if(RegSetValueEx(ghSubKey, valueName, 0, dwType, szkeyValue, strlen((char*)szkeyValue) + 1) != ERROR_SUCCESS)
        {
            RegCloseKey(ghKey);
            RegCloseKey(ghSubKey);
            MessageBox(NULL, L"Cannot create sub key", L"", S_OK);
            CoUninitialize();
            return false;
        }
    }

    else if(dwType == REG_DWORD)
    {
        if(RegSetValueEx(ghSubKey, valueName, 0, dwType, (BYTE*)&dwkeyValue, sizeof(dwkeyValue)) != ERROR_SUCCESS)
        {
            RegCloseKey(ghKey);
            RegCloseKey(ghSubKey);
            MessageBox(NULL, L"Cannot set value", L"", S_OK);
            CoUninitialize();
            return false;
        }
    }

    if(pGPO->Save(false, true, const_cast<GUID*>(&EXTENSION_GUID), const_cast<GUID*>(&CLSID_GPESnapIn)) != S_OK)
    {
        RegCloseKey(ghKey);
        RegCloseKey(ghSubKey);
        MessageBox(NULL, L"Save failed", L"", S_OK);
        CoUninitialize();
        return false;
    }

    pGPO->Release();
    RegCloseKey(ghKey);
    RegCloseKey(ghSubKey);
    CoUninitialize();
    return true;
}

You can call this function like this..

// Remove the Log Off in start menu
SetGroupPolicy(HKEY_CURRENT_USER,
    L"Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer",
    L"StartMenuLogOff", REG_DWORD, NULL, 1);
魔法唧唧 2024-08-28 03:38:06

注意:我使用两个 GroupPolicy 程序集引用:
C:\ Windows \程序集\ GAC_MSIL \ Microsoft.GroupPolicy.Management \ 2.0.0.0__31bf3856ad364e35 \ Microsoft.GroupPolicy.Management.dll

C:\ Windows \程序集\ GAC_32 \ Microsoft.GroupPolicy.Management.Interop \ 2.0.0.0__31bf3856ad364e35 \ Microsoft.GroupPolicy.Management.Interop.dll
这个框架2.0,所以有混合代码,必须使用app.config: http://msmvps.com/blogs/rfennell/archive/2010 /03/27/mixed-mode- assembly-is-built-against-version-v2-0-50727-error-using-net-4-development-web-server.aspx

我就是这样做的。

using System.Collections.ObjectModel;
using Microsoft.GroupPolicy;
using Microsoft.Win32;

/// <summary>
/// Change user's registry policy
/// </summary>
/// <param name="gpoName">The name of Group Policy Object(DisplayName)</param>
/// <param name="keyPath">Is KeyPath(like string path=@"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer")</param>
/// <param name="typeOfKey">DWord, ExpandString,... e.t.c </param>
/// <param name="parameterName">Name of parameter</param>
/// <param name="value">Value</param>
/// <returns>result: true\false</returns>
public bool ChangePolicyUser(string gpoName, string keyPath, RegistryValueKind typeOfKey, string parameterName, object value)
    {
        try
        {
            RegistrySetting newSetting = new PolicyRegistrySetting();
            newSetting.Hive = RegistryHive.CurrentUser;
            newSetting.KeyPath = keyPath;
            bool contains = false;
            //newSetting.SetValue(parameterName, value, typeOfKey);
            switch (typeOfKey)
            {
                case RegistryValueKind.String:
                    newSetting.SetValue(parameterName, (string)value, typeOfKey);
                    break;
                case RegistryValueKind.ExpandString:
                    newSetting.SetValue(parameterName, (string)value, typeOfKey);
                    break;
                case RegistryValueKind.DWord:
                    newSetting.SetValue(parameterName, (Int32)value);
                    break;
                case RegistryValueKind.QWord:
                    newSetting.SetValue(parameterName, (Int64)value);
                    break;
                case RegistryValueKind.Binary:
                    newSetting.SetValue(parameterName, (byte[])value);
                    break;
                case RegistryValueKind.MultiString:
                    newSetting.SetValue(parameterName, (string[])value, typeOfKey);
                    break;
            }
            Gpo gpoTarget = _gpDomain.GetGpo(gpoName);
            RegistryPolicy registry = gpoTarget.User.Policy.GetRegistry(false);
            try
            {
                ReadOnlyCollection<RegistryItem> items = gpoTarget.User.Policy.GetRegistry(false).Read(newSetting.Hive, keyPath);
                foreach (RegistryItem item in items)
                {
                    if (((RegistrySetting) item).ValueName == parameterName)
                    {
                        contains = true;
                    }
                }
                registry.Write((PolicyRegistrySetting) newSetting, !contains);
                registry.Save(false);
                return true;
            }
            catch (ArgumentException)
            {
                registry.Write((PolicyRegistrySetting)newSetting, contains);
                registry.Save(true);
                return true;
            }
        }
        catch (Exception)
        {
            return false;
        }
    }

NOTE: I use two GroupPolicy assembly references:
C:\Windows\assembly\GAC_MSIL\Microsoft.GroupPolicy.Management\2.0.0.0__31bf3856ad364e35\Microsoft.GroupPolicy.Management.dll
and
C:\Windows\assembly\GAC_32\Microsoft.GroupPolicy.Management.Interop\2.0.0.0__31bf3856ad364e35\Microsoft.GroupPolicy.Management.Interop.dll
This framework 2.0, so there are mixed code, and you must use app.config: http://msmvps.com/blogs/rfennell/archive/2010/03/27/mixed-mode-assembly-is-built-against-version-v2-0-50727-error-using-net-4-development-web-server.aspx

I made it like that.

using System.Collections.ObjectModel;
using Microsoft.GroupPolicy;
using Microsoft.Win32;

/// <summary>
/// Change user's registry policy
/// </summary>
/// <param name="gpoName">The name of Group Policy Object(DisplayName)</param>
/// <param name="keyPath">Is KeyPath(like string path=@"Software\Microsoft\Windows\CurrentVersion\Policies\Explorer")</param>
/// <param name="typeOfKey">DWord, ExpandString,... e.t.c </param>
/// <param name="parameterName">Name of parameter</param>
/// <param name="value">Value</param>
/// <returns>result: true\false</returns>
public bool ChangePolicyUser(string gpoName, string keyPath, RegistryValueKind typeOfKey, string parameterName, object value)
    {
        try
        {
            RegistrySetting newSetting = new PolicyRegistrySetting();
            newSetting.Hive = RegistryHive.CurrentUser;
            newSetting.KeyPath = keyPath;
            bool contains = false;
            //newSetting.SetValue(parameterName, value, typeOfKey);
            switch (typeOfKey)
            {
                case RegistryValueKind.String:
                    newSetting.SetValue(parameterName, (string)value, typeOfKey);
                    break;
                case RegistryValueKind.ExpandString:
                    newSetting.SetValue(parameterName, (string)value, typeOfKey);
                    break;
                case RegistryValueKind.DWord:
                    newSetting.SetValue(parameterName, (Int32)value);
                    break;
                case RegistryValueKind.QWord:
                    newSetting.SetValue(parameterName, (Int64)value);
                    break;
                case RegistryValueKind.Binary:
                    newSetting.SetValue(parameterName, (byte[])value);
                    break;
                case RegistryValueKind.MultiString:
                    newSetting.SetValue(parameterName, (string[])value, typeOfKey);
                    break;
            }
            Gpo gpoTarget = _gpDomain.GetGpo(gpoName);
            RegistryPolicy registry = gpoTarget.User.Policy.GetRegistry(false);
            try
            {
                ReadOnlyCollection<RegistryItem> items = gpoTarget.User.Policy.GetRegistry(false).Read(newSetting.Hive, keyPath);
                foreach (RegistryItem item in items)
                {
                    if (((RegistrySetting) item).ValueName == parameterName)
                    {
                        contains = true;
                    }
                }
                registry.Write((PolicyRegistrySetting) newSetting, !contains);
                registry.Save(false);
                return true;
            }
            catch (ArgumentException)
            {
                registry.Write((PolicyRegistrySetting)newSetting, contains);
                registry.Save(true);
                return true;
            }
        }
        catch (Exception)
        {
            return false;
        }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文