An encrypted SSH connection allows complete access to your machine. However, unless you diligently manage all security updates to your OS and SSH Server, there is a possibility that your SSH server gets compromised.
Typically, system administrators restrict access to the SSH Server (Port 22) to selected IPs. The limitation in opening the Port 22 to selected Static IPs is that you will not be able to connect to it when you are on the move, and need to access your machine from, say a mobile phone.
To overcome this limitation, I have written a script that uses a combination of a web server and
iptables firewall, and grants access to Port 22 (or any other Port) on demand to an IP you prefer. It can also work equally well on an AWS EC2 machine where you open
Port 22 for all IPs
(0.0.0.0/0) using a Security Group, and then restrict access via
iptables to that EC2 instance.
I will be using
- Apache with PHP
Step 1 – Grant Access to
On Ubuntu, Apache runs with
www-data as a user. We will allow
www-data user to execute
sudo without a password
At the end of the file, add the following
www-data ALL=NOPASSWD: /sbin/iptables
The line above allows
www-data access to the command
iptables, without a password.
sudo is indeed working for
Run the following command to verify.
sudo -H -u www-data bash -c 'sudo iptables -L'
Note: It should not ask any password for
www-data and show the data related to
iptables as shown in the screenshot above.
Step 2 – Allow Authenticated Access to Ports via The Web
We will now create a file that we’ll put on a web server for easy access. Save the following in a file, and place it on a safe, https protected location on your web server.
- Get the code at GitHub –https://github.com/technotablet/open-port-dynamically/blob/master/openport.php
- Change the password and the port that you wish to open in openport.php
Now access the
openport.php script from your browser.
Complete GitHub Repository at https://github.com/technotablet/open-port-dynamically
For example: https://yourdomain.com/openport.php (Replace the URL with your domain & script name)
- The ports that you open via the script tend to remain open like forever. You should ideally setup a firewall script via
iptablesand reset the rules at a pre-defined interval.
- Instead of using a fixed password, you can try out an OTP version (tutorial coming soon).
- For RDP and other ports that are not on the same machine, but are within the same network, you can setup Port Forwarding based on
iptablesand do the relevant NAT based redirection.