#include "stdafx.h" #include //#include // MSDN的代码中这里没有包含这个头文件,导致编译不过 #include #include #include #include #pragma comment( lib, "ole32.lib" ) #pragma comment( lib, "oleaut32.lib" ) #include "WindowsFirewall.h" #include #include #include ////////////////////////////////////////////////////////////////////////// #define NET_FW_IP_PROTOCOL_TCP_NAME L"TCP" #define NET_FW_IP_PROTOCOL_UDP_NAME L"UDP" #define NET_FW_RULE_DIR_IN_NAME L"In" #define NET_FW_RULE_DIR_OUT_NAME L"Out" #define NET_FW_RULE_ACTION_BLOCK_NAME L"Block" #define NET_FW_RULE_ACTION_ALLOW_NAME L"Allow" #define NET_FW_RULE_ENABLE_IN_NAME L"TRUE" #define NET_FW_RULE_DISABLE_IN_NAME L"FALSE" #define STRING_BUFFER_SIZE 500 ////////////////////////////////////////////////////////////////////////// WinFireWallXP::WinFireWallXP() :fwProfile(NULL), m_hr(S_OK) { HRESULT comInit = CoInitializeEx(0,COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); if (comInit != RPC_E_CHANGED_MODE) { if (FAILED(comInit)) { printf("CoInitializeEx failed: 0x%08lx\n", comInit); } } } WinFireWallXP::~WinFireWallXP() { FirewallCleanup(); CoUninitialize(); } BOOL WinFireWallXP::FirewallInit() { INetFwMgr *fwMgr = NULL; INetFwPolicy *fwPolicy = NULL; m_hr = CoCreateInstance( __uuidof(NetFwMgr), NULL, CLSCTX_INPROC_SERVER, __uuidof(INetFwMgr), (void **)&fwMgr); if (FAILED(m_hr)) { printf("CoCreateInstance failed: 0x%08lx\n", m_hr); goto error; } m_hr = fwMgr->get_LocalPolicy(&fwPolicy); if (FAILED(m_hr)) { printf("get_localPolicy failed: 0x%08lx\n", m_hr); goto error; } m_hr = fwPolicy->get_CurrentProfile(&fwProfile); if (FAILED(m_hr)) { printf("get_CurrentProfile failed: 0x%08lx\n", m_hr); goto error; } error: if (fwPolicy != NULL) { fwPolicy->Release(); } if (fwMgr != NULL) { fwMgr->Release(); } return SUCCEEDED(m_hr) ? TRUE : FALSE; } void WinFireWallXP::FirewallCleanup() { if (fwProfile != NULL) { fwProfile->Release(); } } BOOL WinFireWallXP::FirewallIsOn() { BOOL fwOn = FALSE; m_hr = S_OK; VARIANT_BOOL fwEnabled; _ASSERT(fwProfile != NULL); m_hr = fwProfile->get_FirewallEnabled(&fwEnabled); if (FAILED(m_hr)) { printf("get_FirewallEnabled failed: 0x%08lx\n", m_hr); return FALSE; } if (fwEnabled != VARIANT_FALSE) { fwOn = TRUE; printf("The firewall is on.\n"); } else { printf("The firewall is off.\n"); } return fwOn; } BOOL WinFireWallXP::FirewallTurnOn() { _ASSERT(fwProfile != NULL); BOOL bRet = FALSE; if (FALSE == (bRet = FirewallIsOn())) {// 获取防火墙状态失败; if (FAILED(HGetLastError())) return FALSE; } m_hr = S_OK; if (!bRet) { m_hr = fwProfile->put_FirewallEnabled(VARIANT_TRUE); if (FAILED(m_hr)) { printf("put_FirewallEnabled failed: 0x%08lx\n", m_hr); return FALSE; } printf("The firewall is now on.\n"); } return TRUE; } BOOL WinFireWallXP::FirewallTurnOff() { _ASSERT(fwProfile != NULL); BOOL bRet = FALSE; if (FALSE == (bRet = FirewallIsOn())) {// 获取防火墙状态失败; if (FAILED(HGetLastError())) return FALSE; } m_hr = S_OK; if (bRet) { m_hr = fwProfile->put_FirewallEnabled(VARIANT_FALSE); if (FAILED(m_hr)) { printf("put_FirewallEnabled failed: 0x%08lx\n", m_hr); return FALSE; } printf("The firewall is now on.\n"); } return TRUE; } BOOL WinFireWallXP::FirewallAppIsEnable(IN LPCTSTR lpProcessFileName) { BSTR fwBstrProcessImageFileName = NULL; VARIANT_BOOL fwEnabled; INetFwAuthorizedApplication *fwApp = NULL; INetFwAuthorizedApplications *fwApps = NULL; _ASSERT(lpProcessFileName != NULL); BOOL fwAppEnabled = false; // 获取授权的程序集 ; m_hr = fwProfile->get_AuthorizedApplications(&fwApps); if (FAILED(m_hr)) { printf("get_AuthorizedApplications failed: 0x%08lx\n", m_hr); goto error; } fwBstrProcessImageFileName = SysAllocString(lpProcessFileName); if (fwBstrProcessImageFileName == NULL) { m_hr = E_OUTOFMEMORY; printf("SysAllocString failed: 0x%08lx\n", m_hr); goto error; } m_hr = fwApps->Item(fwBstrProcessImageFileName, &fwApp); if (SUCCEEDED(m_hr)) { m_hr = fwApp->get_Enabled(&fwEnabled); if (FAILED(m_hr)) { printf("get_Enabled failed: 0x%08lx\n", m_hr); goto error; } if (fwEnabled != VARIANT_FALSE) { fwAppEnabled = TRUE; printf( "Authorized application %lS is enabled in the firewall.\n", lpProcessFileName ); } else { printf( "Authorized application %lS is disabled in the firewall.\n", lpProcessFileName ); } } else { m_hr = S_OK; printf( "Authorized application %lS is disabled in the firewall.\n", lpProcessFileName ); } error: SysFreeString(fwBstrProcessImageFileName); if (fwApp != NULL) { fwApp->Release(); } if (fwApps != NULL) { fwApps->Release(); } return fwAppEnabled; } BOOL WinFireWallXP::FirewallAddApp(IN LPCTSTR lpProcessFileName, IN LPCTSTR lpName) { HRESULT hr = S_OK; BOOL fwAppEnabled; BSTR fwBstrName = NULL; BSTR fwBstrProcessImageFileName = NULL; INetFwAuthorizedApplication *fwApp = NULL; INetFwAuthorizedApplications *fwApps = NULL; _ASSERT(fwProfile != NULL); _ASSERT(lpProcessFileName != NULL); _ASSERT(lpName != NULL); fwAppEnabled = FirewallAppIsEnable(lpProcessFileName); if (!fwAppEnabled) { if (FAILED(HGetLastError())) return FALSE; m_hr = fwProfile->get_AuthorizedApplications(&fwApps); if (FAILED(m_hr)) { printf("get_AuthorizedApplications failed: 0x%08lx\n", m_hr); goto error; } m_hr = CoCreateInstance( __uuidof(NetFwAuthorizedApplication), NULL, CLSCTX_INPROC_SERVER, __uuidof(INetFwAuthorizedApplication), (void**)&fwApp); if (FAILED(m_hr)) { printf("CoCreateInstance failed: 0x%08lx\n", m_hr); goto error; } fwBstrProcessImageFileName = SysAllocString(lpProcessFileName); if (fwBstrProcessImageFileName == NULL) { m_hr = E_OUTOFMEMORY; printf("SysAllocString failed: 0x%08lx\n", m_hr); goto error; } m_hr = fwApp->put_ProcessImageFileName(fwBstrProcessImageFileName); if (FAILED(m_hr)) { printf("put_ProcessImageFileName failed: 0x%08lx\n", m_hr); goto error; } fwBstrName = SysAllocString(lpName); if (SysStringLen(fwBstrName) == 0) { m_hr = E_OUTOFMEMORY; printf("SysAllocString failed: 0x%08lx\n", m_hr); goto error; } m_hr = fwApp->put_Name(fwBstrName); if (FAILED(hr)) { printf("put_Name failed: 0x%08lx\n", m_hr); goto error; } m_hr = fwApps->Add(fwApp); if (FAILED(m_hr)) { printf("Add failed: 0x%08lx\n", m_hr); goto error; } m_hr = S_OK; fwAppEnabled = TRUE; printf( "Authorized application %lS is now enabled in the firewall.\n", lpProcessFileName ); } error: SysFreeString(fwBstrName); SysFreeString(fwBstrProcessImageFileName); if (fwApp != NULL) { fwApp->Release(); } if (fwApps != NULL) { fwApps->Release(); } return fwAppEnabled; } BOOL WinFireWallXP::FirewallPortIsEnable(IN LONG lPortNumber, IN NET_FW_IP_PROTOCOL netProtocol) { VARIANT_BOOL fwEnabled; INetFwOpenPort *fwOpenPort = NULL; INetFwOpenPorts *fwOpenPorts = NULL; _ASSERT(fwProfile != NULL); BOOL fwPortEnabled = FALSE; m_hr = fwProfile->get_GloballyOpenPorts(&fwOpenPorts); if (FAILED(m_hr)) { printf("get_GloballyOpenPorts failed: 0x%08lx\n", m_hr); goto error; } // 获取端口的设备上下文; m_hr = fwOpenPorts->Item(lPortNumber, netProtocol, &fwOpenPort); if (SUCCEEDED(m_hr)) { m_hr = fwOpenPort->get_Enabled(&fwEnabled); if (FAILED(m_hr)) { printf("get_Enabled failed: 0x%08lx\n", m_hr); goto error; } if (fwEnabled != VARIANT_FALSE) { fwPortEnabled = TRUE; printf("Port %ld is open in the firewall.\n", lPortNumber); } else { printf("Port %ld is not open in the firewall.\n", lPortNumber); } } else { m_hr = S_OK; printf("Port %ld is not open in the firewall.\n", lPortNumber); } error: if (fwOpenPort != NULL) { fwOpenPort->Release(); } if (fwOpenPorts != NULL) { fwOpenPorts->Release(); } return fwPortEnabled; } BOOL WinFireWallXP::FirewallAddPort(IN LONG lPortNumber, IN NET_FW_IP_PROTOCOL netProtocol, IN LPCTSTR lpName) { BOOL fwPortEnabled; BSTR fwBstrName = NULL; INetFwOpenPort *fwOpenPort = NULL; INetFwOpenPorts *fwOpenPorts = NULL; _ASSERT(fwProfile != NULL); _ASSERT(lpName != NULL); fwPortEnabled = FirewallPortIsEnable(lPortNumber, netProtocol); if (!fwPortEnabled) { if (FAILED(HGetLastError())) return FALSE; m_hr = fwProfile->get_GloballyOpenPorts(&fwOpenPorts); if (FAILED(m_hr)) { printf("get_GloballyOpenPorts failed: 0x%08lx\n", m_hr); goto error; } m_hr = CoCreateInstance( __uuidof(NetFwOpenPort), NULL, CLSCTX_INPROC_SERVER, __uuidof(INetFwOpenPort), (void**)&fwOpenPort); if (FAILED(m_hr)) { printf("CoCreateInstance failed: 0x%08lx\n", m_hr); goto error; } m_hr = fwOpenPort->put_Port(lPortNumber); if (FAILED(m_hr)) { printf("put_Port failed: 0x%08lx\n", m_hr); goto error; } m_hr = fwOpenPort->put_Protocol(netProtocol); if (FAILED(m_hr)) { printf("put_Protocol failed: 0x%08lx\n", m_hr); goto error; } fwBstrName = SysAllocString(lpName); if (SysStringLen(fwBstrName) == 0) { m_hr = E_OUTOFMEMORY; printf("SysAllocString failed: 0x%08lx\n", m_hr); goto error; } m_hr = fwOpenPort->put_Name(fwBstrName); if (FAILED(m_hr)) { printf("put_Name failed: 0x%08lx\n", m_hr); goto error; } m_hr = fwOpenPorts->Add(fwOpenPort); if (FAILED(m_hr)) { printf("Add failed: 0x%08lx\n", m_hr); goto error; } m_hr = S_OK; fwPortEnabled = TRUE; printf("Port %ld is now open in the firewall.\n", lPortNumber); } error: SysFreeString(fwBstrName); if (fwOpenPort != NULL) { fwOpenPort->Release(); } if (fwOpenPorts != NULL) { fwOpenPorts->Release(); } return fwPortEnabled; } BOOL WinFireWallXP::FirewallAddPortVista(IN LPCTSTR lpRulePorts, IN LPCTSTR lpRuleInterfaceType, IN LPCTSTR lpRuleName, IN LPCTSTR lpRuleDescription, IN LPCTSTR lpRuleGroupName) { if (lpRulePorts == NULL || lpRulePorts[0] == '\0' || lpRuleName == NULL || lpRuleName[0] == '\0') { return FALSE; } LONG lPort = _tstol(lpRulePorts); // 不处理lpRuleInterfaceType信息,默认any(tcp+udp); NET_FW_IP_PROTOCOL netProctocl = NET_FW_IP_PROTOCOL_ANY; return FirewallAddPort(lPort, netProctocl, lpRuleName); } int WinFireWallXP::FireWallTest() { HRESULT hr = FirewallInit(); if (FAILED(hr)) { printf("WindowsFirewallInitialize failed: 0x%08lx\n", hr); goto error; } hr = FirewallTurnOff(); if (FAILED(hr)) { printf("WindowsFirewallTurnOff failed: 0x%08lx\n", hr); goto error; } hr = FirewallTurnOn(); if (FAILED(hr)) { printf("WindowsFirewallTurnOn failed: 0x%08lx\n", hr); goto error; } hr = FirewallAddApp(L"%ProgramFiles%\\Messenger\\msmsgs.exe", L"Windows Messenger"); if (FAILED(hr)) { printf("WindowsFirewallAddApp failed: 0x%08lx\n", hr); goto error; } hr = FirewallAddPort( 80, NET_FW_IP_PROTOCOL_TCP, L"WWW"); if (FAILED(hr)) { printf("WindowsFirewallPortAdd failed: 0x%08lx\n", hr); goto error; } error: FirewallCleanup(); return 0; } #if _MSC_VER >= 1600 ////////////////////////////////////////////////////////////////////////// WinFireWallVista::WinFireWallVista() :pNetFwPolicy2(NULL) { // Initialize COM. HRESULT hrComInit = CoInitializeEx(0,COINIT_APARTMENTTHREADED); // 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 (hrComInit != RPC_E_CHANGED_MODE) { if (FAILED(hrComInit)) { printf("CoInitializeEx failed: 0x%08lx\n", hrComInit); } } } WinFireWallVista::~WinFireWallVista() { FirewallCleanup(); CoUninitialize(); } BOOL WinFireWallVista::FirewallInit() { m_hr = CoCreateInstance( __uuidof(NetFwPolicy2), NULL, CLSCTX_INPROC_SERVER, __uuidof(INetFwPolicy2), (void**)&pNetFwPolicy2); if (FAILED(m_hr)) { printf("CoCreateInstance for INetFwPolicy2 failed: 0x%08lx\n", m_hr); return FALSE; } return TRUE; } void WinFireWallVista::FirewallCleanup() { if (pNetFwPolicy2 != NULL) { pNetFwPolicy2->Release(); } } /************************************************************************/ /* 函数:[5/8/2017 Jeff]; /* 描述:; /* 参数:; /* [IN] :; /* [OUT] :; /* [IN/OUT] :; /* 返回:void; /* 注意:; /* 示例:; /* /* 修改:; /* 日期:; /* 内容:; /************************************************************************/ BOOL WinFireWallVista::Get_FirewallSettings_PerProfileType(NET_FW_PROFILE_TYPE2 ProfileTypePassed) { VARIANT_BOOL bIsEnabled = FALSE; NET_FW_ACTION action; printf("******************************************\n"); if (SUCCEEDED(pNetFwPolicy2->get_FirewallEnabled(ProfileTypePassed, &bIsEnabled))) { printf("Firewall is %s\n", bIsEnabled ? "enabled" : "disabled"); if (!bIsEnabled) return FALSE; } if (SUCCEEDED(pNetFwPolicy2->get_BlockAllInboundTraffic(ProfileTypePassed, &bIsEnabled))) { printf("Block all inbound traffic is %s\n", bIsEnabled ? "enabled" : "disabled"); if (!bIsEnabled) return FALSE; } if (SUCCEEDED(pNetFwPolicy2->get_NotificationsDisabled(ProfileTypePassed, &bIsEnabled))) { printf("Notifications are %s\n", bIsEnabled ? "disabled" : "enabled"); if (!bIsEnabled) return FALSE; } if (SUCCEEDED(pNetFwPolicy2->get_UnicastResponsesToMulticastBroadcastDisabled(ProfileTypePassed, &bIsEnabled))) { printf("UnicastResponsesToMulticastBroadcast is %s\n", bIsEnabled ? "disabled" : "enabled"); if (!bIsEnabled) return FALSE; } if (SUCCEEDED(pNetFwPolicy2->get_DefaultInboundAction(ProfileTypePassed, &action))) { printf("Default inbound action is %s\n", action != NET_FW_ACTION_BLOCK ? "Allow" : "Block"); if (!bIsEnabled) return FALSE; } if (SUCCEEDED(pNetFwPolicy2->get_DefaultOutboundAction(ProfileTypePassed, &action))) { printf("Default outbound action is %s\n", action != NET_FW_ACTION_BLOCK ? "Allow" : "Block"); if (!bIsEnabled) return FALSE; } printf("\n"); return TRUE; } HRESULT WinFireWallVista::GetCurrentFirewallState() { HRESULT hr = S_FALSE; long CurrentProfilesBitMask = 0; VARIANT_BOOL bActualFirewallEnabled = VARIANT_FALSE; struct ProfileMapElement { NET_FW_PROFILE_TYPE2 Id; LPCWSTR Name; }; ProfileMapElement ProfileMap[3]; ProfileMap[0].Id = NET_FW_PROFILE2_DOMAIN; ProfileMap[0].Name = L"Domain"; ProfileMap[1].Id = NET_FW_PROFILE2_PRIVATE; ProfileMap[1].Name = L"Private"; ProfileMap[2].Id = NET_FW_PROFILE2_PUBLIC; ProfileMap[2].Name = L"Public"; wprintf(L"\n\nCurrent Firewall State:\n"); wprintf(L"-----------------------\n"); hr = pNetFwPolicy2->get_CurrentProfileTypes(&CurrentProfilesBitMask); if (FAILED(hr)) { wprintf(L"Failed to get CurrentProfileTypes. Error: %x.\n", hr); goto CLEANUP; } // The returned 'CurrentProfiles' bitmask can have more than 1 bit set if multiple profiles // are active or current at the same time for (int i = 0; i < 3; i++) { if (CurrentProfilesBitMask & ProfileMap[i].Id) { /*Is Firewall Enabled?*/ hr = pNetFwPolicy2->get_FirewallEnabled(ProfileMap[i].Id, &bActualFirewallEnabled); if (FAILED(hr)) { wprintf(L"Failed to get FirewallEnabled settings for %s profile. Error: %x.\n", ProfileMap[i].Name, hr); goto CLEANUP; } wprintf(L"On %s profile (Current) : Firewall state is %s\n", ProfileMap[i].Name, (bActualFirewallEnabled ? L"ON" : L"OFF")); } } CLEANUP: return hr; } // For the currently active firewall profiles display whether the rule group is enabled or not HRESULT WinFireWallVista::IsRuleGroupCurrentlyEnabled() { HRESULT hr = S_OK; VARIANT_BOOL bActualEnabled = VARIANT_FALSE; BSTR GroupName = SysAllocString(L"File and Printer Sharing"); wprintf(L"\n\nIs 'File and Printer Sharing' rule group currently enabled ?\n"); wprintf(L"------------------------------------------------------------\n"); hr = pNetFwPolicy2->get_IsRuleGroupCurrentlyEnabled(GroupName, &bActualEnabled); if (SUCCEEDED(hr)) { if (VARIANT_TRUE == bActualEnabled && S_OK == hr) { wprintf(L"Rule Group currently enabled on all the current profiles\n"); } else if (VARIANT_TRUE == bActualEnabled && S_FALSE == hr) { wprintf(L"Rule Group currently enabled on some of the current profiles but not on all the current profiles\n"); } else if (VARIANT_FALSE == bActualEnabled) { wprintf(L"Rule Group Currently not enabled on any of the current profiles\n"); } } else { wprintf(L"Failed calling API IsRuleGroupCurrentlyEnabled. Error: 0x %x.\n", hr); goto Cleanup; } Cleanup: SysFreeString(GroupName); return hr; } // For the specified firewall profiles display whether the rule group is enabled or not HRESULT WinFireWallVista::IsRuleGroupEnabled() { HRESULT hr = S_OK; VARIANT_BOOL bActualEnabled = VARIANT_FALSE; BSTR GroupName = SysAllocString(L"File and Printer Sharing"); wprintf(L"\n\nIs 'File and Printer Sharing' rule group enabled in public and private profiles ?\n"); wprintf(L"---------------------------------------------------------------------------------\n"); hr = pNetFwPolicy2->IsRuleGroupEnabled(NET_FW_PROFILE2_PRIVATE | NET_FW_PROFILE2_PUBLIC, GroupName, &bActualEnabled); if (SUCCEEDED(hr)) { if (VARIANT_TRUE == bActualEnabled && S_OK == hr) { wprintf(L"Rule Group currently enabled on both public and private profiles\n"); } else if (VARIANT_TRUE == bActualEnabled && S_FALSE == hr) { wprintf(L"Rule Group currently enabled on either public or private profile but not both\n"); } else if (VARIANT_FALSE == bActualEnabled) { wprintf(L"Rule Group currently disabled on both public and private profiles\n"); } } else { wprintf(L"Failed calling API IsRuleGroupCurrentlyEnabled. Error: 0x %x.\n", hr); goto Cleanup; } Cleanup: SysFreeString(GroupName); return hr; } // For the currently active firewall profiles display whether the changes to firewall rules will take effect or not HRESULT WinFireWallVista::GetLocalPolicyModifyState() { HRESULT hr; NET_FW_MODIFY_STATE modifystate; wprintf(L"\n\nWill changes to firewall rules take effect ?\n"); wprintf(L"--------------------------------------------\n"); hr = pNetFwPolicy2->get_LocalPolicyModifyState(&modifystate); if (FAILED(hr)) { wprintf(L"Failed calling API get_LocalPolicyModifyState. Error: %x.\n", hr); return hr; } if (modifystate == NET_FW_MODIFY_STATE_OK) { if (hr == S_OK) { wprintf(L"Changing or adding firewall rule (or group) to the current profiles will take effect on all current profiles.\n"); } else if (hr == S_FALSE) { wprintf(L"Changing or adding firewall rule (or group) to the current profiles will take effect on only some current profiles but not all.\n"); } } else if (modifystate == NET_FW_MODIFY_STATE_GP_OVERRIDE) { if (hr == S_OK) { wprintf(L"Changing or adding a firewall rule (or group) to the current profiles will not take effect because group policy overrides it on all current profiles.\n"); } else if (hr == S_FALSE) { wprintf(L"Changing or adding a firewall rule (or group) to the current profiles will not take effect because group policy overrides it on some of the current profiles.\n"); } } else if (modifystate == NET_FW_MODIFY_STATE_INBOUND_BLOCKED) { if (hr == S_OK) { wprintf(L"Changing or adding firewall rule (or group) to the current profiles will not take effect because unsolicited inbound traffic is not allowed on all the current profiles.\n"); } else if (hr == S_FALSE) { wprintf(L"Changing or adding firewall rule (or group) to the current profiles will not take effect because unsolicited inbound traffic is not allowed on some of the current profiles.\n"); } } return hr; } // Output properties of a Firewall rule void WinFireWallVista::DumpFWRulesInCollection(INetFwRule* FwRule) { variant_t InterfaceArray; variant_t InterfaceString; VARIANT_BOOL bEnabled; BSTR bstrVal; long lVal = 0; long lProfileBitmask = 0; NET_FW_RULE_DIRECTION fwDirection; NET_FW_ACTION fwAction; struct ProfileMapElement { NET_FW_PROFILE_TYPE2 Id; LPCWSTR Name; }; ProfileMapElement ProfileMap[3]; ProfileMap[0].Id = NET_FW_PROFILE2_DOMAIN; ProfileMap[0].Name = L"Domain"; ProfileMap[1].Id = NET_FW_PROFILE2_PRIVATE; ProfileMap[1].Name = L"Private"; ProfileMap[2].Id = NET_FW_PROFILE2_PUBLIC; ProfileMap[2].Name = L"Public"; wprintf(L"---------------------------------------------\n"); if (SUCCEEDED(FwRule->get_Name(&bstrVal))) { wprintf(L"Name: %s\n", bstrVal); } if (SUCCEEDED(FwRule->get_Description(&bstrVal))) { wprintf(L"Description: %s\n", bstrVal); } if (SUCCEEDED(FwRule->get_ApplicationName(&bstrVal))) { wprintf(L"Application Name: %s\n", bstrVal); } if (SUCCEEDED(FwRule->get_ServiceName(&bstrVal))) { wprintf(L"Service Name: %s\n", bstrVal); } if (SUCCEEDED(FwRule->get_Protocol(&lVal))) { switch (lVal) { case NET_FW_IP_PROTOCOL_TCP: wprintf(L"IP Protocol: %s\n", NET_FW_IP_PROTOCOL_TCP_NAME); break; case NET_FW_IP_PROTOCOL_UDP: wprintf(L"IP Protocol: %s\n", NET_FW_IP_PROTOCOL_UDP_NAME); break; default: break; } if (lVal != NET_FW_IP_VERSION_V4 && lVal != NET_FW_IP_VERSION_V6) { if (SUCCEEDED(FwRule->get_LocalPorts(&bstrVal))) { wprintf(L"Local Ports: %s\n", bstrVal); } if (SUCCEEDED(FwRule->get_RemotePorts(&bstrVal))) { wprintf(L"Remote Ports: %s\n", bstrVal); } } else { if (SUCCEEDED(FwRule->get_IcmpTypesAndCodes(&bstrVal))) { wprintf(L"ICMP TypeCode: %s\n", bstrVal); } } } if (SUCCEEDED(FwRule->get_LocalAddresses(&bstrVal))) { wprintf(L"LocalAddresses: %s\n", bstrVal); } if (SUCCEEDED(FwRule->get_RemoteAddresses(&bstrVal))) { wprintf(L"RemoteAddresses: %s\n", bstrVal); } if (SUCCEEDED(FwRule->get_Profiles(&lProfileBitmask))) { // The returned bitmask can have more than 1 bit set if multiple profiles // are active or current at the same time for (int i = 0; i < 3; i++) { if (lProfileBitmask & ProfileMap[i].Id) { wprintf(L"Profile: %s\n", ProfileMap[i].Name); } } } if (SUCCEEDED(FwRule->get_Direction(&fwDirection))) { switch (fwDirection) { case NET_FW_RULE_DIR_IN: wprintf(L"Direction: %s\n", NET_FW_RULE_DIR_IN_NAME); break; case NET_FW_RULE_DIR_OUT: wprintf(L"Direction: %s\n", NET_FW_RULE_DIR_OUT_NAME); break; default: break; } } if (SUCCEEDED(FwRule->get_Action(&fwAction))) { switch (fwAction) { case NET_FW_ACTION_BLOCK: wprintf(L"Action: %s\n", NET_FW_RULE_ACTION_BLOCK_NAME); break; case NET_FW_ACTION_ALLOW: wprintf(L"Action: %s\n", NET_FW_RULE_ACTION_ALLOW_NAME); break; default: break; } } if (SUCCEEDED(FwRule->get_Interfaces(&InterfaceArray))) { if (InterfaceArray.vt != VT_EMPTY) { SAFEARRAY *pSa = NULL; pSa = InterfaceArray.parray; for (long index = pSa->rgsabound->lLbound; index < (long)pSa->rgsabound->cElements; index++) { SafeArrayGetElement(pSa, &index, &InterfaceString); wprintf(L"Interfaces: %s\n", (BSTR)InterfaceString.bstrVal); } } } if (SUCCEEDED(FwRule->get_InterfaceTypes(&bstrVal))) { wprintf(L"Interface Types: %s\n", bstrVal); } if (SUCCEEDED(FwRule->get_Enabled(&bEnabled))) { if (bEnabled) { wprintf(L"Enabled: %s\n", NET_FW_RULE_ENABLE_IN_NAME); } else { wprintf(L"Enabled: %s\n", NET_FW_RULE_DISABLE_IN_NAME); } } if (SUCCEEDED(FwRule->get_Grouping(&bstrVal))) { wprintf(L"Grouping: %s\n", bstrVal); } if (SUCCEEDED(FwRule->get_EdgeTraversal(&bEnabled))) { if (bEnabled) { wprintf(L"Edge Traversal: %s\n", NET_FW_RULE_ENABLE_IN_NAME); } else { wprintf(L"Edge Traversal: %s\n", NET_FW_RULE_DISABLE_IN_NAME); } } } void WinFireWallVista::Enumerates() { HRESULT hrComInit = S_OK; HRESULT hr = S_OK; ULONG cFetched = 0; CComVariant var; IUnknown *pEnumerator; IEnumVARIANT* pVariant = NULL; INetFwPolicy2 *pNetFwPolicy2 = NULL; INetFwRules *pFwRules = NULL; INetFwRule *pFwRule = NULL; long fwRuleCount; // Retrieve INetFwRules hr = pNetFwPolicy2->get_Rules(&pFwRules); if (FAILED(hr)) { wprintf(L"get_Rules failed: 0x%08lx\n", hr); goto Cleanup; } // Obtain the number of Firewall rules hr = pFwRules->get_Count(&fwRuleCount); if (FAILED(hr)) { wprintf(L"get_Count failed: 0x%08lx\n", hr); goto Cleanup; } wprintf(L"The number of rules in the Windows Firewall are %d\n", fwRuleCount); // Iterate through all of the rules in pFwRules pFwRules->get__NewEnum(&pEnumerator); if (pEnumerator) { hr = pEnumerator->QueryInterface(__uuidof(IEnumVARIANT), (void **)&pVariant); } while (SUCCEEDED(hr) && hr != S_FALSE) { var.Clear(); hr = pVariant->Next(1, &var, &cFetched); if (S_FALSE != hr) { if (SUCCEEDED(hr)) { hr = var.ChangeType(VT_DISPATCH); } if (SUCCEEDED(hr)) { hr = (V_DISPATCH(&var))->QueryInterface(__uuidof(INetFwRule), reinterpret_cast(&pFwRule)); } if (SUCCEEDED(hr)) { // Output the properties of this rule DumpFWRulesInCollection(pFwRule); } } } Cleanup: // Release pFwRule if (pFwRule != NULL) { pFwRule->Release(); } // Release INetFwPolicy2 if (pNetFwPolicy2 != NULL) { pNetFwPolicy2->Release(); } // Uninitialize COM. if (SUCCEEDED(hrComInit)) { CoUninitialize(); } } BOOL WinFireWallVista::FirewallIsOn() { // 防火墙的三部分,只要有一部分未开启,认为未开启; if (Get_FirewallSettings_PerProfileType(NET_FW_PROFILE2_DOMAIN) && Get_FirewallSettings_PerProfileType(NET_FW_PROFILE2_PRIVATE) && Get_FirewallSettings_PerProfileType(NET_FW_PROFILE2_PUBLIC) ) { return TRUE; } else { return FALSE; } } BOOL WinFireWallVista::FirewallTurnOn() { // Disable Windows Firewall for the Domain profile m_hr = pNetFwPolicy2->put_FirewallEnabled(NET_FW_PROFILE2_DOMAIN, VARIANT_TRUE); if (FAILED(m_hr)) { printf("put_FirewallEnabled failed for Domain: 0x%08lx\n", m_hr); return FALSE; } // Disable Windows Firewall for the Private profile m_hr = pNetFwPolicy2->put_FirewallEnabled(NET_FW_PROFILE2_PRIVATE, VARIANT_TRUE); if (FAILED(m_hr)) { printf("put_FirewallEnabled failed for Private: 0x%08lx\n", m_hr); return FALSE; } // Disable Windows Firewall for the Public profile m_hr = pNetFwPolicy2->put_FirewallEnabled(NET_FW_PROFILE2_PUBLIC, VARIANT_TRUE); if (FAILED(m_hr)) { printf("put_FirewallEnabled failed for Public: 0x%08lx\n", m_hr); return FALSE; } return TRUE; } BOOL WinFireWallVista::FirewallTurnOff() { // Disable Windows Firewall for the Domain profile m_hr = pNetFwPolicy2->put_FirewallEnabled(NET_FW_PROFILE2_DOMAIN, VARIANT_FALSE); if (FAILED(m_hr)) { printf("put_FirewallEnabled failed for Domain: 0x%08lx\n", m_hr); return FALSE; } // Disable Windows Firewall for the Private profile m_hr = pNetFwPolicy2->put_FirewallEnabled(NET_FW_PROFILE2_PRIVATE, VARIANT_FALSE); if (FAILED(m_hr)) { printf("put_FirewallEnabled failed for Private: 0x%08lx\n", m_hr); return FALSE; } // Disable Windows Firewall for the Public profile m_hr = pNetFwPolicy2->put_FirewallEnabled(NET_FW_PROFILE2_PUBLIC, VARIANT_FALSE); if (FAILED(m_hr)) { printf("put_FirewallEnabled failed for Public: 0x%08lx\n", m_hr); return FALSE; } return TRUE; } BOOL WinFireWallVista::FirewallAppIsEnable(IN LPCTSTR lpProcessFileName) { return TRUE; } BOOL WinFireWallVista::FirewallAddApp(IN LPCTSTR lpRuleAppPath, IN LPCTSTR lpRuleName) { return FirewallAddAppVista(lpRuleAppPath, lpRuleName); } /************************************************************************/ /* 函数:[5/11/2017 IT]; /* 描述:; /* 参数:; /* [IN] lpRuleAppPath:应用程序路径; /* [IN] lpRuleName:规则名称; /* [IN] lpRuleDescription:规则描述; /* [IN] lpRuleGroupName:规则组名; /* 返回:void; /* 注意:; /* 示例:; /* /* 修改:; /* 日期:; /* 内容:; /************************************************************************/ BOOL WinFireWallVista::FirewallAddAppVista(IN LPCTSTR lpRuleAppPath, IN LPCTSTR lpRuleName, IN LPCTSTR lpRuleDescription /* = NULL */, IN LPCTSTR lpRuleGroupName /* = NULL */) { if (lpRuleAppPath == NULL || lpRuleAppPath[0] == '\0' || lpRuleName == NULL || lpRuleName[0] == '\0' || _taccess(lpRuleAppPath, 0) == ENOENT) { m_hr = S_FALSE; return FALSE; } m_hr = S_OK; INetFwRules *pNetFwRules = NULL; INetFwRule *pNetFwRule = NULL; INetFwRule2 *pNetFwRule2 = NULL; WCHAR pwszTemp[STRING_BUFFER_SIZE] = L""; BSTR RuleName = NULL; BSTR RuleGroupName = NULL; BSTR RuleDescription = NULL; BSTR RuleAppPath = NULL; // 规则名称; RuleName = SysAllocString(lpRuleName); if (NULL == RuleName) { wprintf(L"\nERROR: Insufficient memory\n"); goto Cleanup; } // 规则组名称; RuleGroupName = SysAllocString(lpRuleGroupName ? lpRuleGroupName : _T("")); // Used for grouping together multiple rules if (NULL == RuleGroupName) { wprintf(L"\nERROR: Insufficient memory\n"); goto Cleanup; } // 规则描述; RuleDescription = SysAllocString(lpRuleDescription ? lpRuleDescription : _T("")); if (NULL == RuleDescription) { wprintf(L"\nERROR: Insufficient memory\n"); goto Cleanup; } // 规则应用程序路径; RuleAppPath = SysAllocString(lpRuleAppPath); if (NULL == RuleAppPath) { wprintf(L"\nERROR: Insufficient memory\n"); goto Cleanup; } m_hr = pNetFwPolicy2->get_Rules(&pNetFwRules); if (FAILED(m_hr)) { wprintf(L"Failed to retrieve firewall rules collection : 0x%08lx\n", m_hr); goto Cleanup; } m_hr = CoCreateInstance( __uuidof(NetFwRule), //CLSID of the class whose object is to be created NULL, CLSCTX_INPROC_SERVER, __uuidof(INetFwRule), // Identifier of the Interface used for communicating with the object (void**)&pNetFwRule); if (FAILED(m_hr)) { wprintf(L"CoCreateInstance for INetFwRule failed: 0x%08lx\n", m_hr); goto Cleanup; } m_hr = pNetFwRule->put_Name(RuleName); if (FAILED(m_hr)) { wprintf(L"Failed INetFwRule::put_Name failed with error: 0x %x.\n", m_hr); goto Cleanup; } m_hr = pNetFwRule->put_Grouping(RuleGroupName); if (FAILED(m_hr)) { wprintf(L"Failed INetFwRule::put_Grouping failed with error: 0x %x.\n", m_hr); goto Cleanup; } m_hr = pNetFwRule->put_Description(RuleDescription); if (FAILED(m_hr)) { wprintf(L"Failed INetFwRule::put_Description failed with error: 0x %x.\n", m_hr); goto Cleanup; } m_hr = pNetFwRule->put_Direction(NET_FW_RULE_DIR_IN); if (FAILED(m_hr)) { wprintf(L"Failed INetFwRule::put_Direction failed with error: 0x %x.\n", m_hr); goto Cleanup; } m_hr = pNetFwRule->put_Action(NET_FW_ACTION_ALLOW); if (FAILED(m_hr)) { wprintf(L"Failed INetFwRule::put_Action failed with error: 0x %x.\n", m_hr); goto Cleanup; } m_hr = pNetFwRule->put_ApplicationName(RuleAppPath); if (FAILED(m_hr)) { wprintf(L"Failed INetFwRule::put_ApplicationName failed with error: 0x %x.\n", m_hr); goto Cleanup; } m_hr = pNetFwRule->put_Protocol(6); // TCP if (FAILED(m_hr)) { wprintf(L"Failed INetFwRule::put_Protocol failed with error: 0x %x.\n", m_hr); goto Cleanup; } m_hr = pNetFwRule->put_Profiles(NET_FW_PROFILE2_ALL); if (FAILED(m_hr)) { wprintf(L"Failed INetFwRule::put_Profiles failed with error: 0x %x.\n", m_hr); goto Cleanup; } m_hr = pNetFwRule->put_Enabled(VARIANT_TRUE); if (FAILED(m_hr)) { wprintf(L"Failed INetFwRule::put_Enabled failed with error: 0x %x.\n", m_hr); goto Cleanup; } // Check if INetFwRule2 interface is available (i.e Windows7+) // If supported, then use EdgeTraversalOptions // Else use the EdgeTraversal boolean flag. if (SUCCEEDED(pNetFwRule->QueryInterface(__uuidof(INetFwRule2), (void**)&pNetFwRule2))) { m_hr = pNetFwRule2->put_EdgeTraversalOptions(NET_FW_EDGE_TRAVERSAL_TYPE_DEFER_TO_APP); if (FAILED(m_hr)) { wprintf(L"Failed INetFwRule::put_EdgeTraversalOptions failed with error: 0x %x.\n", m_hr); goto Cleanup; } } else { m_hr = pNetFwRule->put_EdgeTraversal(VARIANT_TRUE); if (FAILED(m_hr)) { wprintf(L"Failed INetFwRule::put_EdgeTraversal failed with error: 0x %x.\n", m_hr); goto Cleanup; } } m_hr = pNetFwRules->Add(pNetFwRule); if (FAILED(m_hr)) { wprintf(L"Failed to add firewall rule to the firewall rules collection : 0x%08lx\n", m_hr); goto Cleanup; } wprintf(L"Successfully added firewall rule !\n"); Cleanup: SysFreeString(RuleName); SysFreeString(RuleGroupName); SysFreeString(RuleDescription); SysFreeString(RuleAppPath); if (pNetFwRule2 != NULL) { pNetFwRule2->Release(); } if (pNetFwRule != NULL) { pNetFwRule->Release(); } if (pNetFwRules != NULL) { pNetFwRules->Release(); } return SUCCEEDED(m_hr); } BOOL WinFireWallVista::FirewallPortIsEnable(IN LONG lPortNumber, IN NET_FW_IP_PROTOCOL netProtocol) { return TRUE; } BOOL WinFireWallVista::FirewallAddPort(IN LONG lPortNumber, IN NET_FW_IP_PROTOCOL netProtocol, IN LPCTSTR lpName) { return TRUE; } /************************************************************************/ /* 函数:[5/11/2017 IT]; /* 描述:; /* 参数:; /* [IN] lpRulePorts:端口号,可以是连续的端口号"2015-2066",也可是多个独立的端口号"2015,2016,2017"; /* [IN] lpRuleInterfaceType:接口类型有4种:"RemoteAccess"远程访问, "Wireless"无线, "Lan"局域网, "All"全部 ; /* [IN/OUT] :; /* 返回:void; /* 注意:; /* 示例:; /* /* 修改:; /* 日期:; /* 内容:; /************************************************************************/ BOOL WinFireWallVista::FirewallAddPortVista(IN LPCTSTR lpRulePorts, IN LPCTSTR lpRuleInterfaceType, IN LPCTSTR lpRuleName, IN LPCTSTR lpRuleDescription /* = NULL */, IN LPCTSTR lpRuleGroupName /* = NULL */) { if (lpRulePorts == NULL || lpRulePorts[0] == '\0' || lpRuleInterfaceType == NULL || lpRuleInterfaceType[0] == '\0') { m_hr = S_FALSE; return FALSE; } m_hr = S_OK; INetFwPolicy2 *pNetFwPolicy2 = NULL; INetFwRules *pFwRules = NULL; INetFwRule *pFwRule = NULL; long CurrentProfilesBitMask = 0; BSTR bstrRuleName = SysAllocString(lpRuleName); BSTR bstrRuleDescription = SysAllocString(lpRuleDescription ? lpRuleDescription : _T("")); BSTR bstrRuleGroup = SysAllocString(lpRuleGroupName ? lpRuleGroupName : _T("")); BSTR bstrRuleLPorts = SysAllocString(lpRulePorts); BSTR bstrRuleInterfaceType = NULL; if ( lpRuleInterfaceType == NULL || lpRuleInterfaceType[0] == '\0') bstrRuleInterfaceType = SysAllocString(_T("ALL")); else { if (_tcsicmp(lpRuleInterfaceType, _T("RemoteAccess")) != 0 && _tcsicmp(lpRuleInterfaceType, _T("Wireless")) != 0 && _tcsicmp(lpRuleInterfaceType, _T("Lan")) != 0 && _tcsicmp(lpRuleInterfaceType, _T("all")) != 0 ) { // 在输入错误的情况下,默认使用all; bstrRuleInterfaceType = SysAllocString(_T("ALL")); } else { bstrRuleInterfaceType = SysAllocString(lpRuleInterfaceType); } } // Retrieve INetFwRules m_hr = pNetFwPolicy2->get_Rules(&pFwRules); if (FAILED(m_hr)) { printf("get_Rules failed: 0x%08lx\n", m_hr); goto Cleanup; } // Retrieve Current Profiles bitmask m_hr = pNetFwPolicy2->get_CurrentProfileTypes(&CurrentProfilesBitMask); if (FAILED(m_hr)) { printf("get_CurrentProfileTypes failed: 0x%08lx\n", m_hr); goto Cleanup; } #if 0 // When possible we avoid adding firewall rules to the Public profile. // If Public is currently active and it is not the only active profile, we remove it from the bitmask if ((CurrentProfilesBitMask & NET_FW_PROFILE2_PUBLIC) && (CurrentProfilesBitMask != NET_FW_PROFILE2_PUBLIC)) { CurrentProfilesBitMask ^= NET_FW_PROFILE2_PUBLIC; } #else // 三个域都能通过; CurrentProfilesBitMask = NET_FW_PROFILE2_ALL; #endif // Create a new Firewall Rule object. m_hr = CoCreateInstance( __uuidof(NetFwRule), NULL, CLSCTX_INPROC_SERVER, __uuidof(INetFwRule), (void**)&pFwRule); if (FAILED(m_hr)) { printf("CoCreateInstance for Firewall Rule failed: 0x%08lx\n", m_hr); goto Cleanup; } // Populate the Firewall Rule object pFwRule->put_Name(bstrRuleName); pFwRule->put_Description(bstrRuleDescription); pFwRule->put_Protocol(NET_FW_IP_PROTOCOL_TCP); pFwRule->put_LocalPorts(bstrRuleLPorts); pFwRule->put_Grouping(bstrRuleGroup); pFwRule->put_InterfaceTypes(bstrRuleInterfaceType); pFwRule->put_Profiles(CurrentProfilesBitMask); pFwRule->put_Action(NET_FW_ACTION_ALLOW); pFwRule->put_Enabled(VARIANT_TRUE); // Add the Firewall Rule m_hr = pFwRules->Add(pFwRule); if (FAILED(m_hr)) { printf("Firewall Rule Add failed: 0x%08lx\n", m_hr); goto Cleanup; } Cleanup: // Free BSTR's SysFreeString(bstrRuleName); SysFreeString(bstrRuleDescription); SysFreeString(bstrRuleGroup); SysFreeString(bstrRuleLPorts); SysFreeString(bstrRuleInterfaceType); // Release the INetFwRule object if (pFwRule != NULL) { pFwRule->Release(); } // Release the INetFwRules object if (pFwRules != NULL) { pFwRules->Release(); } // Release the INetFwPolicy2 object if (pNetFwPolicy2 != NULL) { pNetFwPolicy2->Release(); } return SUCCEEDED(m_hr); } #endif // #ifdef _MSC_VER >= 1500