def __setup_ban(self, cmd_array, bannedIPV4, bannedMAC): # Add BanTable and BanChain # ban_table = OBJ.TABLE(family=ENUM.ADDR_FAMILY.INET, name="BanTable") ban_ip_chain = OBJ.CHAIN(family=ban_table.family, table=ban_table.name, name="BanIpChain", type=ENUM.CHAIN_TYPE.FILTER, hook=ENUM.CHAIN_HOOK.FORWARD, prio=ENUM.CHAIN_PRIORITY.NF_IP_PRI_FILTER, policy=ENUM.CHAIN_POLICY.ACCEPT) ban_mac_chain = OBJ.CHAIN(family=ban_table.family, table=ban_table.name, name="BanMacChain", type=ENUM.CHAIN_TYPE.FILTER, hook=ENUM.CHAIN_HOOK.INPUT, prio=ENUM.CHAIN_PRIORITY.NF_IP_PRI_FILTER, policy=ENUM.CHAIN_POLICY.ACCEPT) cmd_array.append(CMD.ADD(add=ban_table)) cmd_array.append(CMD.ADD(add=ban_ip_chain)) cmd_array.append(CMD.ADD(add=ban_mac_chain)) # Add BannedIPv4 and BannedMAC sets # banned_ipv4_set = OBJ.SET(family=ban_table.family, table=ban_table.name, name="BannedIPv4", type=ENUM.SET_TYPE.IPV4_ADDR, elem=bannedIPV4) banned_mac_set = OBJ.SET(family=ban_table.family, table=ban_table.name, name="BannedMAC", type=ENUM.SET_TYPE.ETHER_ADDR, elem=bannedMAC) cmd_array.append(CMD.ADD(add=banned_ipv4_set)) cmd_array.append(CMD.ADD(add=banned_mac_set)) # Add rule dropping packets with @BannedIPv4 and @BannedMAC adresses # the_payload = EXP.REFERENCE_PAYLOAD(protocol="ip", field="daddr") the_match = STAT.MATCH(left=the_payload, right="@BannedIPv4", op=ENUM.OPERATOR.EQUAL) cmd_array.append( CMD.ADD( add=OBJ.RULE(family=ban_table.family, table=ban_table.name, chain=ban_ip_chain.name, expr=[the_match, STAT.VERDICT_DROP()]))) the_payload = EXP.REFERENCE_PAYLOAD(protocol="ether", field="saddr") the_match = STAT.MATCH(left=the_payload, right="@BannedMAC", op=ENUM.OPERATOR.EQUAL) cmd_array.append( CMD.ADD( add=OBJ.RULE(family=ban_table.family, table=ban_table.name, chain=ban_mac_chain.name, expr=[the_match, STAT.VERDICT_DROP()])))
def test_CMD_execution(self): table_1 = OBJ.TABLE(family=ENUM.ADDR_FAMILY.INET, name="table_1") res = pynft.execute(CMD.ADD(add=table_1), "add_table_1") self.assertEqual(res['rc'], 0)
def ban_ipv4(self, addr: str): cmdObj = CMD.ADD(add=OBJ.ELEMENT(family=ENUM.ADDR_FAMILY.INET, table="BanTable", name="BannedIPv4", elem=addr)) return self.nft.execute(cmdObj, "ban_ipv4: " + addr)
def test_type_checking(self): table_1 = OBJ.TABLE(family="a very illegal string", name="table_1") res = pynft.execute(CMD.ADD(add=table_1), "add_table_1") self.assertEqual(res['rc'], -1)