简体   繁体   中英

Python to remove iptables rule at specific time

I have written a Python-based daemon which blocks malicious IPs based on certain parameters. Now, I want to auto unblock (delete rule) the IP after 1 hour but am not sure how to use timer/scheduler module with my code.

I know the alternative methods can be:

  1. Fail2ban
  2. ipset timeout
  3. iptables -m - recent --seconds switches
  4. cron job

but I have limitations and can't use the above mentioned alternative methods.

My main code is running in a WHILE(1) loop, so its blocking IPs. How to make a parallel module/function inside my python code that will execute the IPTABLES -D command to remove the IPs? Each IP will have its own specific time to be unblocked.

eg

  1. IP1 --- blocked at 01:00:00 hrs --- should be unblocked at 02:00:00 hrs
  2. IP2 --- blocked at 01:10:00 hrs --- should be unblocked at 02:10:00 hrs
  3. IP3 --- blocked at 01:10:10 hrs --- should be unblocked at 02:10:10 hrs

Update:

while True:
    if (ip_found == -1 and port_found == -1):
        os.system("iptables -A INPUT -s "+str(s_addr)+" -j DROP")
        print(str(s_addr) + " was a malcious IP and it is blocked")
    else:
        print("Not a malcious IP")

Logically, you may try the following steps:

  1. Keep the blocked IPs in a queue; in chronological order
  2. Check the queue every second
  3. Unblock the relevant items and dequeue them

You may schedule the dequeue process to run when the first item from the queue is to be removed or unblocked.

If you want the queue and dequeue logic in the same module, you may try something like:

while(1):
    queue(List of IPs)
    dequeue()
    sleep(1000) # sleep for 1 second

Update

Based on the code provided by you and my understanding, I can suggest to implement something like the following:

import os
from datetime import datetime, timedelta
from time import sleep
from sys import stdout

#These values will be populated by the existing logic
ip_found = -1
port_found = -1

#This is some IP address to be blocked
s_addr = ""

#Sorted List of IP addresses
ip_list = []

while True:
    #Create temporary list
    tmp_list = ip_list[:]
    if (ip_found == -1 and port_found == -1):
        tmp_list.append({'ip_address': s_addr, 'blocked_at': datetime.now()})
        ip_list = sorted(tmp_list, key=lambda x: x['blocked_at'])
        os.system("iptables -A INPUT -s "+str(s_addr)+" -j DROP")
        print(str(s_addr) + " was a malcious IP and it is blocked")
    else:
        print("Not a malcious IP")

    unblock_time = datetime.now()
    #Keep unblocking all IPs which have been blocked for 1 hour or more
    while (ip_list[0]["blocked_at"] + timedelta(hours = 1) < unblock_time):
        print(ip_list[0]["blocked_at"])
        unblock_ip = ip_list.pop(0)

        #Implement command to unblock IP
        os.system("-------- command to unblock IP --------")
        print("Unblocked IP " + unblock_ip['ip_address'])

    #if needed output may be flushed to stdout    
    stdout.flush()
    #sleep for 1 second
    sleep(1)
  • You need to write the command to unblock the IP Address
  • Please use this as a starting point and not as a copy-paste solution!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM