Categories
Interior

How to use port knocking on linux (and why you shouldn’t)

By Jithin on February 27th, 2017

In this tutorial we can check What is Port Knocking?

Security is one of the most important parameter that should be kept in account when you are on a hosting account. There are many security measures that can be used to ensure your server is secure. There are different methods to implement the security. You could secure the website and the whole server. Port knocking is a technique used to secure your server. If you own a VPS or a dedicated server, using port knocking is a good idea to ensure improved security. In this article, we are going to see what the Port Knocking is and how does it secure the server.

What is Port Knocking

Port Knocking is a technique that is used to improve the security of a webserver. It works with the help of the firewall. This method helps to identify which users are legitimate, so that blocking is effective. These ports will be closed on the firewall by default. A pre-defined sequence is needed to implement Port Knocking. If one tries with connection attempts according to this sequence, then the port that needs to be open will be opened. This will allow for the customer to connect to correct port. The primary advantage of this method is that the ports protected by Port Knocking will be shown unavailable for a usual port scan.

Please be aware that the Port Knocking shouldn’t be used as the only security measure, but also along with the other security strategies.

The IPTABLES and Port Knocking

Iptables need to be installed on the server to implement Port Knocking. As we’ve seen earlier, Port Knocking works with the firewall, iptables. To understand how Port Knocking works, we need to discuss iptables. Here is a brief overview.

IPTABLES

IPtables is a user-space application. It allows us to configure the Linux kernel firewall. The iptables maintains a number of chains like the Input Chain, the Output Chain, the Forward Chain, etc. We can configure these chains with the users IP address accessing the server. We can allow or block users by adding them to the appropriate chains.

The format of an iptables will be as below.

target port opt source destination

ACCEPT all — anywhere anywhere

To add a rule to the INPUT chain of the iptables, it will need the format specified below.

iptables -A INPUT -p tcp –dport 80 -j ACCEPT

How Does Port Knocking work

There is a module in the iptables called “recent”. It is used to dynamically create a list of IP addresses. This list will be based on the connection whether the connection was successful or unsuccessful. The firewall will find out the connections made by the user. There will be a pre-defined sequence that will be used by the firewall. If failed attempts from a user occur in this sequence. The desired port will be opened, so that the customer can connect to the port.

A sample session with the port knocking will be looking like the below.

$ ssh [email protected] # No response (Ctrl+c to exit)

$ nmap -Pn –host_timeout 201 –max-retries 0 -p 1122 host #knocking port 1122

$ nmap -Pn –host_timeout 201 –max-retries 0 -p 2233 host #knocking port 2233

$ ssh [email protected] # Now logins are allowed

There are various methods to implement Port Knocking. A specialized daemon can be used to handle the Port Knocking or an iptables.rules file can be created.

Port Knocking using a specialized daemon

We can use a particular daemon so that the daemon will handle the port knocking. It will allow you to set this up easily.

Port Knocking using IPTABLES

To use the Port Knocking with the iptables only, we need to create a custom file. Create the file /etc/iptables/iptables.rules for handling Port Knocking. We are going to see a sample file here. The rules are set up to open the port user defined SSH port 8855 after a sequence of knocks to the ports 1111 then 2222 and 3333. Please keep in mind that we are implementing the single knocking here. Primarily, we should define the default filter policies and chains for the script. We are using the OUTPUT ACCEPT in this example.

We can define the filter as following

:FORWARD DROP [0:0]

:OUTPUT ACCEPT [0:0]

Now, we need to add the following rules. These rules are for the main chain.

-A TRAFFIC -m state –state ESTABLISHED,RELATED -j ACCEPT

-A TRAFFIC -m state –state NEW -m tcp -p tcp –dport 8855 -m recent –rcheck –seconds 30 –name SSH2 -j ACCEPT

The third line on the above script will open the port 8855 for 30 seconds only if the IP address that is trying to connect is on the list SSH2. Please be aware that the port will be closed after 30 seconds and a new Port Knocking attempt can be initiated from that IP address too.

The full content of the file iptables.rules will be looking like the following.

:FORWARD DROP [0:0]

:OUTPUT ACCEPT [0:0]

# TRAFFIC chain for Port Knocking. The correct port sequence in this example is 8881 -> 7777 -> 9991; any other sequence will drop the traffic

-A INPUT -j TRAFFIC

-A TRAFFIC -p icmp –icmp-type any -j ACCEPT

-A TRAFFIC -m state –state ESTABLISHED,RELATED -j ACCEPT

-A TRAFFIC -m state –state NEW -m tcp -p tcp –dport 22 -m recent –rcheck –seconds 30 –name SSH2 -j ACCEPT

-A TRAFFIC -m state –state NEW -m tcp -p tcp -m recent –name SSH2 –remove -j DROP

-A TRAFFIC -m state –state NEW -m tcp -p tcp –dport 9991 -m recent –rcheck –name SSH1 -j SSH-INPUTTWO

-A TRAFFIC -m state –state NEW -m tcp -p tcp -m recent –name SSH1 –remove -j DROP

-A TRAFFIC -m state –state NEW -m tcp -p tcp –dport 7777 -m recent –rcheck –name SSH0 -j SSH-INPUT

-A TRAFFIC -m state –state NEW -m tcp -p tcp -m recent –name SSH0 –remove -j DROP

-A TRAFFIC -m state –state NEW -m tcp -p tcp –dport 8881 -m recent –name SSH0 –set -j DROP

-A SSH-INPUT -m recent –name SSH1 –set -j DROP

-A SSH-INPUTTWO -m recent –name SSH2 –set -j DROP

-A TRAFFIC -j DROP

# END or further rules

If you need any further assistance please contact our support department.

Normally for a server I like to lock down SSH and other non-public service to only be accessible by certain IP addresses. However this is not always practical if the business doesn’t have static IP addresses or if outside developers need access.

I heard about Port Knocking a while ago and have finally had chance to look into it as a solution to the above problem. As a result of this I have a load of questions I hope people can help me out with.

  • Has anyone deployed it within their Business / Organisation and can offer any advise?
  • What is the best knocking Daemon to run under Linux?
  • What are the best clients for Linux, Windows and OSX?
  • What is the recommend length for knock sequence and is it best to use TCP, UDP or Both?
  • What are the associated downsides and issues with using it?
  • Is it just Security Through Obscurity?
  • Are there any alternatives to the port knocking approach?

7 Answers 7

While I have not deployed it yet, I know many people who have deployed it. Every single one of them have noted a significant reduction in the amount of bandwidth consumed by things like SSH brute-force attacks as a result.

However, that is not to say that there are not downsides. AFAIK, there are no kernel-based port knocking implementations available, which for me would be the real key to adoption. Port knocking daemons rely on reading failed (and filtered/prohibited) log file entries from a firewall system. That’s all fine and dandy, but what happens if the filesystem gets full? What happens when the daemon gets killed because of some runaway process eating up the system’s RAM and swap? What happens if something else which either of those two things depend on just up and stop working? You most likely end up with a server that you will have to physically access. That could wind up being more costly than is reasonable, especially if you are more than a few tens of miles away from the server and do not have anyone that you can call to get there in a hurry.

One thing that I can say is that it is not “security through obscurity”. Port knocking is a form of authentication, and like any authentication system it can be made to be as simple or complex as desired. Something as simple as “knock on port 10,000 + realPortNumber” can be done, which would amount to a trivial break, or the port knocking might itself be used to transmit some form of real authentication (say, 1 block of AES encoded data given a key derived by some other method). It would not be feasible to use port knocking to transmit large amounts of data, though, because it would take significantly longer than just sending a single packet, and if the packet is over TCP than at least it can be known if it was received successfully or encountered some form of error.

One interesting question that this brings up, however, is how to manage the log files—userland implementations mostly require the log files in order to determine whether or not a knock has been successfully sent, and what happens if those logs are leaked? Authentication data becomes known, and that is obviously not a very good thing.

I cannot tell you whether or not to use port knocking in your setup. I am not yet, and I am not 100% certain that I ever will be. It makes more sense to me to use strong authentication systems that are based on strong cryptography (such as a PKI infrastructure) than it does to throw port knocking in the way. Also, adding a single point of failure to access critical infrastructure, to me anyway, seems like a bad idea, and way more difficult to properly support with any sort of guarantee. Again, though, that is based on the notion of the port-knocking software being not integrated with the firewall at the operating system kernel level; if that ever changes, I may also change how I feel about using it.

didymus

New Member

I’m not 100% sure if this can be done, but I imagine it has to be possible. I’m just not sure why I’ve never encountered it being set up like this. Maybe I’m just inexperienced. Please enlighten me. I’m having trouble searching about this.

dos2unix

Well-Known Member

Edit you sshd_config (this is normally in /etc/ssh

#Port 22
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

Change this line to whatever subnet you are on.

f33dm3bits

Gold Member

Tolkem

Well-Known Member

How to use port knocking on linux (and why you shouldn’t)

How to Use Port Knocking To Secure SSH Service in Linux

KGIII

Super Moderator

This is the method I use. I just don’t forward the port at the router.

It’s definitely the lazy method and probably not the greatest idea if there’s any chance of someone malicious being on the same LAN.

dcbrown73

New Member

First, allow ssh in hosts.allow from ONLY your subnet.

Edit /etc/hosts.allow and add:
sshd: 192.168.1.0/24 (or whatever your subnet is)

Then deny all for ssh in hosts.deny.

Edit /etc/hosts.deny and add.
sshd: ALL

Oh and don’t forget to disable ssh as root in your sshd_config

dcbrown73

New Member

This is the method I use. I just don’t forward the port at the router.

It’s definitely the lazy method and probably not the greatest idea if there’s any chance of someone malicious being on the same LAN.

Port forwarding ssh is incredibly dangerous. Install a vpn. (SoftEther, OpenVPN, or Pritunl or something)

Besides, if you port forward ssh, the subnet blocking won’t matter because the router likely has NAT enabled. It will just appear as though they are coming from the router which is on the subnet you likely do not want to block.

I check /var/log/secure and I have these logs:

It seems someone tries to log in by SSH. I disable login by root user and enable public/private key login, but is this a DDoS attack? And does it use RAM/CPU?

What should I do?

How to use port knocking on linux (and why you shouldn’t)

7 Answers 7

That’s just the normal Internet background noise of people scanning for vulnerable servers.

You can add an iptables rule to rate limit incoming connections (e.g. four in four minutes) for a simple fix (but that will also lock you out if you open too many connections or someone forges SYN packets originating from your address):

The proper solution is to use a tool like fail2ban that parses the log file for failed logins and creates firewall rules on demand — a bit more work to set up, but it requires an established connection and a failed authentication to trigger, so it will not react to forged connection attempts or successful logins like the simple approach does.

As @Simon Richter mentionned, that’s just internet background noise and you shouldn’t worry. A few things you have to make sure are that:

  • You don’t allow password-based authentication but only public key auth
  • You can disable unsafe and poorly designed ciphers, remove small Diffie-Hellman moduli and other cryptographic improvements
  • You can install fail2ban

Changing the port will make the problem go away, but it’s security through obscurity and it can create the illusion of safety while providing none.

Here are a few other recommendations surrounding SSH, as well as counter arguments to mainstream “best practices” arguments.

How to use port knocking on linux (and why you shouldn’t)

Are you in India? All those IP addresses listed are in the block:

which according to the WHOIS database is allocated to

One short-term solution is to block the whole block 223.196.160.0/19 at the firewall, but that is micromanaging IP addresses and becomes an uphill battle.

Instead you could deny ALL ssh except for the source IPs that you know are trusted. Simply take care to not lock yourself out of your own host. If you don’t have a static IP, you can permit a block, or possibly look at running a VPN server on the host.

Or if you don’t need to permit SSH connections from the internet, just deny them and only reenable when its required.

How to use port knocking on linux (and why you shouldn’t)

Here is a simple script I wrote to block all unauthorized attempts at logging into my dev server.

If you set the script to run via cron every minute, it will dramatically reduce the noise in your logs and block offending IPs giving them just 1 minute to attempt their brute force before being blocked.

It would be a good idea to insert your IP and any other IPs you access your server with to your firewall iptables -I INPUT -s xxx.xx.xxx.xx -j ACCEPT

A log of all IPs banned will be generated.

How to use port knocking on linux (and why you shouldn’t)

  1. Use only key-based auth. Many bots only attack password-based systems. Using password-based auth is bad idea anyway.
  2. Use https://www.sshguard.net/ : it blocks IPs after a couple of failed logins.
  3. Use random port (not 22), it will stop some bots.
  4. Make sure your system doesn’t permit root login
  5. If you only login from your home, consider only open SSH for your IP/ISP or country.

1. Change your sshd listening port

As simple as it sounds, changing your port from the default 22 to a custom value (e.g. 2200 ) on a public IP could reduce the number of port scans from thousands a day to a few dozen. For a tutorial see here.

That being said, while this does reduce the annoyance of being port-scanned, it DOES NOT provide real security. “Security by obscurity” is a myth and nothing more.

2. Use public key login and disable password login

Bots might guess a password right, but they’re never going to guess a private key right. As long as you use modern algorithms and don’t leak your key accidentally. For a tutorial see here.

Note that this does mean you will no longer be able to login from any random machine, unless you carry the key with you (which you need to secure via some other way).

3. Use fail2ban

If they fail 5 times, ban them from trying again for a day or something. That’ll show them. Very effective against brute force attempts. For a tutorial see here.

The downside is that you might lock yourself out if you’ve got wobbly fingers one day (drunk or something, I don’t know).

4. Pre-ban a list of IPs known for abusive use

Sources like AbuseIPDB maintain big lists of known malicious IPs accessible via API. You will need an API key to use it, but you can register a free account easily enough. Pull the list and use something like iptables to ban those known IPs in bulk. Set up a cron job to automate it periodically for best effect. Here’s a very simple script I wrote (and am personally using) to do just that. Feel free to use it as reference, but DON’T USE IT IN PRODUCTION.

In my personal experience, this method is equally effective (if not more so) as method #3.

Personally, I use all 4 methods listed above, and my VPS might get one or two malicious login attempts in my security log at most, in a bad month. Here’s the interception history of iptables via method #4:

* Does not bind to sockets

* Is not written in C

* Prevents replay attacks

* The only code that runs as root is just tailing kern.log and is like 15 lines

It probably needs to roll from SHA1 to SHA256 and Python2 to Python3, but otherwise seems sound.

Edit: It appears there may be an active fork here: https://github.com/indyprime/knockknock

Still digging through to see if the encrypt-then-authenticate change made it into this version.

Edit 2: It looks like it still uses authenticate-then-encrypt. I sent an email to the maintainer of that fork, we’ll see what happens. ^__^

Sounds pretty cool, but do SSH clients (e.g. PuTTY need special support for it)

I lost my fob. So I took my intercom apart and wired a band pass filter circuit between the buzzer input and actuator output. If you pressed my buzzer with the right steady pattern, it would automatically let you in.

It worked great and I didn’t buy a replacement fob.

A few months later I started getting woken up by someone buzzing my buzzer. They would always scurry in before I could open my door to see who it was.

Turns out my upstairs neighbor saw my shenanigans a few times and started freeloading off my invention. Honestly amazed he/she reverse engineered what was going on!

Needless to say, I bought a new fob.

First friend-a local-is the type who doesn’t answer his phone from numbers he doesn’t know/isn’t saved as a contact-which I knew, so I dialed him, then dialed his wife (who also doesn’t answer unknown numbers), then dialed him again. He picked up the second time and after some explaining he chuckled and goes “yeah I figured it must be important when the same number called $wife immediately after calling me”.

He was there to pick us (including drunk mutual friend) up within the hour. And yes, he’s a network engineer heh.

Not sure how payment worked and why you could listen for free—I’m only familiar with the method from written accounts.

The other person would get an option to receive a call from for $5, but usually is the name or code of a location to be picked up.

I must have done this 100 times as a kid. Once an angry man clued onto it, switched my line across and told me off. This is back in the days where mobile calls were expensive and very few kids had phones.

But you just gave me an idea for something I’ll probably never implement: an audio key. The intercom auto-responds and if the audio matches the key (hello 90s modem sounds), then it lets you in. You could add more automation on top and provide temporary keys for guests, etc. Just play the audio you received on whatsapp, it will open the door. Please someone implement this and get rich doing it so that I can just buy it. It needs to take into account when you’re at home and you still want to answer the mailman.

I understand the key fob/card concept for access purposes, but have never heard of an “intercom” in the context of home/apartment/etc security.

20 years ago — at most, on a reasonably designed network, it was saving you from your own misconfigurations, but at least in 2005 it was reasonable to imagine a highly diverse network of machines that people logged into using multiple protocols, where those misconfigurations were likely.

In 2020, it’s gone past “silly” and is now a design smell, in the same way that actually relying on fail2ban would be. Whatever port knocking is doing to help you is a a description of something you’re doing wrong with your architecture.

We’re not even comfortable with long-lived keys anymore; modern networks are built with short-lived certificates issued off 2FA from an IdP. We have good VPNs right now for the other weird cases. Our networks default to all-ports all-hosts closed. Arguably, port knocking is literally setting your security back, by making it harder for automated tooling to scream bloody murder if you’ve managed to expose a dev instance unexpectedly to the Internet.

Don’t bother. If you’ve got a single system you’re managing outside of a cloud provider with its own decent network firewall, just set up WireGuard and filter everything but that. If it helps, think of WireGuard as the evolution of SPA port knocking.

Modern networks are sadly far too rare; 95%+ of the industry is built on legacy networks.

My take on fail2ban and port knocking are:

* they reduce the amounts of logs produced

* they defend against fully automated at-scale scans / password stuffing attacks that a well-maintained application wouldn’t need defending against, but we all know that in any sufficiently big organization, not all applications and accounts will be well maintained.

When the next 0day hits… will it be enough to protect them, yes. After all, they’re not a target and the automated attacks won’t affect them.

In my case, all internal services in a kubernetes cluster have no path that allow it to be accessed from the outside. Occasionally, developers might want to do so, say to access a database or prometheus server.

The way to properly do this, imo, is to use a hardened service that functions as a networking proxy. Use proper encryption keys for access, and it should be quite hard to bust open.

Where does port knocking come in? That service should need to be exposed at all times. So, use port knocking to configure the infrastructure to temporarily allow access from your IP, to that proxy servers IP, on that particular port.

I’m more inclined to not take it serious, if such a simple mechanism isn’t in place to protect infrastructure.

Is there any advantage in changing the SSH port, I’ve seen people do that, but I can’t seem to find the reason why.

If you have a strong password and/or a certificate, is it useful for anything?

I should also mention that I am using iptables rules to limit brute forcing attacks, only 5 login attempts are allowed per minute per IP address.

How to use port knocking on linux (and why you shouldn’t)

8 Answers 8

The Internet is a wild and scary place, full of malcontents whose motives range from curiosity all the way to criminal enterprise. These unsavories are constantly scanning for computers running services they hope to exploit; usually the more common services such as SSH, HTTP, FTP, etc. The scans typically fall into one of two categories:

  1. Recon scans to see what IP address have those services open.
  2. Exploit scans against IP addresses who have been found to be running a specific service.

Considering how large the Internet is it is typically infeasible to look on every port of every IP address to find what’s listening everywhere. This is the crux of the advice to change your default port. If these disaffected individuals want to find SSH servers they will start probing each IP address on port 22 (they may also add some common alternates such as 222 or 2222). Then, once they have their list of IP addresses with port 22 open, they will start their password brute force to guess usernames/passwords or launch their exploit kit of choice and start testing known (at least to them) vulnerabilities on the target system.

This means that if you change your SSH port to 34887 then that sweep will pass you on by, likely resulting in you not being targeted by the followup break-in.

Seems rosy right? There are some disadvantages though.

  1. Client Support: Everybody who connects to your server will need to know and use the changed port. If you are in a heavily managed environment, this configuration can be pushed down to the clients, or if you have few enough users it should be easy to communicate.
  2. Documentation Exceptions: Most network devices, such as firewalls and IDSes, are pre-setup for common services to be run on common ports. Any firewall rules related to this service on this device will need to be inspected and possibly modified. Similarly, IDS signatures will be tweaked so as to only perform SSH inspection on port 22. You will need to modify every signature, every time they are updated, with your new port. (As a data point there are currently 136 VRT and ET snort signatures involving SSH).
  3. System Protections: Modern Linuxes often ship with an kernel layer MAC and/or RBAC systems (e.g. SELinux on RedHat based or AppAmor on Debian based) and that are designed to only allow applications to do exactly what they’re intended to do. That could range from accessing the /etc/hosts file, to writing to a specific file, or sending a packet out on the network. Depending on how this system is configured it may, by default, forbid sshd from binding to a non-standard port. You would need to maintain a local policy that would allow it.
  4. Other Party Monitoring: If you have an external Information Security division, or outsource monitoring, then they will need to be made aware of the change. When performing a security assessment, or analyzing logs looking for security threats, if I see an SSH server running on a non-standard port (or an SSH server on a non-UNIX/Linux for that matter) I treat it as a potential backdoor and invoke the compromised system part of incident handling procedure. Sometimes it is resolved in 5 minutes after making a call to the administrator and being told it’s legitimate, at which point I update documentation, other times it really is badness that gets taken care of. In any event, this can result in down-time for you or, at the least, a nerve racking call when you answer your phone and hear, “Hi, this is Bob from the Information Security Office. I have a few questions for you.”

Before changing your port you need to take all of this into account so you know you’re making the best decision. Some of those disadvantages may not apply, but some certainly will. Also consider what you’re trying to protect yourself against. Often times it is simply easier to just configure your firewall to only allow access to 22 from specific hosts, as opposed to the whole Internet.

Introduction

Port knocking is a method of externally opening ports. Once a server receives a secret sequence of ‘knocks’ on a closed port or ports, the server will execute a pre-configured set of actions. Actions may vary from opening ports for quick access to a full reboot of the system.

Port knocking should not be taken as an implementation of authentication security, as it is an example of the security through obscurity concept, which is fundamentally flawed.

How it works

On the server side, port knocking is usually implemented by configuring a daemon to watch the firewall log file for connection attempts to certain ports.

The ‘knock’ itself is a secret sequence of packets sent to numbered ports on the destination machine. The complexity of the knock may vary from a single TCP SYN packet to a complex time-dependent, source-IP-based and other-factor-based encrypted hash.

Client-wise, simple TCP knocks could be performed via telnet or netcat, for more advanced knocks see knock, hping, sendip or packit.

Server and client

knockd server

knockd is a port-knock server, which listens at the link-layer, the lowest layer in the Internet protocol suite. That makes possible to catch packets destined for closed ports. When the server detects a specific sequence of port-hits, it runs a command defined in its configuration file.

The setup and configuration of knockd are simple. Lets break down the configuration file, located by default in /etc/knockd.conf :

Each event begins with a title marker, in the form [name], where name is the name of the event that will appear in the log. A special marker, [options], is used to define global options.

  • Sequence is the order of ports in the knock. Optionally, you can specify protocol for port (TCP by default).
  • Seq_timeout is the timeframe for the execution of the full sequence to trigger the command. If the time elapses before the knock is complete, it is discarded.
  • Tcpflags are the types of packets ports expect to receive. When using TCP flags, knockd will ignore packets that don’t match the flags. (TCP SYN is the default flag, as it is the first packet in a TCP connection request)
  • Command is the command to be executed when a client makes the correct port-knock. All instances of %IP% will be replaced with the knocker’s IP address.

After configuring knockd, specify the interface and run it as a daemon:

To make knockd start on boot, set START_KNOCKD to 1 in the the /etc/default/knockd file and provide additional options, if required.

knock client

Install the knockd package on the client-side machine, as it includes a tool called knock. This tool helps to perform complex secret sequences. To send a knock sequence to the server use knock .

  • knock server 7000 8000 9000 – sequence would open the SSH port on the server-side example.
  • knock server 9000 8000 7000 – would close the SSH port from the same example.

Advantages

Defeating port knocking protection requires large-scale brute force attacks in order to discover even simple sequences. An anonymous brute force attack against a three-knock TCP sequence would require an attacker to test every three port combination in the 1 – 65535 range and then scan each port between attacks to uncover any changes in port access on the target system.

Even if the attacker were to successfully gain port access, other port security mechanisms are still in place, along with the assigned service authentication mechanisms on the opened ports.

Disadvantages

The failure of the port knocking daemon will deny port access to all users and from a usability and security perspective, this is an undesirable single point of failure.

Port knocking can be problematic on networks exhibiting high latency. Port knocking depends on packets arriving in the correct sequence to access its designed functionality. TCP/IP, on the other hand, is designed to function by assembling out of order packets into a coherent message. In these situations, the only solution is for the client to continue resending the correct sequence of packets on a periodic basis until the sequence is acknowledged by the server.

Any attacker who can sniff or otherwise obtain the knock sequence can use it to bypass the port knocking protection on all hosts which are using the same sequence.

Unintended publication of the knock sequence implies compromise of all devices supporting the sequence.

Conclusion

Port knocking is a thin layer of the server security against scanning and enumeration, but it cannot be used as the sole authentication mechanism for a server. Port knocking will come in handy to hide your services against strangers, and possibly protect your server against SSH brute-force.

Anthony Heddings is the resident cloud engineer for LifeSavvy Media, a technical writer, programmer, and an expert at Amazon’s AWS platform. He’s written hundreds of articles for How-To Geek and CloudSavvy IT that have been read millions of times. Read more.

How to use port knocking on linux (and why you shouldn’t)

Mosh, or “Mobile Shell,” is designed to be a replacement for SSH, specifically for mobile devices or laptops on slow connections. Mosh works over UDP, and will keep your connection alive, even if you change WiFi networks or experience fluctuating cell signal.

What Is Mosh?

Mosh’s UDP-based transfer system makes it more stable than traditional SSH, as it handles packet loss much more effectively. If your connection drops out for a bit, Mosh will reconnect you as soon as it comes back, leaving your commands in place as you were typing.

It also significantly reduces latency; if you’ve ever tried to SSH to a slow server, you’ll notice even your keystrokes become slow and unresponsive. This is because the SSH client waits for a TCP response from the server before showing your typing, in case the server intercepts it for some reason. Mosh is more intelligent, and will display your typing in real-time. It even gives underlined typing predictions, which is also handy.

If long-term persistence is all you’re after, you can instead use tmux on your server over SSH. Tmux splits your terminal into multiple panes, each with multiple tabs, that all persist on the server across SSH sessions. The benefit here is that if your SSH session gets disconnected, it doesn’t affect what’s going on on the server, similarly to Mosh.

But Mosh and tmux also play well together, as Mosh will automatically reconnect you to your tmux session if your connection drops out, without having to run ssh and tmux -a t [name] all over again.

How Secure Is Mosh?

Mosh makes the initial connection over SSH, so the authentication is about as secure as SSH is. It uses AES-128 encryption for traffic sent over UDP, so your traffic can’t be sniffed.

The main issue with Mosh is that it requires a lot of ports to be open. Mosh can use any port between 60000-61000, depending on the IP address of the connection. And while you will usually use the same port for the duration of the connection, it’s not guaranteed. This isn’t a major issue, but opening 1000 ports isn’t really good security practice.

If you are running a firewall like iptables, you’ll have to open these ports manually:

And if you’re running a server on a service like AWS, you’ll need to open the ports through their firewall as well. If you wanted it to be more secure, you could use port knocking to close these addresses and only open them when Mosh knocks, but this also isn’t ideal if the port changes during your session.

Bottom line, if you’re using Mosh and you’re worried about security, you should probably make it listen on your private network and use a VPN.

Install Mosh Server and Get a Mosh Client

For Mosh to work, the server needs to have Mosh binaries installed. This doesn’t run a daemon like sshd ; rather, it’s the first command your Mosh client runs when connecting over SSH. When the connection closes, the server terminates the running Mosh server.

The installation is quite simple, as it’s available on most package managers. For Debian-based systems like Ubuntu, that would be:

This installs the client and the server, so you’ll install the same package on both. Server-oriented installations will simply require you to substitute apt-get for your distro’s package manager.

For Windows, you’ll have to install the client for Chrome. There’s no binary yet for Windows.

For macOS, you can install the package directly, or install it using Homebrew:

For iOS, you can use an app like Termius or Blink Shell.

And for Android, you can use an app like Termux or JuiceSSH.

In any case, you’ll connect as you would with SSH:

This connects with a username and password. If this isn’t ideal for you, you can also manually specify new SSH options with the –ssh parameter:

This command will make use of your private key rather than a password. Note that the server will need to be configured to accept this private key, especially if it’s a new one coming from a phone or other device.

Still fresh, damnit!
  • Mar 12, 2021
  • #41
  • sebt3

    homebrew player (P. & C.)
    • Mar 12, 2021
  • #42
  • That 0 on the “Swap:” line mean it’s unused.
    Note : the “buff/cache” column show you how much disk cache your system does to speed thing up. Linux will use all the “free” RAM for cache as much as useful, yet most of it can be freed instantly hence the “available” column. Beware, your system doesn’t start to reduce speed when it’s starting to use swap, but when it start freeing buffer/cache for apps memory. Hence my position against swap and opting to buy more RAM

    PS: yeah, i’m using swap. but I have alerting if it become used. It’s just a fail-safe against oomkiller.
    PPS: that LANG=C in the command line only force output in english instead of my frenchy

    Pickle

    Mega GP Mania
    • Mar 12, 2021
  • #43
  • Linux-SWAT

    Hardcore Member
    • Mar 12, 2021
  • #44
  • netcat

    Very Active Member
    • Mar 12, 2021
  • #45
  • i lied i use swap too.
    on my little vm creating a swap file on / was the only way to have enough memory to generate daily reports of all the hack attempts
    i’m getting like 44k failed ssh logins daily from a botnet. yay.

    here’s another way to observe swapping:
    bpftrace -e ‘software:faults:1 < @[comm] = count(); >‘

    but it might quite alarming for you, as it is for me.

    THERE IS JAVA RUNNING ON MY MACHINE.

    JDTAY

    Half Pepperoni, All Cheese
    • Mar 12, 2021
  • #46
  • I’ve been thinking that it might be time to take down the internet, because it’s not secure enough. Old habits die hard though. Especially in America, where our main export is ones and zeroes. Wouldn’t want the world to run out of those.

    Still fresh, damnit!
    • Mar 12, 2021
  • #47
  • Nilsnsn

    Member
    • Mar 13, 2021
  • #48
  • i lied i use swap too.
    on my little vm creating a swap file on / was the only way to have enough memory to generate daily reports of all the hack attempts
    i’m getting like 44k failed ssh logins daily from a botnet. yay.

    here’s another way to observe swapping:
    bpftrace -e ‘software:faults:1 < @[comm] = count(); >‘

    but it might quite alarming for you, as it is for me.

    THERE IS JAVA RUNNING ON MY MACHINE.

    Phlyra

    Electric
    • Mar 13, 2021
  • #49
  • Still fresh, damnit!
    • Mar 13, 2021
  • #50
  • Nilsnsn

    Member
    • Mar 13, 2021
  • #51
  • netcat

    Very Active Member
    • Mar 13, 2021
  • #52
  • Pickle

    Mega GP Mania
    • Mar 13, 2021
  • #53
    • Mar 13, 2021
  • #54
  • There’s not a single way an SSD can be faster than RAM.
    The CPU have a direct connection to the RAM (well with multi socket systems it’s a little more complicated, but lets forget this for a bit). An M.2 drive is piloted by the CPU throw interrupts, these interrupts go throw the south-bridge to enter the PCI-e line then get to the M.2 controller that indirect the call to the actual drive. The buffer follow the road back to the main data line where it enter . the fucking RAM.
    How the fuck all these indirections that finally endups in the RAM can be faster than the RAM itself ? Could you explain me this ?

    Do you know how the linux kernel work ? Any write to a disk is cached into RAM so the write is faster for the program, the kernel making sure the data is written to disk in an async fashion. (yeah async write is the default. Getting sync write is actually cumbersome and a bit convulted).
    Removing RAM from a computer would requiere a completly new hardware design and a completly new OS design. While the linux kernel is the most versatile kernel ever written, it would need a complet redesign for your idea to works. A redisign that would make the 1.x->2.0 and the 2.2->2.4 redisigns as mer simple patches.

    BTW, I was talking about software architecture used in datacenter. kubernetes is pretty much this. Google, amazon and a few others are running using kubernetes, thuss without any swap. I guess you think you understand better hardware than the google engineers that designed kubernetes and the hardware it’s running on top of.

    Port knocking is a mechanism to provide additional security to firewalling. Port knocking is normally used in firewalls. A target port needed for a particular service (e.g. SecureShell, SSH) is normally closed and the service is unreachable. Only by ‘knocking’ on a number of ports in a particular order opens the target port. Knocking means: sending a TCP or UDP packet to the port. Though the knock ports are closed and won’t respond, the firewall notices the knocks. To the outside world the firewall appears totally closed. Portscans fail. Only when the proper sequence of ports is knocked the target port opens and the service is reachable for a few seconds. During this time-span the service can be reached.

    There are a large number of port knock implementation. See for an overview: portknocking.org. Open Sesamy differs from other mechanism because only one port for knocking is needed. It may even be the target port. It is implemented using Linux iptables. This is another difference: most port knocking algorithms are implemented as scripts scrutenising the log files. Using iptables the packet filtering is exploited as present in the Linux kernel or modules.

    At home I have an internet server with a great number of goodies. When I am at work I occasionally need a few of the goodies. However, at work I am stuck with a company firewall that only allow TCP connections to
    port 80 (HTTP) and 443 (HTTPS). On port 80 I run a webserver. On port 443 I run a SecureShell (SSH) server, which I like to protect by means of port knocking. Because no other connection are allowed to other ports, I cannot use regular port knocking. So I created Open Sesamy. I can use port 443 for knocking and for SSH!

    In Open Sesamy 4 sequences of knocks are sent to the knock port at regular time intervals (e.g. 4 seconds). When correct sequences are received, the secured port opens for the period equal to one time interval. During this period, connection can be made to the opened secure port. Only the machine that performed the knocks can connect. A knock may be a TCP SYN packet or an UDP packet.

    Next piece of code implements the necessary iptables code. Open Sesamy has been implemented as function portKnockListener(). The download section contains an example implementing a simple firewall only allowing access to a SSH server after port knocking (1-2-3-4 knocks).

    The function is called in a firewall script (e.g. rc.firewall) using an input chain as input:

    The function can be added to more than one input chain.

    The function uses the ipchain matching (-m) criterion ‘recent’. This criterion checks whether current host has been noticed before. The matching is narrowed down by using the –hitcount and –seconds extensions, to implement the sequences and time window behaviour. Refer to the iptables man pages under linux for a good explanation of these matching criteria. Note: ipchains behaves somewhat weird. When a knock port is forwarded using prerouting the original port should be defined as the KNOCKPORT and not the forwarded one (as I would have expected).

    For example, when I preroute port 443 to port 22 like

    it is necessary to set KNOCKPORT to 443 and SECUREPORT to 22

    Open Sesamy: Windows, TCP Syn based

    Open Sesamy tool offers a Windows based tool that sends TCP SYN packets. For this, it needs WinPcap needs to be installed. WinPcap is used to send raw TCP packets without using the Windows TCP/IP stack (when using the stack, the stack would wait for the TCP connection to set up; this is not what we want; we just want to spit out a few TCP SYN packets). Refer to the download section for the tool.

    How to use port knocking on linux (and why you shouldn’t)

    Following fields can be filled:

    Ip Address The address or name of the host to be knocked Port The knock port (KNOCKPORT in the script) Sequence Sequence of knocks as a string of 4 digits. Each digit (value 1-9) represents a number of knocks. Window Timing window in milliseconds. 4000 represents a 4 second window Devices The network interfaces available on this PC are listed here. You should select the network interface that should be used to send the knocks to. Mac The MAC address of the interface selected is filled in here. Under WinNT this does not work. Unfortunatelly you have to fill in the MAC by hand than. Knock Start knocking Info Print available network interface info About Version information Exit Does what the button says…

    When a file knocksettings.txt is present, these settings are read from this file.
    Note: storing these settings in a file means compromising security, since these settings should be kept secret!

    Following settings should be defined in the file, each on a new line:

    • server
    • port
    • sequence
    • window
    • interface index (0, 1, etc)
    • mac address

    PortKnocker: Windows/Linux, UDP based, commandline tool

    A commandline tool called PortKnocker is available as well. This tool sends UDP packets. Since UDP is a connection-less protocol, it is possible to use standard sockets to spit out UDP packets. So we use the Windows/Linux kernel. No need for WinPcap. The commandline version may come in handy, because it may be used in a start-up script calling PortKnocker, sleeping a second and than call the e.g. the SSH client.

    server The address or name of the host to be knocked port The knock port (KNOCKPORT in the script) sequence Sequence of knocks as a string of 4 digits. Each digit (value 1-9) represents a
    number of knocks. window Timing window in milliseconds. 4000 represents a 4 second window

    A file called knocksettings.txt is expected to be present defining the settings. Note: storing these settings in a file means compromising security, since these settings should be kept secret! . The file should contain the settings described above, each setting on a new line.

    Note: the same file may be used that is used for the OpenSesamy tool.

    filename Name of the settings file

    Basically, this is the same as option 2. However, now the filename can be specified.

    • rc.firewall.test
    • PortKnocker for Linux/Windows
    • Open Sesamy tool for Windows

    Note: Open Sesamy is quite outdated and probably needs upgrading….