Port Knocking

An introduction to how trusted users can manipulate firewall rules to transmit information across closed ports.
Benefits of Port Knocking

One of the key features of port knocking is it provides a stealthy method of authentication and information transfer to a networked machine that has no open ports. It is not possible to determine successfully whether the machine is listening for knock sequences by using port probes. Thus, although a brute-force attack could be mounted to try to guess the ports and the form of the sequence, such breach attempts could be detected easily.

Second, because information is flowing in the form of connection attempts rather than in typical packet data payload, without knowing that this system is in place it would be unlikely that the use of this authentication method would be detected by monitoring traffic. To minimize the risk of a functional sequence being constructed by the intercepting party, the information content containing the remote IP of the sequence can be encrypted.

Third, because the authentication is built into the port knock sequence, existing applications need not be changed. Implementing one-time passwords is done easily by adjusting the way particular sequences are interpreted. A sequence could correspond to a request that a port be opened for a specific length of time and then closed and never opened again to the same IP. Furthermore, a one-time pad could be used to encrypt the sequence, making it indecipherable by those without the pad.

Disadvantages of Port Knocking

To use port knocking, a client script that performs the knock is required. The client and any associated data should be considered a secret and kept on removable media, such as a USB key. The use of the client imposes an overhead for each connection. Certain locations, such as libraries or Internet cafés, may not allow execution of arbitrary programs.

In order to use port knocking, a number of ports need to be allocated for exclusive use by this system. As the number of such ports increases, the knock sequences becomes shorter for a given amount of information payload, because the number of coding symbols is increased. Practically, 256 free privileged ports (in the 1-1024 range), not necessarily contiguous, usually can be allocated and used to listen for port knocks.

Finally, any system that manipulates firewall rules in an automated fashion requires careful implementation. For the scenario in which no ports are initially open, if the listening dæmon fails or is not able to interpret the knocks correctly, it becomes impossible to connect remotely to the host.

Applications

In this section, three examples are outlined that illustrate how the port knocking system can be used.

1. Single Port, Fixed Mapping

Connection to only one port (ssh/22) is required. The ssh dæmon is running; all privileged ports are closed, including ssh/22; and packets addressed to ports 30,31,32 are being logged. The following port sequences are recognized:

31,32,30        open ssh/22 to connecting IP
32,30,31        close ssh/22 to connecting IP
31,30,32        close ssh/22 to connecting IP and disregard further knocks from this IP

The justifiably paranoid administrator can open the ssh/22 port on his system by initiating TCP connections to ports 31,32,30. At the end of the ssh session, the port would be closed by using the second sequence shown above. If the host from which the administrator is connecting is not trusted (if, say, keystrokes may be snooped), the use of the third sequence would deny all further traffic from the IP, preventing anyone from duplicating the session. This assumes the port sequence and system login credentials are not captured by a third party and used before the legitimate session ends.

In this example, only three sequences are understood by the system, as the requirements call for only a handful of well-defined firewall manipulations. The sequences were chosen not to be monotonically increasing (30, 31, 32), so they would not be triggered by remote port scans. If multiple ports are to be protected by this system, a mapping needs to be derived between the port sequence and a flexible firewall rule. This is covered in the next example.

2. Multiple Port, Dynamic Mapping

In this example, a network may be running any number of applications. Ports 100-109 are used to listen to knocks. The port sequence is expected to be of the form:

102,100,110  10a,10b,10c,10d  10(a+b+c+d mod 10)        110,100,102
header          payload             checksum                 footer

The first and last three ports let the port knocking dæmon know that a sequence is starting and ending. The next four ports encode the port (abcd) to be opened. For example, if a connection to port 143 is required, the sequence would be 100,101,104,103. The final element in the sequence is a checksum that validates the sequence payload. In this example, the checksum is 8 (1+4+3 mod 10). The sequence element therefore is 108, and the full sequence would be

102,100,103  100,101,104,103 108 103,100,102

When this sequence is detected, port 143 would be made available to the incoming IP address. If the port is open already, the knock would rendered it closed. The knock can be extended to include additional information, such as an anticipated session length, that can be used to close the port after a set amount of time.

3. Mapping with Encryption

The information contained in the knock sequence can be encrypted to provide an additional measure of security. In this example, 256 ports are allocated and logged. A knock map of the form

remote IP  port   time   checksum

is used where the remote IP, port, time and checksum (sum of other fields mod 255) are encrypted. The encrypted string can be mapped onto eight unsigned chars using Perl's pack("C*",STRING) command, see Listing 1.

Listing 1. Mapping the Encrypted String

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

im sure it is for protocols

ipod transfer's picture

im sure it is for protocols like ssh, not http.

Enhancement to Knocking

Anonymous's picture

A better approach here would be to include payload data in the packets, where the server has the "key" to what that data should be. Could be anything.

This would hopefully mitigate the chance that portscanners could trigger something unexpected.

Single Packet Authorization

mrash's picture

Indeed the using the application layer is a much better approach. You may be interested in "fwknop" (http://www.cipherdyne.org/fwknop). Here is a paper on why SPA is better than port knocking:

http://www.cipherdyne.org/fwknop/docs/SPA.html

Theres a good iptables port k

Anonymous's picture

Theres a good iptables port knocking script up at http://www.neep.co.uk/index.php?tab=Projects&menu=Port%20Knocking

Re: Port Knocking

Anonymous's picture

this is something that has been in use and known for quite some time, a simple google search for a program called 'cd00r.c' will reveal a backdoor that was developed years ago that uses a packet sniffer to do this. I have also seen a real implementation of this in a blackhat's backdoor, execpt rather than using something like that, it uses a specific sequence of packet header options and part of an encrypted payload to create a reverse/connect back shell.

as per usual, the whitehats are slow and are stealing the ideas of blackhats everywhere.

Re: Port Knocking

Anonymous's picture

agreed

knock

youtube's picture

a lamer do ddos my dc :(

Re: Port Knocking

Anonymous's picture

Why not use UDP instead of TCP for "Port Knocking"? Using UDP allows you to pass real data without stretching the TCP/IP protocol rules and/or crafting strange IP packets.

To do this, you set up a non-responding UDP listener on one or more UDP ports. If no response is ever given, such ports are indistinguishable from ports filtered by a firewall (e.g. via iptables DROP).

When the UDP listener receives a packet it likes, it instructs the firewall to open up the desired TCP (or UDP) port for the service in question. If you want to be extra fancy, the UDP listener can be a state machine which listens for a sequence of packets on one or more ports, but this may be overkill.

The hidden service can be always "running" -- directly or via xinetd -- listening on the usually filtered port. When the firewall allows traffic on that port, the service can then become active. To be extra safe, a TCP service can immediately instruct the firewall to filter the port it is now using against further SYNs (until another UDP knock).

There are two advantages I see to using UDP. First, the UDP listener can be more easily responsive, since it is a regular network program and doesn't have to dig through firewall log files (which might even be "rotated" during the knock sequence).

Second, the knocks can be much less conspicuous to anyone monitoring traffic. For example, you could use the traditional traceroute ports, or other UDP service ports like DNS or NETBIOS with valid looking requests. If you do this, you might want to use a state machine to require a sequence such as: (1) "Traceroute on port 34567 TTL 3", followed by (2) "DNS lookup of foo.mydomain.com", followed by (3) "NETBIOS something-or-other COLORPRINTER" (my NetBios is sketchy). The point is that these look pretty innocuous to the snooper.

On the other hand, you might want to make things much more straightforward and just have "DNS lookup of pcXYZ.mydomain.com" mean "allow incoming SYNs on port 57XYZ for the next minute" so that you can set up a SSL/SSH/TLS connection to port 57XYZ. Of course, this assumes you aren't running DNS (and hence aren't responding), or you *are* running DNS but have hooked some kind of sniffer on port 53.

Finally, UDP "knock" packets (and even some TCP ones) work just as well with spoofed source addresses. But this should *not* be done without the approval of your network administrator, and is quite inappropriate -- or even illegal -- on the Internet (and may be grounds for your ISP to terminate your account).

Re: Port Knocking? ... Use SSL and a script.

Duchamp's picture

There is a simpler way. Make a script on your SSL encrypted server that returns a 404 error unless a correct password is provided in the URL. https://yourserver.com/secretknockscript/SeCrEtPass/
The script then looks up the pass in a config file to know what ports to open and send the command to open that port for 10 seconds.

The request is encrypted so nobody will get your pass by sniffing. It would be in the web server log so perhaps make a local form that POSTs.

Re: Port Knocking? ... Use SSL and a script.

Anonymous's picture

Umm.... wouldn't you have to keep port 80 open for you to use https? The whole reason for doing this is to keep your ports closed until needed.

I think you mean, port 443 (u

Anonymous's picture

I think you mean, port 443 (unless otherwise configured). Also, it is quite often that the machine that you are trying to gain access to is indeed providing some services to the Internet, so the point is a valid one, whether it be an SSL-protected http request or pop3s request or whatever.

Re: Port Knocking

Anonymous's picture

Ok, here are some ideas I thought up after reading this initially great idea:

1. Improve it to make the port number sequence tied into something like cryptographic key services like SecurID. This prevents later abuse of the port by anyone who would be sniffing.

2. iptables doesn't need to allow all new connections for the ip after it is first established, since it is statefull, so the first connection attempt could succeed wheras any subsequent attempts would fail before another knock is given.

3. Using other garbage data inside a TCP connection attempt, like TOS, or some such garbage, even varying the TTL of each packet could be used to convey some simple type of number combination.

Re: Port Knocking

Anonymous's picture

There is a slightly different implementation of Martin Krzywinski's port-knocking idea available at:

http://doorman.sourceforge.net

Re: Port Knocking - another disadvantage

Anonymous's picture

Internet Cafes, libraries, business partners will all present the potential to not allow outbound traffic to arbritrary ports. Indeed, a good firewall implementation would not allow such traffic. As an example, what business does a client have connecting to ports 822, 915, 341?

Re: Port Knocking - another disadvantage

Anonymous's picture

It would be quite possibl to use a call to a single blocked port with the data embedded inside.. common guys, this is all about being creative!

Re: Port Knocking - another disadvantage

Anonymous's picture

And at all it's nothing really new, but just another level of security - like a password, just not on this high (application) level. It's the same: You have some secret which you shouldn't share and which gives you access to some resources you're denied access otherwise.

I.e. might be nice as an additional level, but nothing exceptionally new.

Re: Port Knocking - another disadvantage

Anonymous's picture

Specifically because a legitimate client has no business connecting to unusual ports like 822, 915, 341, the firewall can be configured to use these ports for user authentication. The method provides a firewall-based method of authentication, as another layer to protect the system.

It is not necessary to allow inbound traffic to arbitrary ports - merely that connection attempts to these ports be logged. In fact, the method relies on these logged ports to be set to deny all connections.

Re: Port Knocking - another disadvantage

Anonymous's picture

I think the concern that's actually presented here is one of whether it'll be possible to knock at all if your particular set of arbitrary ports (or any subset thereof) is blocked to outbound use. I've worked in call centers and the like that use a default-deny policy on outbound traffic with the exception of a very very few ports (the most draconian allowed only 53, 80 and maybe 443 on tcp, and I think they killed 53 sometime after I left). Of course, in that case the exercise might be moot anyway...

Re: Port Knocking

Anonymous's picture

I guess you could disguis a portknock as a portscan, with let says a nmap signature?

Re: Port Knocking

billy ranson's picture

Wouldn't be that the same ???

Re: Port Knocking

Anonymous's picture

Second, because information is flowing in the form of connection attempts rather than in typical packet data payload, without knowing that this system is in place it would be unlikely that the use of this authentication method would be detected by monitoring traffic. To minimize the risk of a functional sequence being constructed by the intercepting party, the information content containing the remote IP of the sequence can be encrypted.

IMHO, though, it seems very likely - especially given the nature of this article in explaining what to monitor for: a series of seemingly-random port connect attempts followed by a steady stream of accepted packets. The steady stream would have valid IP addresses in them, unlike the possibly encrypted portknock packets. A comparison of groups of such port connect sequences followed by normal traffic reveals the presence of the portknocking. Unless I've misunderstood something, the port numbers have to remain in clear, so they *can* be monitored even if the IPs of the portknocking packets can't be.

I think this is a valid technique, but it's not quite as undetectable as presented.

Re: Port Knocking

Anonymous's picture

One can change the port knocking sequence randomly based on a shared key scheme. So it might depend on time and a key and change every second. So listening to ports won't mean anything since the same sequence would not work again. THe randomizer on both the client and the server would take the shared key and based on the key and let say time would create sequence of random ports.

Orhan Karsligil

Re: Port Knocking

Anonymous's picture

One can change the port knocking sequence randomly based on a shared key scheme. So it might depend on time and a key and change every second. So listening to ports won't mean anything since the same sequence would not work again. THe randomizer on both the client and the server would take the shared key and based on the key and let say time would create sequence of random ports.

Creating a client to go with the knockdeamon that also requires a password as part of the shared key scheme might also work. The ports triggered by the client could cause a client predictable key response, like the opening of a communications port on the server.

Because a hacker would not know which ports might be opened on the server side (it is not in the packet afterall, but part of a shared key and password scheme), it would be difficult for a hacker to guess which ports had been opened, but the client would know because of the shared key.

This newly opened port is random and based on a shared key, and could actually be the service you need open running on an uncommon port (the client would either tunnel the port, or start ssh pointed to the right port, for instance). The other option would be some secured communication on that port that could include further identification, or some sort of handshake to agree on what must be done (opening servers or what have you).

I think I have gone insane or something...

Gando Thesly

Re: Port Knocking

Anonymous's picture

Good point - I agree. If the eavesdropper is sophisticated and is looking for what you describe then the IP address of the connecting client would be detected.

It may be possible to prevent the eavesdropper from spoofing their IP address to match the clients, thereby being allowed to reach the application authentication after a successful connection. The server daemon could be configured to disregard any subsequent connections (even if they come from the same IP address) after the initial legitimate port knock is received and the first connection is made.

Martin Krzywinski (author)

Re: Port Knocking

Anonymous's picture

The port can always be closed immediately after first connection has been made. Adding a rule for allowing packages related to established connections come through, there is no need for keeping the port open. This works at least with iptables (--state related,established), dunno about ipchains.

Re: Port Knocking

Anonymous's picture

The port can always be closed immediately

This was of course for protocols like ssh, not http.

Re: Port Knocking

john golder's picture

yes, this was, how I understood it

sec or obs ?

Mike's picture

Uncommon ports. Shared keys. Port hopping. Come on guys, is this security or obscurity ?

Mike is right

anonymous's picture

and think of this: Because each attempt to knock is logged, whats to prevent an attacker from just filling up your logs? I sit behind a router that logs internally to its memory and the logs are "rolling" ie if the log gets full then the oldest entries are dropped as new ones are added. If i was using a pc to do this and logging to disk it would present a problem. If on the other hand you only log attempts at the port knocking ports then it reduces this problem greatly - I think port knocking is a good idea, but it needs more thought put to it especially by some security guru's, definately a step in the right direction tho.

Very interseting idea

mark davis's picture

Very interseting idea

firewall

portrait artist's picture

Thanks for this information. It’s time that firewall administrator and developer should review these requirements for them to be able to support the needs of firewall users.

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState