使用 C++ 防火墙 开关和添加白名单

本文涉及的产品
云防火墙,500元 1000GB
简介: 使用 C++ 防火墙 开关和添加白名单

以下代码示例练习 Windows 防火墙配置文件; 显示当前配置文件、关闭防火墙、打开防火墙并添加应用程序。

/*
    Copyright (c) Microsoft Corporation
    SYNOPSIS
        Sample code for the Windows Firewall COM interface.
*/
#include <windows.h>
#include <crtdbg.h>
#include <netfw.h>
#include <objbase.h>
#include <oleauto.h>
#include <stdio.h>
#pragma comment( lib, "ole32.lib" )
#pragma comment( lib, "oleaut32.lib" )
HRESULT WindowsFirewallInitialize(OUT INetFwProfile** fwProfile)
{
    HRESULT hr = S_OK;
    INetFwMgr* fwMgr = NULL;
    INetFwPolicy* fwPolicy = NULL;
    _ASSERT(fwProfile != NULL);
    *fwProfile = NULL;
// Create an instance of the firewall settings manager.
    hr = CoCreateInstance(
            __uuidof(NetFwMgr),
NULL,
            CLSCTX_INPROC_SERVER,
            __uuidof(INetFwMgr),
            (void**)&fwMgr
            );
if (FAILED(hr))
    {
printf("CoCreateInstance failed: 0x%08lx\n", hr);
goto error;
    }
// Retrieve the local firewall policy.
    hr = fwMgr->get_LocalPolicy(&fwPolicy);
if (FAILED(hr))
    {
printf("get_LocalPolicy failed: 0x%08lx\n", hr);
goto error;
    }
// Retrieve the firewall profile currently in effect.
    hr = fwPolicy->get_CurrentProfile(fwProfile);
if (FAILED(hr))
    {
printf("get_CurrentProfile failed: 0x%08lx\n", hr);
goto error;
    }
error:
// Release the local firewall policy.
if (fwPolicy != NULL)
    {
        fwPolicy->Release();
    }
// Release the firewall settings manager.
if (fwMgr != NULL)
    {
        fwMgr->Release();
    }
return hr;
}
void WindowsFirewallCleanup(IN INetFwProfile* fwProfile)
{
// Release the firewall profile.
if (fwProfile != NULL)
    {
        fwProfile->Release();
    }
}
HRESULT WindowsFirewallIsOn(IN INetFwProfile* fwProfile, OUT BOOL* fwOn)
{
    HRESULT hr = S_OK;
    VARIANT_BOOL fwEnabled;
    _ASSERT(fwProfile != NULL);
    _ASSERT(fwOn != NULL);
    *fwOn = FALSE;
// Get the current state of the firewall.
    hr = fwProfile->get_FirewallEnabled(&fwEnabled);
if (FAILED(hr))
    {
printf("get_FirewallEnabled failed: 0x%08lx\n", hr);
goto error;
    }
// Check to see if the firewall is on.
if (fwEnabled != VARIANT_FALSE)
    {
        *fwOn = TRUE;
printf("The firewall is on.\n");
    }
else
    {
printf("The firewall is off.\n");
    }
error:
return hr;
}
HRESULT WindowsFirewallTurnOn(IN INetFwProfile* fwProfile)
{
    HRESULT hr = S_OK;
    BOOL fwOn;
    _ASSERT(fwProfile != NULL);
// Check to see if the firewall is off.
    hr = WindowsFirewallIsOn(fwProfile, &fwOn);
if (FAILED(hr))
    {
printf("WindowsFirewallIsOn failed: 0x%08lx\n", hr);
goto error;
    }
// If it is, turn it on.
if (!fwOn)
    {
// Turn the firewall on.
        hr = fwProfile->put_FirewallEnabled(VARIANT_TRUE);
if (FAILED(hr))
        {
printf("put_FirewallEnabled failed: 0x%08lx\n", hr);
goto error;
        }
printf("The firewall is now on.\n");
    }
error:
return hr;
}
HRESULT WindowsFirewallTurnOff(IN INetFwProfile* fwProfile)
{
    HRESULT hr = S_OK;
    BOOL fwOn;
    _ASSERT(fwProfile != NULL);
// Check to see if the firewall is on.
    hr = WindowsFirewallIsOn(fwProfile, &fwOn);
if (FAILED(hr))
    {
printf("WindowsFirewallIsOn failed: 0x%08lx\n", hr);
goto error;
    }
// If it is, turn it off.
if (fwOn)
    {
// Turn the firewall off.
        hr = fwProfile->put_FirewallEnabled(VARIANT_FALSE);
if (FAILED(hr))
        {
printf("put_FirewallEnabled failed: 0x%08lx\n", hr);
goto error;
        }
printf("The firewall is now off.\n");
    }
error:
return hr;
}
HRESULT WindowsFirewallAppIsEnabled(
            IN INetFwProfile* fwProfile,
            IN const wchar_t* fwProcessImageFileName,
            OUT BOOL* fwAppEnabled
            )
{
    HRESULT hr = S_OK;
    BSTR fwBstrProcessImageFileName = NULL;
    VARIANT_BOOL fwEnabled;
    INetFwAuthorizedApplication* fwApp = NULL;
    INetFwAuthorizedApplications* fwApps = NULL;
    _ASSERT(fwProfile != NULL);
    _ASSERT(fwProcessImageFileName != NULL);
    _ASSERT(fwAppEnabled != NULL);
    *fwAppEnabled = FALSE;
// Retrieve the authorized application collection.
    hr = fwProfile->get_AuthorizedApplications(&fwApps);
if (FAILED(hr))
    {
printf("get_AuthorizedApplications failed: 0x%08lx\n", hr);
goto error;
    }
// Allocate a BSTR for the process image file name.
    fwBstrProcessImageFileName = SysAllocString(fwProcessImageFileName);
if (fwBstrProcessImageFileName == NULL)
    {
        hr = E_OUTOFMEMORY;
printf("SysAllocString failed: 0x%08lx\n", hr);
goto error;
    }
// Attempt to retrieve the authorized application.
    hr = fwApps->Item(fwBstrProcessImageFileName, &fwApp);
if (SUCCEEDED(hr))
    {
// Find out if the authorized application is enabled.
        hr = fwApp->get_Enabled(&fwEnabled);
if (FAILED(hr))
        {
printf("get_Enabled failed: 0x%08lx\n", hr);
goto error;
        }
if (fwEnabled != VARIANT_FALSE)
        {
// The authorized application is enabled.
            *fwAppEnabled = TRUE;
printf(
"Authorized application %lS is enabled in the firewall.\n",
                fwProcessImageFileName
                );
        }
else
        {
printf(
"Authorized application %lS is disabled in the firewall.\n",
                fwProcessImageFileName
                );
        }
    }
else
    {
// The authorized application was not in the collection.
        hr = S_OK;
printf(
"Authorized application %lS is disabled in the firewall.\n",
            fwProcessImageFileName
            );
    }
error:
// Free the BSTR.
    SysFreeString(fwBstrProcessImageFileName);
// Release the authorized application instance.
if (fwApp != NULL)
    {
        fwApp->Release();
    }
// Release the authorized application collection.
if (fwApps != NULL)
    {
        fwApps->Release();
    }
return hr;
}
HRESULT WindowsFirewallAddApp(
            IN INetFwProfile* fwProfile,
            IN const wchar_t* fwProcessImageFileName,
            IN const wchar_t* fwName
            )
{
    HRESULT hr = S_OK;
    BOOL fwAppEnabled;
    BSTR fwBstrName = NULL;
    BSTR fwBstrProcessImageFileName = NULL;
    INetFwAuthorizedApplication* fwApp = NULL;
    INetFwAuthorizedApplications* fwApps = NULL;
    _ASSERT(fwProfile != NULL);
    _ASSERT(fwProcessImageFileName != NULL);
    _ASSERT(fwName != NULL);
// First check to see if the application is already authorized.
    hr = WindowsFirewallAppIsEnabled(
            fwProfile,
            fwProcessImageFileName,
            &fwAppEnabled
            );
if (FAILED(hr))
    {
printf("WindowsFirewallAppIsEnabled failed: 0x%08lx\n", hr);
goto error;
    }
// Only add the application if it isn't already authorized.
if (!fwAppEnabled)
    {
// Retrieve the authorized application collection.
        hr = fwProfile->get_AuthorizedApplications(&fwApps);
if (FAILED(hr))
        {
printf("get_AuthorizedApplications failed: 0x%08lx\n", hr);
goto error;
        }
// Create an instance of an authorized application.
        hr = CoCreateInstance(
                __uuidof(NetFwAuthorizedApplication),
NULL,
                CLSCTX_INPROC_SERVER,
                __uuidof(INetFwAuthorizedApplication),
                (void**)&fwApp
                );
if (FAILED(hr))
        {
printf("CoCreateInstance failed: 0x%08lx\n", hr);
goto error;
        }
// Allocate a BSTR for the process image file name.
        fwBstrProcessImageFileName = SysAllocString(fwProcessImageFileName);
if (fwBstrProcessImageFileName == NULL)
        {
            hr = E_OUTOFMEMORY;
printf("SysAllocString failed: 0x%08lx\n", hr);
goto error;
        }
// Set the process image file name.
        hr = fwApp->put_ProcessImageFileName(fwBstrProcessImageFileName);
if (FAILED(hr))
        {
printf("put_ProcessImageFileName failed: 0x%08lx\n", hr);
goto error;
        }
// Allocate a BSTR for the application friendly name.
        fwBstrName = SysAllocString(fwName);
if (SysStringLen(fwBstrName) == 0)
        {
            hr = E_OUTOFMEMORY;
printf("SysAllocString failed: 0x%08lx\n", hr);
goto error;
        }
// Set the application friendly name.
        hr = fwApp->put_Name(fwBstrName);
if (FAILED(hr))
        {
printf("put_Name failed: 0x%08lx\n", hr);
goto error;
        }
// Add the application to the collection.
        hr = fwApps->Add(fwApp);
if (FAILED(hr))
        {
printf("Add failed: 0x%08lx\n", hr);
goto error;
        }
printf(
"Authorized application %lS is now enabled in the firewall.\n",
            fwProcessImageFileName
            );
    }
error:
// Free the BSTRs.
    SysFreeString(fwBstrName);
    SysFreeString(fwBstrProcessImageFileName);
// Release the authorized application instance.
if (fwApp != NULL)
    {
        fwApp->Release();
    }
// Release the authorized application collection.
if (fwApps != NULL)
    {
        fwApps->Release();
    }
return hr;
}
HRESULT WindowsFirewallPortIsEnabled(
            IN INetFwProfile* fwProfile,
            IN LONG portNumber,
            IN NET_FW_IP_PROTOCOL ipProtocol,
            OUT BOOL* fwPortEnabled
            )
{
    HRESULT hr = S_OK;
    VARIANT_BOOL fwEnabled;
    INetFwOpenPort* fwOpenPort = NULL;
    INetFwOpenPorts* fwOpenPorts = NULL;
    _ASSERT(fwProfile != NULL);
    _ASSERT(fwPortEnabled != NULL);
    *fwPortEnabled = FALSE;
// Retrieve the globally open ports collection.
    hr = fwProfile->get_GloballyOpenPorts(&fwOpenPorts);
if (FAILED(hr))
    {
printf("get_GloballyOpenPorts failed: 0x%08lx\n", hr);
goto error;
    }
// Attempt to retrieve the globally open port.
    hr = fwOpenPorts->Item(portNumber, ipProtocol, &fwOpenPort);
if (SUCCEEDED(hr))
    {
// Find out if the globally open port is enabled.
        hr = fwOpenPort->get_Enabled(&fwEnabled);
if (FAILED(hr))
        {
printf("get_Enabled failed: 0x%08lx\n", hr);
goto error;
        }
if (fwEnabled != VARIANT_FALSE)
        {
// The globally open port is enabled.
            *fwPortEnabled = TRUE;
printf("Port %ld is open in the firewall.\n", portNumber);
        }
else
        {
printf("Port %ld is not open in the firewall.\n", portNumber);
        }
    }
else
    {
// The globally open port was not in the collection.
        hr = S_OK;
printf("Port %ld is not open in the firewall.\n", portNumber);
    }
error:
// Release the globally open port.
if (fwOpenPort != NULL)
    {
        fwOpenPort->Release();
    }
// Release the globally open ports collection.
if (fwOpenPorts != NULL)
    {
        fwOpenPorts->Release();
    }
return hr;
}
HRESULT WindowsFirewallPortAdd(
            IN INetFwProfile* fwProfile,
            IN LONG portNumber,
            IN NET_FW_IP_PROTOCOL ipProtocol,
            IN const wchar_t* name
            )
{
    HRESULT hr = S_OK;
    BOOL fwPortEnabled;
    BSTR fwBstrName = NULL;
    INetFwOpenPort* fwOpenPort = NULL;
    INetFwOpenPorts* fwOpenPorts = NULL;
    _ASSERT(fwProfile != NULL);
    _ASSERT(name != NULL);
// First check to see if the port is already added.
    hr = WindowsFirewallPortIsEnabled(
            fwProfile,
            portNumber,
            ipProtocol,
            &fwPortEnabled
            );
if (FAILED(hr))
    {
printf("WindowsFirewallPortIsEnabled failed: 0x%08lx\n", hr);
goto error;
    }
// Only add the port if it isn't already added.
if (!fwPortEnabled)
    {
// Retrieve the collection of globally open ports.
        hr = fwProfile->get_GloballyOpenPorts(&fwOpenPorts);
if (FAILED(hr))
        {
printf("get_GloballyOpenPorts failed: 0x%08lx\n", hr);
goto error;
        }
// Create an instance of an open port.
        hr = CoCreateInstance(
                __uuidof(NetFwOpenPort),
NULL,
                CLSCTX_INPROC_SERVER,
                __uuidof(INetFwOpenPort),
                (void**)&fwOpenPort
                );
if (FAILED(hr))
        {
printf("CoCreateInstance failed: 0x%08lx\n", hr);
goto error;
        }
// Set the port number.
        hr = fwOpenPort->put_Port(portNumber);
if (FAILED(hr))
        {
printf("put_Port failed: 0x%08lx\n", hr);
goto error;
        }
// Set the IP protocol.
        hr = fwOpenPort->put_Protocol(ipProtocol);
if (FAILED(hr))
        {
printf("put_Protocol failed: 0x%08lx\n", hr);
goto error;
        }
// Allocate a BSTR for the friendly name of the port.
        fwBstrName = SysAllocString(name);
if (SysStringLen(fwBstrName) == 0)
        {
            hr = E_OUTOFMEMORY;
printf("SysAllocString failed: 0x%08lx\n", hr);
goto error;
        }
// Set the friendly name of the port.
        hr = fwOpenPort->put_Name(fwBstrName);
if (FAILED(hr))
        {
printf("put_Name failed: 0x%08lx\n", hr);
goto error;
        }
// Opens the port and adds it to the collection.
        hr = fwOpenPorts->Add(fwOpenPort);
if (FAILED(hr))
        {
printf("Add failed: 0x%08lx\n", hr);
goto error;
        }
printf("Port %ld is now open in the firewall.\n", portNumber);
    }
error:
// Free the BSTR.
    SysFreeString(fwBstrName);
// Release the open port instance.
if (fwOpenPort != NULL)
    {
        fwOpenPort->Release();
    }
// Release the globally open ports collection.
if (fwOpenPorts != NULL)
    {
        fwOpenPorts->Release();
    }
return hr;
}
int __cdecl wmain(int argc, wchar_t* argv[])
{
    HRESULT hr = S_OK;
    HRESULT comInit = E_FAIL;
    INetFwProfile* fwProfile = NULL;
// Initialize COM.
    comInit = CoInitializeEx(
0,
                COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE
                );
// Ignore RPC_E_CHANGED_MODE; this just means that COM has already been
// initialized with a different mode. Since we don't care what the mode is,
// we'll just use the existing mode.
if (comInit != RPC_E_CHANGED_MODE)
   {
        hr = comInit;
if (FAILED(hr))
        {
printf("CoInitializeEx failed: 0x%08lx\n", hr);
goto error;
        }
   }
// Retrieve the firewall profile currently in effect.
    hr = WindowsFirewallInitialize(&fwProfile);
if (FAILED(hr))
    {
printf("WindowsFirewallInitialize failed: 0x%08lx\n", hr);
goto error;
    }
// Turn off the firewall.
    hr = WindowsFirewallTurnOff(fwProfile);
if (FAILED(hr))
    {
printf("WindowsFirewallTurnOff failed: 0x%08lx\n", hr);
goto error;
    }
// Turn on the firewall.
    hr = WindowsFirewallTurnOn(fwProfile);
if (FAILED(hr))
    {
printf("WindowsFirewallTurnOn failed: 0x%08lx\n", hr);
goto error;
    }
// Add Windows Messenger to the authorized application collection.
    hr = WindowsFirewallAddApp(
            fwProfile,
L"%ProgramFiles%\\Messenger\\msmsgs.exe",
L"Windows Messenger"
            );
if (FAILED(hr))
    {
printf("WindowsFirewallAddApp failed: 0x%08lx\n", hr);
goto error;
    }
// Add TCP::80 to list of globally open ports.
    hr = WindowsFirewallPortAdd(fwProfile, 80, NET_FW_IP_PROTOCOL_TCP, L"WWW");
if (FAILED(hr))
    {
printf("WindowsFirewallPortAdd failed: 0x%08lx\n", hr);
goto error;
    }
error:
// Release the firewall profile.
    WindowsFirewallCleanup(fwProfile);
// Uninitialize COM.
if (SUCCEEDED(comInit))
    {
        CoUninitialize();
    }
return 0;
}
目录
打赏
0
0
0
0
3
分享
相关文章
linux配置防火墙 Centos7下 添加 端口白名单
linux配置防火墙 Centos7下 添加 端口白名单
1174 0
【Example】C++ 用于编译时封装的 Pimpl 演示 (编译防火墙 Private-IMPL)
什么是 Private-IMPL ? 即【隐藏实现的方式】,如果你还停留在学习的阶段,那这种方式对你的代码几乎毫无用处。 但是如果你走入到真实项目当中,这种方式又显得尤为重要。
198 0
Linux 下设置防火墙白名单(RHEL 6 和 CentOS 7)
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/catoop/article/details/50476099 进入Linux 命...
1606 0
【C++篇】深度解析类与对象(下)
在上一篇博客中,我们学习了C++的基础类与对象概念,包括类的定义、对象的使用和构造函数的作用。在这一篇,我们将深入探讨C++类的一些重要特性,如构造函数的高级用法、类型转换、static成员、友元、内部类、匿名对象,以及对象拷贝优化等。这些内容可以帮助你更好地理解和应用面向对象编程的核心理念,提升代码的健壮性、灵活性和可维护性。
【C++篇】深度解析类与对象(中)
在上一篇博客中,我们学习了C++类与对象的基础内容。这一次,我们将深入探讨C++类的关键特性,包括构造函数、析构函数、拷贝构造函数、赋值运算符重载、以及取地址运算符的重载。这些内容是理解面向对象编程的关键,也帮助我们更好地掌握C++内存管理的细节和编码的高级技巧。
【C++篇】深度解析类与对象(上)
在C++中,类和对象是面向对象编程的基础组成部分。通过类,程序员可以对现实世界的实体进行模拟和抽象。类的基本概念包括成员变量、成员函数、访问控制等。本篇博客将介绍C++类与对象的基础知识,为后续学习打下良好的基础。
|
1月前
|
【C++面向对象——类与对象】Computer类(头歌实践教学平台习题)【合集】
声明一个简单的Computer类,含有数据成员芯片(cpu)、内存(ram)、光驱(cdrom)等等,以及两个公有成员函数run、stop。只能在类的内部访问。这是一种数据隐藏的机制,用于保护类的数据不被外部随意修改。根据提示,在右侧编辑器补充代码,平台会对你编写的代码进行测试。成员可以在派生类(继承该类的子类)中访问。成员,在类的外部不能直接访问。可以在类的外部直接访问。为了完成本关任务,你需要掌握。
70 19
【C++面向对象——类与对象】CPU类(头歌实践教学平台习题)【合集】
声明一个CPU类,包含等级(rank)、频率(frequency)、电压(voltage)等属性,以及两个公有成员函数run、stop。根据提示,在右侧编辑器补充代码,平台会对你编写的代码进行测试。​ 相关知识 类的声明和使用。 类的声明和对象的声明。 构造函数和析构函数的执行。 一、类的声明和使用 1.类的声明基础 在C++中,类是创建对象的蓝图。类的声明定义了类的成员,包括数据成员(变量)和成员函数(方法)。一个简单的类声明示例如下: classMyClass{ public: int
53 13