防火墙规则

原文链接地址:https://blog.csdn.net/tajon1226/article/details/52591141、https://blog.csdn.net/chence19871/article/details/50394061

  1 // MicroFireExample.cpp : 定义控制台应用程序的入口点。
  2 //
  3 
  4 #include "stdafx.h"
  5 
  6 #include <windows.h>
  7 #include <stdio.h>
  8 #include <netfw.h>
  9 
 10 #pragma comment( lib, "ole32.lib" )
 11 #pragma comment( lib, "oleaut32.lib" )
 12 
 13 
 14 // Forward declarations
 15 HRESULT     WFCOMInitialize(INetFwPolicy2** ppNetFwPolicy2);
 16 
 17 
 18 
 19 int _tmain(int argc, _TCHAR* argv[])
 20 {
 21     HRESULT hrComInit = S_OK;
 22     HRESULT hr = S_OK;
 23 
 24     INetFwPolicy2 *pNetFwPolicy2 = NULL;
 25     INetFwRules *pFwRules = NULL;
 26     INetFwRule *pFwRule = NULL;
 27 
 28     long CurrentProfilesBitMask = 0;
 29 
 30     BSTR bstrRuleName = SysAllocString(L"OUTBOUND_RULE");
 31     BSTR bstrRuleDescription = SysAllocString(L"Disable outbound network traffic to Dst IP 112.80.248.73 and dst port 80");
 32     BSTR bstrRuleGroup = SysAllocString(L"Sample Rule Group");
 33     //BSTR bstrRuleApplication = SysAllocString(L"%programfiles%\\MyApplication.exe");
 34     BSTR bstrRuleRIP = SysAllocString(L"112.80.248.73");
 35     BSTR bstrRuleRPorts = SysAllocString(L"80");
 36 
 37     // Initialize COM.
 38     hrComInit = CoInitializeEx(
 39         0,
 40         COINIT_APARTMENTTHREADED
 41         );
 42 
 43     // Ignore RPC_E_CHANGED_MODE; this just means that COM has already been
 44     // initialized with a different mode. Since we don't care what the mode is,
 45     // we'll just use the existing mode.
 46     if (hrComInit != RPC_E_CHANGED_MODE)
 47     {
 48         if (FAILED(hrComInit))
 49         {
 50             printf("CoInitializeEx failed: 0x%08lx\n", hrComInit);
 51             goto Cleanup;
 52         }
 53     }
 54 
 55     // Retrieve INetFwPolicy2
 56     hr = WFCOMInitialize(&pNetFwPolicy2);
 57     if (FAILED(hr))
 58     {
 59         goto Cleanup;
 60     }
 61 
 62     // Retrieve INetFwRules
 63     hr = pNetFwPolicy2->get_Rules(&pFwRules);
 64     if (FAILED(hr))
 65     {
 66         printf("get_Rules failed: 0x%08lx\n", hr);
 67         goto Cleanup;
 68     }
 69 
 70     // Retrieve Current Profiles bitmask
 71     hr = pNetFwPolicy2->get_CurrentProfileTypes(&CurrentProfilesBitMask);
 72     if (FAILED(hr))
 73     {
 74         printf("get_CurrentProfileTypes failed: 0x%08lx\n", hr);
 75         goto Cleanup;
 76     }
 77 
 78     // When possible we avoid adding firewall rules to the Public profile.
 79     // If Public is currently active and it is not the only active profile, we remove it from the bitmask
 80     if ((CurrentProfilesBitMask & NET_FW_PROFILE2_PUBLIC) &&
 81         (CurrentProfilesBitMask != NET_FW_PROFILE2_PUBLIC))
 82     {
 83         CurrentProfilesBitMask ^= NET_FW_PROFILE2_PUBLIC;
 84     }
 85 
 86     // Create a new Firewall Rule object.
 87     hr = CoCreateInstance(
 88         __uuidof(NetFwRule),
 89         NULL,
 90         CLSCTX_INPROC_SERVER,
 91         __uuidof(INetFwRule),
 92         (void**)&pFwRule);
 93     if (FAILED(hr))
 94     {
 95         printf("CoCreateInstance for Firewall Rule failed: 0x%08lx\n", hr);
 96         goto Cleanup;
 97     }
 98 
 99     // Populate the Firewall Rule object
100     pFwRule->put_Name(bstrRuleName);
101     pFwRule->put_Description(bstrRuleDescription);
102     //pFwRule->put_ApplicationName(bstrRuleApplication);
103     pFwRule->put_Protocol(NET_FW_IP_PROTOCOL_TCP);
104     pFwRule->put_RemoteAddresses(bstrRuleRIP);
105     pFwRule->put_RemotePorts(bstrRuleRPorts);
106     pFwRule->put_Direction(NET_FW_RULE_DIR_OUT);
107     pFwRule->put_Grouping(bstrRuleGroup);
108     pFwRule->put_Profiles(CurrentProfilesBitMask);
109     pFwRule->put_Action(NET_FW_ACTION_BLOCK);
110     pFwRule->put_Enabled(VARIANT_TRUE);
111 
112     // Add the Firewall Rule
113     hr = pFwRules->Add(pFwRule);
114     if (FAILED(hr))
115     {
116         printf("Firewall Rule Add failed: 0x%08lx\n", hr);
117         goto Cleanup;
118     }
119 
120 Cleanup:
121 
122     // Free BSTR's
123     SysFreeString(bstrRuleName);
124     SysFreeString(bstrRuleDescription);
125     SysFreeString(bstrRuleGroup);
126     //SysFreeString(bstrRuleApplication);
127     SysFreeString(bstrRuleRIP);
128     SysFreeString(bstrRuleRPorts);
129 
130     // Release the INetFwRule object
131     if (pFwRule != NULL)
132     {
133         pFwRule->Release();
134     }
135 
136     // Release the INetFwRules object
137     if (pFwRules != NULL)
138     {
139         pFwRules->Release();
140     }
141 
142     // Release the INetFwPolicy2 object
143     if (pNetFwPolicy2 != NULL)
144     {
145         pNetFwPolicy2->Release();
146     }
147 
148     // Uninitialize COM.
149     if (SUCCEEDED(hrComInit))
150     {
151         CoUninitialize();
152     }
153 
154     return 0;
155 }
156 
157 
158 // Instantiate INetFwPolicy2
159 HRESULT WFCOMInitialize(INetFwPolicy2** ppNetFwPolicy2)
160 {
161     HRESULT hr = S_OK;
162 
163     hr = CoCreateInstance(
164         __uuidof(NetFwPolicy2), 
165         NULL, 
166         CLSCTX_INPROC_SERVER, 
167         __uuidof(INetFwPolicy2), 
168         (void**)ppNetFwPolicy2);
169 
170     if (FAILED(hr))
171     {
172         printf("CoCreateInstance for INetFwPolicy2 failed: 0x%08lx\n", hr);
173         goto Cleanup;        
174     }
175 
176 Cleanup:
177     return hr;
178 }





  1 #include "stdafx.h"
  2 
  3 #include <windows.h>
  4 #include <stdio.h>
  5 #include <netfw.h>
  6 
  7 #pragma comment( lib, "ole32.lib" )
  8 #pragma comment( lib, "oleaut32.lib" )
  9 
 10 
 11 // Forward declarations
 12 HRESULT     WFCOMInitialize(INetFwPolicy2** ppNetFwPolicy2);
 13 
 14 
 15 int __cdecl main()
 16 {
 17     HRESULT hrComInit = S_OK;
 18     HRESULT hr = S_OK;
 19 
 20     INetFwRules *pFwRules = NULL;
 21     INetFwRule *pFwRule = NULL;
 22     INetFwRule *pTmpFwRule = NULL;
 23 
 24     VARIANT_BOOL isServiceRestricted = FALSE;
 25 
 26     INetFwPolicy2 *pNetFwPolicy2 = NULL;
 27     INetFwServiceRestriction *pFwServiceRestriction = NULL;
 28 
 29     // The Service and App name to use
 30     BSTR bstrServiceName = SysAllocString(L"SampleService");   // provide a valid service short name here.
 31     BSTR bstrAppName = SysAllocString(L"E:\\DownCode\\13114500790\\ServiceTest.exe");
 32     // The rule name, description should be provided as indirect strings '@appfullpath,-resource index' for
 33     // localization purposes. 
 34     // Using the strings directly for illustration here.
 35     BSTR bstrRuleName = SysAllocString(L"Allow TCP 12345 to sampleservice");
 36     BSTR bstrRuleDescription = SysAllocString(L"Allow only TCP 12345 traffic to sampleservice service, block everything else");
 37     BSTR bstrRuleLPorts = SysAllocString(L"12345");
 38 
 39     // Error checking for BSTR allocations
 40     if (NULL == bstrServiceName) { printf("Failed to allocate bstrServiceName\n"); goto Cleanup; }
 41     if (NULL == bstrAppName) { printf("Failed to allocate bstrAppName\n"); goto Cleanup; }
 42     if (NULL == bstrRuleName) { printf("Failed to allocate bstrRuleName\n"); goto Cleanup; }
 43     if (NULL == bstrRuleDescription) { printf("Failed to allocate bstrRuleDescription\n"); goto Cleanup; }
 44     if (NULL == bstrRuleLPorts) { printf("Failed to allocate bstrRuleLPorts\n"); goto Cleanup; }
 45 
 46     // Initialize COM.
 47     hrComInit = CoInitializeEx(
 48         0,
 49         COINIT_APARTMENTTHREADED
 50         );
 51 
 52     // Ignore RPC_E_CHANGED_MODE; this just means that COM has already been
 53     // initialized with a different mode. Since we don't care what the mode is,
 54     // we'll just use the existing mode.
 55     if (hrComInit != RPC_E_CHANGED_MODE)
 56     {
 57         if (FAILED(hrComInit))
 58         {
 59             printf("CoInitializeEx failed: 0x%08lx\n", hrComInit);
 60             goto Cleanup;
 61         }
 62     }
 63 
 64     // Retrieve INetFwPolicy2
 65     hr = WFCOMInitialize(&pNetFwPolicy2);
 66     if (FAILED(hr))
 67     {
 68         goto Cleanup;
 69     }
 70 
 71     
 72     // Retrieve INetFwServiceRestriction
 73     hr = pNetFwPolicy2->get_ServiceRestriction(&pFwServiceRestriction);
 74     if (FAILED(hr))
 75     {
 76         printf("get_ServiceRestriction failed: 0x%08lx\n", hr);
 77         goto Cleanup;
 78     }
 79 
 80     // Restrict the sampleservice Service.
 81     // This will add two WSH rules -
 82     //    - a default block all inbound traffic to the service
 83     //    - a default block all outbound traffic from the service
 84     /*
 85     hr = pFwServiceRestriction->RestrictService(bstrServiceName, bstrAppName, TRUE, FALSE);
 86     if (FAILED(hr))
 87     {
 88         printf("RestrictService failed: 0x%08lx\nMake sure you specified a valid service shortname.\n", hr);
 89         goto Cleanup;
 90     }
 91     */
 92 
 93     // If the service does not send/receive any network traffic then you are done. You can skip adding the allow WSH rules below.
 94 
 95     // If the service requires sending/receiving certain traffic, then add 'allow' WSH rules as follows
 96 
 97     // Get the collections of Windows Service Hardening networking rules first
 98     hr = pNetFwPolicy2->get_Rules(&pFwRules);
 99     //hr = pFwServiceRestriction->get_Rules(&pFwRules);
100     if (FAILED(hr))
101     {
102         wprintf(L"get_Rules failed: 0x%08lx\n", hr);
103         goto Cleanup;
104     }
105 
106     // Add inbound WSH allow rule for allowing TCP 12345 to the service
107     // Create a new Rule object.
108     hr = CoCreateInstance(
109         __uuidof(NetFwRule),
110         NULL,
111         CLSCTX_INPROC_SERVER,
112         __uuidof(INetFwRule),
113         (void**)&pFwRule);
114     if (FAILED(hr))
115     {
116         printf("CoCreateInstance for Firewall Rule failed: 0x%08lx\n", hr);
117         goto Cleanup;
118     }
119 
120     // Populate the Rule Name
121     hr = pFwRule->put_Name(bstrRuleName);
122     if (FAILED(hr))
123     {
124         printf("put_Name failed: 0x%08lx\n", hr);
125         goto Cleanup;
126     }
127 
128     // Populate the Rule Description
129     hr = pFwRule->put_Description(bstrRuleDescription);
130     if (FAILED(hr))
131     {
132         printf("put_Description failed: 0x%08lx\n", hr);
133         goto Cleanup;
134     }
135 
136     // Populate the Application Name
137     hr = pFwRule->put_ApplicationName(bstrAppName);
138     if (FAILED(hr))
139     {
140         printf("put_ApplicationName failed: 0x%08lx\n", hr);
141         goto Cleanup;
142     }
143 
144     // Populate the Service Name
145     hr = pFwRule->put_ServiceName(bstrServiceName);
146     if (FAILED(hr))
147     {
148         printf("put_ServiceName failed: 0x%08lx\n", hr);
149         goto Cleanup;
150     }
151 
152     // Populate the Protocol
153     hr = pFwRule->put_Protocol(NET_FW_IP_PROTOCOL_TCP);
154     if (FAILED(hr))
155     {
156         printf("put_Protocol failed: 0x%08lx\n", hr);
157         goto Cleanup;
158     }
159 
160     // Populate the Local Ports
161     hr = pFwRule->put_LocalPorts(bstrRuleLPorts);
162     if (FAILED(hr))
163     {
164         printf("put_LocalPorts failed: 0x%08lx\n", hr);
165         goto Cleanup;
166     }
167 
168     // Populate the rule Action
169     hr = pFwRule->put_Action(NET_FW_ACTION_ALLOW);
170     if (FAILED(hr))
171     {
172         printf("put_Action failed: 0x%08lx\n", hr);
173         goto Cleanup;
174     }
175 
176     // Populate the rule Enabled setting
177     hr = pFwRule->put_Enabled(VARIANT_TRUE);
178     if (FAILED(hr))
179     {
180         printf("put_Enabled failed: 0x%08lx\n", hr);
181         goto Cleanup;
182     }
183 
184 //------------------------------------------------------------------------------------------
185     BSTR bstrPPLiveRuleName = SysAllocString(L"PPLive");
186     hr = pFwRules->Item(bstrRuleName, &pTmpFwRule);
187     /*
188     if (FAILED(hr))
189     {
190         printf("Item failed: 0x%08lx\n", hr);
191         goto Cleanup;
192     }
193     */
194 
195     if (pTmpFwRule != NULL)
196     {
197         printf("规则已存在!\n");
198         VARIANT_BOOL flag;
199         pTmpFwRule->get_Enabled(&flag);
200         if (!flag) //如果规则没打开
201         {
202             pTmpFwRule->put_Enabled(VARIANT_TRUE); //打开规则
203         }
204         int a;
205         a = 3;
206         goto Cleanup;
207     }
208 
209     // Add the Rule to the collection of Windows Service Hardening(WSH) rules
210     hr = pFwRules->Add(pFwRule);
211     if (FAILED(hr))
212     {
213         printf("Firewall Rule Add failed: 0x%08lx\n", hr);
214         goto Cleanup;
215     }
216 
217     Sleep(3000);
218 
219     // Check to see if the Service is Restricted
220     hr = pFwServiceRestriction->ServiceRestricted(bstrServiceName, bstrAppName, &isServiceRestricted);
221     if (FAILED(hr))
222     {
223         printf("ServiceRestricted failed: 0x%08lx\n", hr);
224         goto Cleanup;
225     }
226 
227     if (isServiceRestricted)
228     {
229         printf ("Service was successfully restricted in WSH.\nExcept for TCP 12345 inbound traffic and its responses, all other inbound and outbound connections to and from the service will be blocked.\n");
230     }
231     else
232     {
233         printf ("The Service could not be properly restricted.\n");
234     }
235 
236 
237 Cleanup:
238 
239     // Free BSTR's
240     SysFreeString(bstrServiceName);
241     SysFreeString(bstrAppName);
242     SysFreeString(bstrRuleName);
243     SysFreeString(bstrRuleDescription);
244     SysFreeString(bstrRuleLPorts);
245     SysFreeString(bstrPPLiveRuleName);
246 
247     // Release the INetFwRule object
248     if (pFwRule != NULL)
249     {
250         pFwRule->Release();
251     }
252 
253     // Release the INetFwRules object
254     if (pFwRules != NULL)
255     {
256         pFwRules->Release();
257     }
258 
259     // Release INetFwPolicy2
260     if (pNetFwPolicy2 != NULL)
261     {
262         pNetFwPolicy2->Release();
263     }
264 
265     // Uninitialize COM.
266     if (SUCCEEDED(hrComInit))
267     {
268         CoUninitialize();
269     }
270 
271     getchar();
272     return 0;
273 }
274 
275 
276 // Instantiate INetFwPolicy2
277 HRESULT WFCOMInitialize(INetFwPolicy2** ppNetFwPolicy2)
278 {
279     HRESULT hr = S_OK;
280 
281     hr = CoCreateInstance(
282         __uuidof(NetFwPolicy2), 
283         NULL, 
284         CLSCTX_INPROC_SERVER, 
285         __uuidof(INetFwPolicy2), 
286         (void**)ppNetFwPolicy2);
287 
288     if (FAILED(hr))
289     {
290         printf("CoCreateInstance for INetFwPolicy2 failed: 0x%08lx\n", hr);
291         goto Cleanup;        
292     }
293 
294 Cleanup:
295     return hr;
296 }





XP

  1 #include <windows.h>
  2 #include <crtdbg.h>
  3 #include <netfw.h>
  4 #include <objbase.h>
  5 #include <oleauto.h>
  6 #include <stdio.h>
  7 
  8 #pragma comment( lib, "ole32.lib" )
  9 #pragma comment( lib, "oleaut32.lib" )
 10 
 11 
 12 HRESULT WindowsFirewallInitialize(OUT INetFwProfile** fwProfile)
 13 {
 14     HRESULT hr = S_OK;
 15     INetFwMgr* fwMgr = NULL;
 16     INetFwPolicy* fwPolicy = NULL;
 17 
 18     _ASSERT(fwProfile != NULL);
 19 
 20     *fwProfile = NULL;
 21 
 22     // Create an instance of the firewall settings manager.
 23     hr = CoCreateInstance(
 24         __uuidof(NetFwMgr),
 25         NULL,
 26         CLSCTX_INPROC_SERVER,
 27         __uuidof(INetFwMgr),
 28         (void**)&fwMgr
 29         );
 30     if (FAILED(hr))
 31     {
 32         printf("CoCreateInstance failed: 0x%08lx\n", hr);
 33         goto error;
 34     }
 35 
 36     // Retrieve the local firewall policy.
 37     hr = fwMgr->get_LocalPolicy(&fwPolicy);
 38     if (FAILED(hr))
 39     {
 40         printf("get_LocalPolicy failed: 0x%08lx\n", hr);
 41         goto error;
 42     }
 43 
 44     // Retrieve the firewall profile currently in effect.
 45     hr = fwPolicy->get_CurrentProfile(fwProfile);
 46     if (FAILED(hr))
 47     {
 48         printf("get_CurrentProfile failed: 0x%08lx\n", hr);
 49         goto error;
 50     }
 51 
 52 error:
 53 
 54     // Release the local firewall policy.
 55     if (fwPolicy != NULL)
 56     {
 57         fwPolicy->Release();
 58     }
 59 
 60     // Release the firewall settings manager.
 61     if (fwMgr != NULL)
 62     {
 63         fwMgr->Release();
 64     }
 65 
 66     return hr;
 67 }
 68 
 69 
 70 void WindowsFirewallCleanup(IN INetFwProfile* fwProfile)
 71 {
 72     // Release the firewall profile.
 73     if (fwProfile != NULL)
 74     {
 75         fwProfile->Release();
 76     }
 77 }
 78 
 79 
 80 HRESULT WindowsFirewallIsOn(IN INetFwProfile* fwProfile, OUT BOOL* fwOn)
 81 {
 82     HRESULT hr = S_OK;
 83     VARIANT_BOOL fwEnabled;
 84 
 85     _ASSERT(fwProfile != NULL);
 86     _ASSERT(fwOn != NULL);
 87 
 88     *fwOn = FALSE;
 89 
 90     // Get the current state of the firewall.
 91     hr = fwProfile->get_FirewallEnabled(&fwEnabled);
 92     if (FAILED(hr))
 93     {
 94         printf("get_FirewallEnabled failed: 0x%08lx\n", hr);
 95         goto error;
 96     }
 97 
 98     // Check to see if the firewall is on.
 99     if (fwEnabled != VARIANT_FALSE)
100     {
101         *fwOn = TRUE;
102         printf("The firewall is on.\n");
103     }
104     else
105     {
106         printf("The firewall is off.\n");
107     }
108 
109 error:
110 
111     return hr;
112 }
113 
114 
115 HRESULT WindowsFirewallTurnOn(IN INetFwProfile* fwProfile)
116 {
117     HRESULT hr = S_OK;
118     BOOL fwOn;
119 
120     _ASSERT(fwProfile != NULL);
121 
122     // Check to see if the firewall is off.
123     hr = WindowsFirewallIsOn(fwProfile, &fwOn);
124     if (FAILED(hr))
125     {
126         printf("WindowsFirewallIsOn failed: 0x%08lx\n", hr);
127         goto error;
128     }
129 
130     // If it is, turn it on.
131     if (!fwOn)
132     {
133         // Turn the firewall on.
134         hr = fwProfile->put_FirewallEnabled(VARIANT_TRUE);
135         if (FAILED(hr))
136         {
137             printf("put_FirewallEnabled failed: 0x%08lx\n", hr);
138             goto error;
139         }
140 
141         printf("The firewall is now on.\n");
142     }
143 
144 error:
145 
146     return hr;
147 }
148 
149 
150 HRESULT WindowsFirewallTurnOff(IN INetFwProfile* fwProfile)
151 {
152     HRESULT hr = S_OK;
153     BOOL fwOn;
154 
155     _ASSERT(fwProfile != NULL);
156 
157     // Check to see if the firewall is on.
158     hr = WindowsFirewallIsOn(fwProfile, &fwOn);
159     if (FAILED(hr))
160     {
161         printf("WindowsFirewallIsOn failed: 0x%08lx\n", hr);
162         goto error;
163     }
164 
165     // If it is, turn it off.
166     if (fwOn)
167     {
168         // Turn the firewall off.
169         hr = fwProfile->put_FirewallEnabled(VARIANT_FALSE);
170         if (FAILED(hr))
171         {
172             printf("put_FirewallEnabled failed: 0x%08lx\n", hr);
173             goto error;
174         }
175 
176         printf("The firewall is now off.\n");
177     }
178 
179 error:
180 
181     return hr;
182 }
183 
184 
185 HRESULT WindowsFirewallAppIsEnabled(
186                                     IN INetFwProfile* fwProfile,
187                                     IN const wchar_t* fwProcessImageFileName,
188                                     OUT BOOL* fwAppEnabled
189                                     )
190 {
191     HRESULT hr = S_OK;
192     BSTR fwBstrProcessImageFileName = NULL;
193     VARIANT_BOOL fwEnabled;
194     INetFwAuthorizedApplication* fwApp = NULL;
195     INetFwAuthorizedApplications* fwApps = NULL;
196 
197     _ASSERT(fwProfile != NULL);
198     _ASSERT(fwProcessImageFileName != NULL);
199     _ASSERT(fwAppEnabled != NULL);
200 
201     *fwAppEnabled = FALSE;
202 
203     // Retrieve the authorized application collection.
204     hr = fwProfile->get_AuthorizedApplications(&fwApps);
205     if (FAILED(hr))
206     {
207         printf("get_AuthorizedApplications failed: 0x%08lx\n", hr);
208         goto error;
209     }
210 
211     // Allocate a BSTR for the process image file name.
212     fwBstrProcessImageFileName = SysAllocString(fwProcessImageFileName);
213     if (fwBstrProcessImageFileName == NULL)
214     {
215         hr = E_OUTOFMEMORY;
216         printf("SysAllocString failed: 0x%08lx\n", hr);
217         goto error;
218     }
219 
220     // Attempt to retrieve the authorized application.
221     hr = fwApps->Item(fwBstrProcessImageFileName, &fwApp);
222     if (SUCCEEDED(hr))
223     {
224         // Find out if the authorized application is enabled.
225         hr = fwApp->get_Enabled(&fwEnabled);
226         if (FAILED(hr))
227         {
228             printf("get_Enabled failed: 0x%08lx\n", hr);
229             goto error;
230         }
231 
232         if (fwEnabled != VARIANT_FALSE)
233         {
234             // The authorized application is enabled.
235             *fwAppEnabled = TRUE;
236 
237             printf(
238                 "Authorized application %lS is enabled in the firewall.\n",
239                 fwProcessImageFileName
240                 );
241         }
242         else
243         {
244             printf(
245                 "Authorized application %lS is disabled in the firewall.\n",
246                 fwProcessImageFileName
247                 );
248         }
249     }
250     else
251     {
252         // The authorized application was not in the collection.
253         hr = S_OK;
254 
255         printf(
256             "Authorized application %lS is disabled in the firewall.\n",
257             fwProcessImageFileName
258             );
259     }
260 
261 error:
262 
263     // Free the BSTR.
264     SysFreeString(fwBstrProcessImageFileName);
265 
266     // Release the authorized application instance.
267     if (fwApp != NULL)
268     {
269         fwApp->Release();
270     }
271 
272     // Release the authorized application collection.
273     if (fwApps != NULL)
274     {
275         fwApps->Release();
276     }
277 
278     return hr;
279 }
280 
281 
282 HRESULT WindowsFirewallAddApp(
283                               IN INetFwProfile* fwProfile,
284                               IN const wchar_t* fwProcessImageFileName,
285                               IN const wchar_t* fwName
286                               )
287 {
288     HRESULT hr = S_OK;
289     BOOL fwAppEnabled;
290     BSTR fwBstrName = NULL;
291     BSTR fwBstrProcessImageFileName = NULL;
292     INetFwAuthorizedApplication* fwApp = NULL;
293     INetFwAuthorizedApplications* fwApps = NULL;
294 
295     _ASSERT(fwProfile != NULL);
296     _ASSERT(fwProcessImageFileName != NULL);
297     _ASSERT(fwName != NULL);
298 
299     // First check to see if the application is already authorized.
300     hr = WindowsFirewallAppIsEnabled(
301         fwProfile,
302         fwProcessImageFileName,
303         &fwAppEnabled
304         );
305     if (FAILED(hr))
306     {
307         printf("WindowsFirewallAppIsEnabled failed: 0x%08lx\n", hr);
308         goto error;
309     }
310 
311     // Only add the application if it isn't already authorized.
312     if (!fwAppEnabled)
313     {
314         // Retrieve the authorized application collection.
315         hr = fwProfile->get_AuthorizedApplications(&fwApps);
316         if (FAILED(hr))
317         {
318             printf("get_AuthorizedApplications failed: 0x%08lx\n", hr);
319             goto error;
320         }
321 
322         // Create an instance of an authorized application.
323         hr = CoCreateInstance(
324             __uuidof(NetFwAuthorizedApplication),
325             NULL,
326             CLSCTX_INPROC_SERVER,
327             __uuidof(INetFwAuthorizedApplication),
328             (void**)&fwApp
329             );
330         if (FAILED(hr))
331         {
332             printf("CoCreateInstance failed: 0x%08lx\n", hr);
333             goto error;
334         }
335 
336         // Allocate a BSTR for the process image file name.
337         fwBstrProcessImageFileName = SysAllocString(fwProcessImageFileName);
338         if (fwBstrProcessImageFileName == NULL)
339         {
340             hr = E_OUTOFMEMORY;
341             printf("SysAllocString failed: 0x%08lx\n", hr);
342             goto error;
343         }
344 
345         // Set the process image file name.
346         hr = fwApp->put_ProcessImageFileName(fwBstrProcessImageFileName);
347         if (FAILED(hr))
348         {
349             printf("put_ProcessImageFileName failed: 0x%08lx\n", hr);
350             goto error;
351         }
352 
353         // Allocate a BSTR for the application friendly name.
354         fwBstrName = SysAllocString(fwName);
355         if (SysStringLen(fwBstrName) == 0)
356         {
357             hr = E_OUTOFMEMORY;
358             printf("SysAllocString failed: 0x%08lx\n", hr);
359             goto error;
360         }
361 
362         // Set the application friendly name.
363         hr = fwApp->put_Name(fwBstrName);
364         if (FAILED(hr))
365         {
366             printf("put_Name failed: 0x%08lx\n", hr);
367             goto error;
368         }
369 
370 
371         // Add the application to the collection.
372         hr = fwApps->Add(fwApp);
373         if (FAILED(hr))
374         {
375             printf("Add failed: 0x%08lx\n", hr);
376             goto error;
377         }
378 
379         printf(
380             "Authorized application %lS is now enabled in the firewall.\n",
381             fwProcessImageFileName
382             );
383     }
384 
385 error:
386 
387     // Free the BSTRs.
388     SysFreeString(fwBstrName);
389     SysFreeString(fwBstrProcessImageFileName);
390 
391     // Release the authorized application instance.
392     if (fwApp != NULL)
393     {
394         fwApp->Release();
395     }
396 
397     // Release the authorized application collection.
398     if (fwApps != NULL)
399     {
400         fwApps->Release();
401     }
402 
403     return hr;
404 }
405 
406 
407 HRESULT WindowsFirewallPortIsEnabled(
408                                      IN INetFwProfile* fwProfile,
409                                      IN LONG portNumber,
410                                      IN NET_FW_IP_PROTOCOL ipProtocol,
411                                      OUT BOOL* fwPortEnabled
412                                      )
413 {
414     HRESULT hr = S_OK;
415     VARIANT_BOOL fwEnabled;
416     INetFwOpenPort* fwOpenPort = NULL;
417     INetFwOpenPorts* fwOpenPorts = NULL;
418 
419     _ASSERT(fwProfile != NULL);
420     _ASSERT(fwPortEnabled != NULL);
421 
422     *fwPortEnabled = FALSE;
423 
424     // Retrieve the globally open ports collection.
425     hr = fwProfile->get_GloballyOpenPorts(&fwOpenPorts);
426     if (FAILED(hr))
427     {
428         printf("get_GloballyOpenPorts failed: 0x%08lx\n", hr);
429         goto error;
430     }
431 
432     // Attempt to retrieve the globally open port.
433     hr = fwOpenPorts->Item(portNumber, ipProtocol, &fwOpenPort);
434     if (SUCCEEDED(hr))
435     {
436         // Find out if the globally open port is enabled.
437         hr = fwOpenPort->get_Enabled(&fwEnabled);
438         if (FAILED(hr))
439         {
440             printf("get_Enabled failed: 0x%08lx\n", hr);
441             goto error;
442         }
443 
444         if (fwEnabled != VARIANT_FALSE)
445         {
446             // The globally open port is enabled.
447             *fwPortEnabled = TRUE;
448 
449             printf("Port %ld is open in the firewall.\n", portNumber);
450         }
451         else
452         {
453             printf("Port %ld is not open in the firewall.\n", portNumber);
454         }
455     }
456     else
457     {
458         // The globally open port was not in the collection.
459         hr = S_OK;
460 
461         printf("Port %ld is not open in the firewall.\n", portNumber);
462     }
463 
464 error:
465 
466     // Release the globally open port.
467     if (fwOpenPort != NULL)
468     {
469         fwOpenPort->Release();
470     }
471 
472     // Release the globally open ports collection.
473     if (fwOpenPorts != NULL)
474     {
475         fwOpenPorts->Release();
476     }
477 
478     return hr;
479 }
480 
481 
482 HRESULT WindowsFirewallPortAdd(
483                                IN INetFwProfile* fwProfile,
484                                IN LONG portNumber,
485                                IN NET_FW_IP_PROTOCOL ipProtocol,
486                                IN const wchar_t* name
487                                )
488 {
489     HRESULT hr = S_OK;
490     BOOL fwPortEnabled;
491     BSTR fwBstrName = NULL;
492     INetFwOpenPort* fwOpenPort = NULL;
493     INetFwOpenPorts* fwOpenPorts = NULL;
494 
495     _ASSERT(fwProfile != NULL);
496     _ASSERT(name != NULL);
497 
498     // First check to see if the port is already added.
499     hr = WindowsFirewallPortIsEnabled(
500         fwProfile,
501         portNumber,
502         ipProtocol,
503         &fwPortEnabled
504         );
505     if (FAILED(hr))
506     {
507         printf("WindowsFirewallPortIsEnabled failed: 0x%08lx\n", hr);
508         goto error;
509     }
510 
511     // Only add the port if it isn't already added.
512     if (!fwPortEnabled)
513     {
514         // Retrieve the collection of globally open ports.
515         hr = fwProfile->get_GloballyOpenPorts(&fwOpenPorts);
516         if (FAILED(hr))
517         {
518             printf("get_GloballyOpenPorts failed: 0x%08lx\n", hr);
519             goto error;
520         }
521 
522         // Create an instance of an open port.
523         hr = CoCreateInstance(
524             __uuidof(NetFwOpenPort),
525             NULL,
526             CLSCTX_INPROC_SERVER,
527             __uuidof(INetFwOpenPort),
528             (void**)&fwOpenPort
529             );
530         if (FAILED(hr))
531         {
532             printf("CoCreateInstance failed: 0x%08lx\n", hr);
533             goto error;
534         }
535 
536         // Set the port number.
537         hr = fwOpenPort->put_Port(portNumber);
538         if (FAILED(hr))
539         {
540             printf("put_Port failed: 0x%08lx\n", hr);
541             goto error;
542         }
543 
544         // Set the IP protocol.
545         hr = fwOpenPort->put_Protocol(ipProtocol);
546         if (FAILED(hr))
547         {
548             printf("put_Protocol failed: 0x%08lx\n", hr);
549             goto error;
550         }
551 
552         // Allocate a BSTR for the friendly name of the port.
553         fwBstrName = SysAllocString(name);
554         if (SysStringLen(fwBstrName) == 0)
555         {
556             hr = E_OUTOFMEMORY;
557             printf("SysAllocString failed: 0x%08lx\n", hr);
558             goto error;
559         }
560 
561         // Set the friendly name of the port.
562         hr = fwOpenPort->put_Name(fwBstrName);
563         if (FAILED(hr))
564         {
565             printf("put_Name failed: 0x%08lx\n", hr);
566             goto error;
567         }
568 
569         // Opens the port and adds it to the collection.
570         hr = fwOpenPorts->Add(fwOpenPort);
571         if (FAILED(hr))
572         {
573             printf("Add failed: 0x%08lx\n", hr);
574             goto error;
575         }
576 
577         printf("Port %ld is now open in the firewall.\n", portNumber);
578     }
579 
580 error:
581 
582     // Free the BSTR.
583     SysFreeString(fwBstrName);
584 
585     // Release the open port instance.
586     if (fwOpenPort != NULL)
587     {
588         fwOpenPort->Release();
589     }
590 
591     // Release the globally open ports collection.
592     if (fwOpenPorts != NULL)
593     {
594         fwOpenPorts->Release();
595     }
596 
597     return hr;
598 }
599 
600 
601 int  main(int argc, TCHAR* argv[])
602 {
603     HRESULT hr = S_OK;
604     HRESULT comInit = E_FAIL;
605     INetFwProfile* fwProfile = NULL;
606 
607     // Initialize COM.
608     comInit = CoInitializeEx(
609         0,
610         COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE
611         );
612 
613     // Ignore RPC_E_CHANGED_MODE; this just means that COM has already been
614     // initialized with a different mode. Since we don't care what the mode is,
615     // we'll just use the existing mode.
616     if (comInit != RPC_E_CHANGED_MODE)
617     {
618         hr = comInit;
619         if (FAILED(hr))
620         {
621             printf("CoInitializeEx failed: 0x%08lx\n", hr);
622             goto error;
623         }
624     }
625 
626     INetFwRules *fwRules;
627 
628 
629 
630     // Retrieve the firewall profile currently in effect.
631     hr = WindowsFirewallInitialize(&fwProfile);
632     if (FAILED(hr))
633     {
634         printf("WindowsFirewallInitialize failed: 0x%08lx\n", hr);
635         goto error;
636     }
637 
638 
639     // Turn off the firewall.
640     hr = WindowsFirewallTurnOff(fwProfile);
641     if (FAILED(hr))
642     {
643         printf("WindowsFirewallTurnOff failed: 0x%08lx\n", hr);
644         goto error;
645     }
646 
647     // Turn on the firewall.
648     hr = WindowsFirewallTurnOn(fwProfile);
649     if (FAILED(hr))
650     {
651         printf("WindowsFirewallTurnOn failed: 0x%08lx\n", hr);
652         goto error;
653     }
654 
655 
656     // Add Windows Messenger to the authorized application collection.
657     hr = WindowsFirewallAddApp(
658         fwProfile,
659         L"E:\\Code_Factory\\NetDemo\\NetDemo V1.0-UDP\\Release\\NetDemo.exe",
660         L"NetDemo"
661         );
662     if (FAILED(hr))
663     {
664         printf("WindowsFirewallAddApp failed: 0x%08lx\n", hr);
665         goto error;
666     }
667 
668     // Add TCP::80 to list of globally open ports.
669     hr = WindowsFirewallPortAdd(fwProfile, 80, NET_FW_IP_PROTOCOL_TCP, L"WWW");
670     if (FAILED(hr))
671     {
672         printf("WindowsFirewallPortAdd failed: 0x%08lx\n", hr);
673         goto error;
674     }
675 
676 error:
677 
678     // Release the firewall profile.
679     WindowsFirewallCleanup(fwProfile);
680 
681     // Uninitialize COM.
682     if (SUCCEEDED(comInit))
683     {
684         CoUninitialize();
685     }
686 
687     getchar();
688     return 0;
689 }

 

转载于:https://www.cnblogs.com/wuyuan2011woaini/p/10455512.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值