How to temporarily open a port in ufw for a specific IP address

ufw

I use ufw (Uncomplicated Firewall) on my web server. Right now I have it set up to allow SSH to the world and fail2ban to prevent massive sign in attempts. The web server has ports 80 and 443 open.

What I would like to do is close SSH access until I need it and then only make it available to my current public IP address that changes periodically. I am thinking of a PHP script over HTTPS that verifies my access and then puts the request into a database. Then a cron job runs a script that reads the database and runs ufw to open the SSH port for just my IP address. After 30 minutes, the rule would be removed and SSH would become inaccessible again. I also want to allow multiple IPs to have temporary access as well and I eventually want to expand to other ports beyond SSH.

What ufw commands should my aforementioned automated scripts run to temporarily add and remove SSH port access for individual IP addresses?

Best Answer

In my opinion a better solution would be to use port knocking, basically you would have "knock" a series of random ports that would then trigger an action on the server, the action would be to allow your IP address to SSH in. You can even setup a timeout so after a while the port would be closed.

For port knocking you could use knockd. You need a knock client too on the other side of course. A knockd config would look like this:

[options]
   logfile = /var/log/knockd.log

[SSH]
  sequence    = 7000,8000,9000
  seq_timeout = 5
  start_command = ufw allow from %IP% to any port 22
  tcpflags    = syn
  cmd_timeout   = 10
  stop_command  = ufw delete allow from %IP% to any port 22