示例#1
1
/******************************************************************
 AddPortException

********************************************************************/
static HRESULT AddPortException(
    __in LPCWSTR wzName,
    __in int iProfile,
    __in_opt LPCWSTR wzRemoteAddresses,
    __in BOOL fIgnoreFailures,
    __in LPCWSTR wzPort,
    __in int iProtocol,
    __in LPCWSTR wzDescription
    )
{
    HRESULT hr = S_OK;
    BSTR bstrName = NULL;
    INetFwRules* pNetFwRules = NULL;
    INetFwRule* pNetFwRule = NULL;

    // convert to BSTRs to make COM happy
    bstrName = ::SysAllocString(wzName);
    ExitOnNull(bstrName, hr, E_OUTOFMEMORY, "failed SysAllocString for name");

    // get the collection of firewall rules
    hr = GetFirewallRules(fIgnoreFailures, &pNetFwRules);
    ExitOnFailure(hr, "failed to get firewall rules object");
    if (S_FALSE == hr) // user or package author chose to ignore missing firewall
    {
        ExitFunction();
    }

    // try to find it (i.e., support reinstall)
    hr = pNetFwRules->Item(bstrName, &pNetFwRule);
    if (HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND) == hr)
    {
        hr = CreateFwRuleObject(bstrName, iProfile, wzRemoteAddresses, wzPort, iProtocol, wzDescription, &pNetFwRule);
        ExitOnFailure(hr, "failed to create FwRule object");

        // enable it
        hr = pNetFwRule->put_Enabled(VARIANT_TRUE);
        ExitOnFailure(hr, "failed to to enable port exception");

        // add it to the list of authorized ports
        hr = pNetFwRules->Add(pNetFwRule);
        ExitOnFailure(hr, "failed to add app to the authorized ports list");
    }
    else
    {
        // we found an existing port exception (if we succeeded, that is)
        ExitOnFailure(hr, "failed trying to find existing port rule");

        // enable it (just in case it was disabled)
        pNetFwRule->put_Enabled(VARIANT_TRUE);
    }

LExit:
    ReleaseBSTR(bstrName);
    ReleaseObject(pNetFwRules);
    ReleaseObject(pNetFwRule);

    return fIgnoreFailures ? S_OK : hr;
}
int __cdecl main()
{
    HRESULT hrComInit = S_OK;
    HRESULT hr = S_OK;

    INetFwPolicy2 *pNetFwPolicy2 = NULL;
    INetFwRules *pFwRules = NULL;
    INetFwRule *pFwRule = NULL;

    long CurrentProfilesBitMask = 0;

    // The rule name, description, and group are provided as indirect strings for 
    // localization purposes. These resource strings can be found in the rc file

    BSTR bstrRuleName = SysAllocString(L"@Add_GRE_Rule.exe,-128");
    BSTR bstrRuleDescription = SysAllocString(L"@Add_GRE_Rule.exe,-129");
    BSTR bstrRuleGroup = SysAllocString(L"@Add_GRE_Rule.exe,-127");

    // Error checking for BSTR allocations
    if (NULL == bstrRuleName) { printf("Failed to allocate bstrRuleName\n"); goto Cleanup; }
    if (NULL == bstrRuleDescription) { printf("Failed to allocate bstrRuleDescription\n"); goto Cleanup; }
    if (NULL == bstrRuleGroup) { printf("Failed to allocate bstrRuleGroup\n"); goto Cleanup; }

    // Initialize COM.
    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);
            goto Cleanup;
        }
    }

    // Retrieve INetFwPolicy2
    hr = WFCOMInitialize(&pNetFwPolicy2);
    if (FAILED(hr))
    {
        goto Cleanup;
    }

    // Retrieve INetFwRules
    hr = pNetFwPolicy2->get_Rules(&pFwRules);
    if (FAILED(hr))
    {
        printf("get_Rules failed: 0x%08lx\n", hr);
        goto Cleanup;
    }

    // Retrieve Current Profiles bitmask
    hr = pNetFwPolicy2->get_CurrentProfileTypes(&CurrentProfilesBitMask);
    if (FAILED(hr))
    {
        printf("get_CurrentProfileTypes failed: 0x%08lx\n", hr);
        goto Cleanup;
    }

    // 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;
    }

    // Create a new Firewall Rule object.
    hr = CoCreateInstance(
                __uuidof(NetFwRule),
                NULL,
                CLSCTX_INPROC_SERVER,
                __uuidof(INetFwRule),
                (void**)&pFwRule);
    if (FAILED(hr))
    {
        printf("CoCreateInstance for Firewall Rule failed: 0x%08lx\n", hr);
        goto Cleanup;
    }

    // Populate the Firewall Rule Name
    hr = pFwRule->put_Name(bstrRuleName);
    if (FAILED(hr))
    {
        printf("put_Name failed: 0x%08lx\n", hr);
        goto Cleanup;
    }

    // Populate the Firewall Rule Description
    hr = pFwRule->put_Description(bstrRuleDescription);
    if (FAILED(hr))
    {
        printf("put_Description failed: 0x%08lx\n", hr);
        goto Cleanup;
    }

    // Populate the Firewall Rule Protocol
    hr = pFwRule->put_Protocol(47);
    if (FAILED(hr))
    {
        printf("put_Protocol failed: 0x%08lx\n", hr);
        goto Cleanup;
    }

    // Populate the Firewall Rule Group
    hr = pFwRule->put_Grouping(bstrRuleGroup);
    if (FAILED(hr))
    {
        printf("put_Grouping failed: 0x%08lx\n", hr);
        goto Cleanup;
    }

    // Populate the Firewall Rule Profiles
    hr = pFwRule->put_Profiles(CurrentProfilesBitMask);
    if (FAILED(hr))
    {
        printf("put_Profiles failed: 0x%08lx\n", hr);
        goto Cleanup;
    }

    // Populate the Firewall Rule Action
    hr = pFwRule->put_Action(NET_FW_ACTION_ALLOW);
    if (FAILED(hr))
    {
        printf("put_Action failed: 0x%08lx\n", hr);
        goto Cleanup;
    }

    // Populate the Firewall Rule Enabled
    hr = pFwRule->put_Enabled(VARIANT_TRUE);
    if (FAILED(hr))
    {
        printf("put_Enabled failed: 0x%08lx\n", hr);
        goto Cleanup;
    }

    // Add the Firewall Rule
    hr = pFwRules->Add(pFwRule);
    if (FAILED(hr))
    {
        printf("Firewall Rule Add failed: 0x%08lx\n", hr);
        goto Cleanup;
    }

Cleanup:

    // Free BSTR's
    SysFreeString(bstrRuleName);
    SysFreeString(bstrRuleDescription);
    SysFreeString(bstrRuleGroup);

    // 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();
    }

    // Uninitialize COM.
    if (SUCCEEDED(hrComInit))
    {
        CoUninitialize();
    }
   
    return 0;
}
示例#3
0
/******************************************************************
 RemoveException - Removes the exception rule with the given name.

********************************************************************/
static HRESULT RemoveException(
    __in LPCWSTR wzName, 
    __in BOOL fIgnoreFailures
    )
{
    HRESULT hr = S_OK;;
    INetFwRules* pNetFwRules = NULL;

    // convert to BSTRs to make COM happy
    BSTR bstrName = ::SysAllocString(wzName);
    ExitOnNull(bstrName, hr, E_OUTOFMEMORY, "failed SysAllocString for path");

    // get the collection of firewall rules
    hr = GetFirewallRules(fIgnoreFailures, &pNetFwRules);
    ExitOnFailure(hr, "failed to get firewall rules object");
    if (S_FALSE == hr) // user or package author chose to ignore missing firewall
    {
        ExitFunction();
    }

    hr = pNetFwRules->Remove(bstrName);
    ExitOnFailure(hr, "failed to remove authorized app");

LExit:
    ReleaseBSTR(bstrName);
    ReleaseObject(pNetFwRules);

    return fIgnoreFailures ? S_OK : hr;
}
ErrorCode FirewallSecurityProvider::RemoveFirewallRule(
    wstring const & policyName)
{
#if defined(PLATFORM_UNIX)
    return CleanupRulesForAllProfiles(policyName, 0);
#else
    if (this->State.Value != FabricComponentState::Opened)
    {
        WriteInfo(
            TraceFirewallSecurityProvider,
            Root.TraceId,
            "FirewallSecurityProvider cannot remove rule '{0}' since provider is not open", policyName);

        return ErrorCode(ErrorCodeValue::OperationFailed);
    }

    HRESULT hr = S_OK;

    hr = CoInitializeEx(
        0,
        COINIT_MULTITHREADED
    );
    if (FAILED(hr))
    {
        ErrorCode error = ErrorCode::FromHResult(hr);
        WriteError(TraceFirewallSecurityProvider, Root.TraceId, "Failed to create CoInitialize {0}", error);
        return error;
    }

    INetFwPolicy2* fwPolicy;
    hr = CoCreateInstance(
        __uuidof(NetFwPolicy2),
        NULL,
        CLSCTX_INPROC_SERVER,
        __uuidof(INetFwPolicy2),
        (void**)&fwPolicy);
    if (FAILED(hr))
    {
        ErrorCode error = ErrorCode::FromHResult(hr);
        WriteError(TraceFirewallSecurityProvider, Root.TraceId, "Failed to create INetFwPolicy2 {0}", error);
        return error;
    }

    INetFwRules *pFwRules = NULL;

    // Retrieve INetFwRules
    hr = fwPolicy->get_Rules(&pFwRules);
    if (FAILED(hr))
    {
        WriteWarning(
            TraceFirewallSecurityProvider,
            Root.TraceId,
            "Failed to get firewall rules, hresult {0}", hr);
        return ErrorCode::FromHResult(hr);
    }
    else
    {
        auto error = CleanupRulesForAllProfiles(policyName, pFwRules);
        WriteTrace(
            error.ToLogLevel(),
            TraceFirewallSecurityProvider,
            Root.TraceId,
            "Removing firewall rules for policy {0} returned error {1}", policyName, error);
        // Release the INetFwRules object
        if (pFwRules != NULL)
        {
            pFwRules->Release();
        }
        if (fwPolicy != NULL)
        {
            fwPolicy->Release();
        }
        return error;
    }
#endif    
}
ErrorCode FirewallSecurityProvider::ConfigurePortFirewallPolicy(
    wstring const & policyName,
    vector<LONG> ports)
{
    if (this->State.Value != FabricComponentState::Opened)
    {
        WriteInfo(
            TraceFirewallSecurityProvider,
            Root.TraceId,
            "FirewallSecurityProvider cannot open ports for policy '{0}' since provider is not open", policyName);

        return ErrorCode(ErrorCodeValue::OperationFailed);
    }

    HRESULT hr = S_OK;

#if defined(PLATFORM_UNIX)
    auto err = CleanupRulesForAllProfiles(policyName, 0);
    if (!err.IsSuccess())
    {
        WriteInfo(
                TraceFirewallSecurityProvider,
                Root.TraceId,
                "Failed to remove firewall rule, error {0}, rulename", err, policyName);
    }

    wstring ruleDescription = wformatString("Rule for WindowsFabric service package {0}", policyName);
    for (auto it = profilesEnabled_.begin(); it != profilesEnabled_.end() && SUCCEEDED(hr); ++it)
    {
        for (auto iter = ports.begin(); iter != ports.end(); ++iter)
        {
            for (auto it1 = allprotocols_.begin(); it1 != allprotocols_.end(); it1++)
            {
                hr = this->AddRule(0,
                                   FirewallSecurityProvider::GetFirewallRuleName(policyName, false, *it, *it1),
                                   ruleDescription,
                                   *it,
                                   *it1,
                                   *iter,
                                   false);
                if (SUCCEEDED(hr))
                {
                    hr = this->AddRule(0,
                                       FirewallSecurityProvider::GetFirewallRuleName(policyName, true, *it, *it1),
                                       ruleDescription,
                                       *it,
                                       *it1,
                                       *iter,
                                       true);
                }
                if (FAILED(hr))
                {
                    break;
                }
            }
        }
    }
    return ErrorCode::FromHResult(hr);
#else

    hr = CoInitializeEx(
        0,
        COINIT_MULTITHREADED
    );
    if (FAILED(hr))
    {
        ErrorCode error = ErrorCode::FromHResult(hr);
        WriteError(TraceFirewallSecurityProvider, Root.TraceId, "Failed to create CoInitialize {0}", error);
        return error;
    }
    INetFwPolicy2* fwPolicy;
    hr = CoCreateInstance(
        __uuidof(NetFwPolicy2),
        NULL,
        CLSCTX_INPROC_SERVER,
        __uuidof(INetFwPolicy2),
        (void**)&fwPolicy);
    if (FAILED(hr))
    {
        ErrorCode error = ErrorCode::FromHResult(hr);
        WriteError(TraceFirewallSecurityProvider, Root.TraceId, "Failed to create INetFwPolicy2 {0}", error);
        return error;
    }
    INetFwRules *pFwRules = NULL;

    LONG currentProfilesBitMask = 0;

    // Retrieve INetFwRules
    hr = fwPolicy->get_Rules(&pFwRules);
    if (FAILED(hr))
    {
        WriteWarning(
            TraceFirewallSecurityProvider,
            Root.TraceId,
            "Failed to get firewall rules, hresult {0}", hr);
    }
    else
    {
        auto err = CleanupRulesForAllProfiles(policyName, pFwRules);
        if (!err.IsSuccess())
        {
            WriteInfo(
                TraceFirewallSecurityProvider,
                Root.TraceId,
                "Failed to remove firewall rule, error {0}, rulename", err, policyName);
        }
        // Retrieve Current Profiles bitmask
        hr = fwPolicy->get_CurrentProfileTypes(&currentProfilesBitMask);
        if (SUCCEEDED(hr))
        {

            wstring ruleDescription = wformatString("Rule for WindowsFabric service package {0}", policyName);
            bool currentUserProfileEnabled = false;
            for (auto it = profilesEnabled_.begin(); it != profilesEnabled_.end() && SUCCEEDED(hr); ++it)
            {
                for (auto iter = ports.begin(); iter != ports.end(); ++iter)
                {
                    for (auto it1 = allprotocols_.begin(); it1 != allprotocols_.end(); it1++)
                    {
                        hr = this->AddRule(
                            pFwRules,
                            FirewallSecurityProvider::GetFirewallRuleName(policyName, false, *it, *it1),
                            ruleDescription,
                            *it,
                            *it1,
                            *iter,
                            false);
                        if (SUCCEEDED(hr))
                        {
                            hr = this->AddRule(
                                pFwRules,
                                FirewallSecurityProvider::GetFirewallRuleName(policyName, true, *it, *it1),
                                ruleDescription,
                                *it,
                                *it1,
                                *iter,
                                true);
                        }
                        if (FAILED(hr))
                        {
                            break;
                        }
                    }
                }
                if (*it & currentProfilesBitMask)
                {
                    currentUserProfileEnabled = true;
                }
            }
            if (!currentUserProfileEnabled)
            {
                WriteWarning(
                    TraceFirewallSecurityProvider,
                    Root.TraceId,
                    "Did not enable firewallpolicy for current profile {0}", currentProfilesBitMask);
            }
        }
        else
        {
            WriteWarning(
                TraceFirewallSecurityProvider,
                Root.TraceId,
                "Failed to get current profile types, hresult {0}", hr);
        }
        // Release the INetFwRules object
        if (pFwRules != NULL)
        {
            pFwRules->Release();
        }
        if (fwPolicy != NULL)
        {
            fwPolicy->Release();
        }
    }
    return ErrorCode::FromHResult(hr);
#endif    
}
int __cdecl main()
{
    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;

    // Initialize COM.
    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))
        {
            wprintf(L"CoInitializeEx failed: 0x%08lx\n", hrComInit);
            goto Cleanup;
        }
    }

    // Retrieve INetFwPolicy2
    hr = WFCOMInitialize(&pNetFwPolicy2);
    if (FAILED(hr))
    {
        goto Cleanup;
    }

    // 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<void**>(&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();
    }
   
    return 0;
}