Windows过滤平台 – 如何根据本地端口阻止传入连接?

我正在尝试使用WFP设置一些filter来阻止到本地服务器的入站连接(例如,侦听端口8080的Web服务器)。

我有一个可以基于远程端口阻止的filter工作,所以我可以阻止我的机器上的进程建立到端口8080的任何连接,但我无法弄清楚如何阻止来自另一台机器的传入连接基于本地8080港口?

这是我的代码,它基于远程端口进行阻塞:(它是使用P / invoke的C#,但它与用C ++编写的几乎相同)

var RemotePort = 8080 # port to block // connect to engine var session = new Fwpm.FWPM_SESSION0 { flags = Fwpm.FWPM_SESSION_FLAG_DYNAMIC }; UInt32 engineHandle; UnsafeNativeMethods.FwpmEngineOpen0(null, Fwpm.RPC_C_AUTHN_WINNT, IntPtr.Zero, session, out engineHandle // create a subLayer to attach filters to var subLayerGuid = Guid.NewGuid(); var subLayer = new Fwpm.FWPM_SUBLAYER0(); subLayer.subLayerKey = subLayerGuid; subLayer.displayData.name = DisplayName; subLayer.displayData.description = DisplayName; subLayer.flags = 0; subLayer.weight = 0x100; UnsafeNativeMethods.FwpmSubLayerAdd0(engineHandle, subLayer, IntPtr.Zero) var condition = new Fwpm.FWPM_FILTER_CONDITION0 { fieldKey = Fwpm.FWPM_CONDITION_IP_REMOTE_PORT, matchType = Fwpm.FWP_MATCH_TYPE.FWP_MATCH_EQUAL, conditionValue = { type = Fwpm.FWP_DATA_TYPE.FWP_UINT16, uint16 = RemotePort } } // create the filter itself var fwpFilter = new Fwpm.FWPM_FILTER0(); fwpFilter.layerKey = Fwpm.FWPM_LAYER_ALE_AUTH_CONNECT_V4; fwpFilter.action.type = Fwpm.FWP_ACTION_BLOCK; fwpFilter.subLayerKey = subLayerGuid; fwpFilter.weight.type = Fwpm.FWP_DATA_TYPE.FWP_EMPTY; // auto-weight. fwpFilter.numFilterConditions = (uint)1; var condsArray = new[]{ condition }; var condsPtr = SafeNativeMethods.MarshalArray(condsArray); // helper to create a native array from a C# one fwpFilter.filterCondition = condsPtr; fwpFilter.displayData.name = DisplayName; fwpFilter.displayData.description = DisplayName; // add the filter UInt64 filterId = 0L; UnsafeNativeMethods.FwpmFilterAdd0(engineHandle, ref fwpFilter, IntPtr.Zero, out filterId)); 

如上所述,此代码可以阻止与远程端口8080的连接。要阻止与本地端口8080的连接,我修改了代码,如下所示:

 var LocalPort = 8080; var condition = new Fwpm.FWPM_FILTER_CONDITION0 { fieldKey = Fwpm.FWPM_CONDITION_IP_LOCAL_PORT, matchType = Fwpm.FWP_MATCH_TYPE.FWP_MATCH_EQUAL, conditionValue = { type = Fwpm.FWP_DATA_TYPE.FWP_UINT16, uint16 = LocalPort } } // create the filter itself var fwpFilter = new Fwpm.FWPM_FILTER0(); fwpFilter.layerKey = Fwpm.FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V4; 

MSDN暗示FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V4是阻止入站连接的正确位置,但这根本不起作用。 我已经尝试了FWPM_LAYER_ALE_RESOURCE_ASSIGNMENT_V4以及其他一些图层,但无论我尝试过什么,我总能在我的机器上建立从另一台机器到服务器8080端口的连接。

任何帮助将非常感激

您应该能够在支持FWPM_CONDITION_IP_LOCAL_PORT条件的任何INBOUND或RECV层上创建该filter,要搜索的资源是:

http://msdn.microsoft.com/en-us/library/windows/hardware/ff549939%28v=vs.85%29.aspx

然而,并非所有流量都通过每一层,我绝不是专家,但一种方法是在每个适用层(半打左右的filter)中添加这样的filter,看看是否有效。 如果是这样,那么您一次删除一个filter,直到找到实际需要的集合。 我最近的一个项目需要4层才能阻止我感兴趣的所有流量。

可能值得注意的一个重要警告是,localhost上的流量可能不会通过任何WFP层(或者可能只是它跳过的入站层,我不记得了)。 因此,您可以使用WFP来阻止与端口的远程连接,但本地连接仍可能通过。