def nft(cmds): global _nftables if _nftables is None: LOGGER.info('Loading nftables') _nftables = nftables.Nftables() _nftables.validator = nftables.SchemaValidator() if len(cmds) == 0: return None for cmd in cmds: log_cmd(LOGGER, cmd) payload = { 'nftables': cmds } _nftables_lock.acquire() rc, output, err = _nftables.json_cmd(payload) _nftables_lock.release() if output != '': LOGGER.trace('NFT Output: %s', json.dumps(output, indent=2)) if rc != 0: raise NftablesError(rc, err, cmds) return output
def main(): # init libnftables nft = nftables.Nftables() # configure library behavior nft.set_json_output(True) nft.set_stateless_output(False) nft.set_service_output(False) nft.set_reversedns_output(False) nft.set_numeric_proto_output(True) rc, output, error = nft.cmd("list ruleset") if rc != 0: # do proper error handling here, exceptions etc print("ERROR: running cmd 'list ruleset'") print(error) exit(1) if len(output) == 0: # more error control print("ERROR: no output from libnftables") exit(0) print("raw libnftables JSON output:\n{}".format(output)) data_structure = json.loads(output) print("native python data structure:\n{}".format(data_structure))
def main(): # init libnftables nft = nftables.Nftables() # configure library behavior nft.set_json_output(True) nft.set_stateless_output(False) nft.set_service_output(False) nft.set_reversedns_output(False) nft.set_numeric_proto_output(True) # list all nftables stateful counters configured in the system ruleset = nft_cmd(nft, "list counters") for counter in _find_objects(ruleset, "counter"): print('Counter "{}" in table {} {}: packets {} bytes {}'.format( counter["name"], counter["family"], counter["table"], counter["packets"], counter["bytes"], )) # list all nftables quota objects configured in the system ruleset = nft_cmd(nft, "list quotas") for quota in _find_objects(ruleset, "quota"): print('Quota "{}" in table {} {}: used {} out of {} bytes (inv: {})'. format( quota["name"], quota["family"], quota["table"], quota["used"], quota["bytes"], quota["inv"], ))
def main(): nft = nftables.Nftables() # STEP 1: load your JSON content try: data_structure = json.loads(NFTABLES_JSON) except json.decoder.JSONDecodeError as e: print(f"ERROR: failed to decode JSON: {e}") exit(1) # STEP 2: validate it with the libnftables JSON schema try: nft.json_validate(data_structure) except Exception as e: print(f"ERROR: failed validating json schema: {e}") exit(1) # STEP 3: finally, run the JSON command print(f"INFO: running json cmd: {data_structure}") rc, output, error = nft.json_cmd(data_structure) if rc != 0: # do proper error handling here, exceptions etc print(f"ERROR: running json cmd: {error}") exit(1) if len(output) != 0: # more error control? print(f"WARNING: output: {output}") # ok! exit(0)
def __init__(self): self.nft = nftables.Nftables( sofile='/usr/lib/x86_64-linux-gnu/libnftables.so.1') self.nft.set_echo_output(True) self.nft.set_handle_output(True) self.mitm_proxy_local_port = 8443 self.nat_table = 'mitm_capture' self.chain = 'prerouting'
def main(): nft = nftables.Nftables() nft.set_json_output(True) nft.set_handle_output( True) # important! to get the rule handle when getting the ruleset # STEP 1: load the ruleset in JSON format into the kernel # see other examples in this tutorial to know more about how this works load_ruleset(nft) # STEP 2: get the ruleset from the kernel, im JSON format and search for # all rules with a 'counter' expression on them, get their information kernel_ruleset = get_ruleset(nft) info_about_rules_to_delete = search_rules_with_counter(kernel_ruleset) # STEP 3: generate a new command to delete all interesting rules, validate and run it delete_rules_command = dict(nftables=[]) delete_rules_command["nftables"] = [] delete_rules_command["nftables"].append( dict(metainfo=dict(json_schema_version=1))) for rule_info in info_about_rules_to_delete: delete_rules_command["nftables"].append( dict(delete=dict(rule=rule_info))) try: nft.json_validate(delete_rules_command) except Exception as e: print(f"ERROR: failed validating JSON schema: {e}") exit(1) rc, output, error = nft.json_cmd(delete_rules_command) if rc != 0: # do proper error handling here, exceptions etc print(f"ERROR: running JSON cmd: {error}") exit(1) if len(output) != 0: # more error control? print(f"WARNING: output: {output}") # ok! exit(0)
def main(argv): write_debug_file(argv[0], "Started") # validate json and get command msg = setup_and_check_message(argv) nft = nftables.Nftables() nft.set_json_output(True) nft.set_stateless_output(False) nft.set_service_output(False) nft.set_reversedns_output(False) nft.set_numeric_proto_output(True) if msg.command < 0: sys.exit(OS_INVALID) if msg.command == ADD_COMMAND: """ Start Custom Key At this point, it is necessary to select the keys from the alert and add them into the keys array. """ alert = msg.alert["parameters"]["alert"] ip_to_ban = alert["data"]["srcip"] keys = [alert["rule"]["id"]] ip_type = validIPAddress(ip_to_ban) if ip_type == "invalid": write_debug_file( argv[0], "Invalid IP provided, can't add/delete it from blacklist") sys.exit(OS_INVALID) """ End Custom Key """ action = send_keys_and_check_message(argv, keys) # if necessary, abort execution if action != CONTINUE_COMMAND: if action == ABORT_COMMAND: write_debug_file(argv[0], "Aborted") sys.exit(OS_SUCCESS) else: write_debug_file(argv[0], "Invalid command") sys.exit(OS_INVALID) """ Start Custom Action Add """ rc, output, error = nft.cmd("add element %s filter blacklist { %s }" % (ip_type, ip_to_ban)) if rc > 0: write_debug_file(argv[0], error) else: write_debug_file(argv[0], "%s has been added in the blacklist" % ip_to_ban) """ End Custom Action Add """ elif msg.command == DELETE_COMMAND: """ Start Custom Action Delete """ alert = msg.alert["parameters"]["alert"] ip_to_ban = alert["data"]["srcip"] ip_type = validIPAddress(ip_to_ban) if ip_type == "invalid": write_debug_file( argv[0], "Invalid IP provided, can't add/delete it from blacklist") sys.exit(OS_INVALID) rc, output, error = nft.cmd( "delete element %s filter blacklist { %s }" % (ip_type, ip_to_ban)) if rc > 0: write_debug_file(argv[0], error) else: write_debug_file( argv[0], "%s has been removed from the blacklist" % ip_to_ban) """ End Custom Action Delete """ else: write_debug_file(argv[0], "Invalid command") write_debug_file(argv[0], "Ended") sys.exit(OS_SUCCESS)
def __init__(self): self.nft = nftables.Nftables() self.nft.set_json_output(True)