피드 구독

The ncat command is part of the nmap suite and was written specifically for it. It's true that ncat has as many uses as the famed Swiss Army knife, but it can be as equally dangerous when incorrectly used or when used by malicious actors. One of its strengths is that ncat can be both client and server. This article focuses on one aspect of that relationship. I show you how to open a listening bash shell with ncat that anyone can access with ncat as a client. In my article, Linux troubleshooting: Setting up a TCP listener with ncat, I describe how to set up ncat as a listener or server that listens on a specific port. This example is similar, but I think you'll be impressed with the sheer power that ncat gives you. It should also scare you—a lot.

Install ncat

Check your system under /usr/bin first to see if you need to install ncat. It is typically included in any Red Hat Enterprise Linux-based distribution. If you find that you need to install it, the package name is nmap-ncat. You either can install ncat by itself or install nmap and the nmap-ncat package installs as a dependency.

Use ncat

Don't issue ncat commands as root, especially for the examples in this article. Doing so will allow anyone to have root access to your system without authentication. Any user can issue ncat commands, which is one of its features as well as one of its dangers. I suggest that you create a service account and work with ncat using that account. Trust me, I've heard every argument for and against service accounts, but once you see ncat in action, you'll want to use the service account for interactions with it.

Deliver a bash shell

This is the fun (and dangerous) part of using ncat. Switch user to your new service account. I've named mine bashful.

[ken@server1 ~] $ su - bashful
Password: 
[bashful@server1 ~] $

Now that you've switched user accounts, it's time to open that shell. It gives unauthenticated access to your system via a mostly interactive shell. You'll see what I mean by "mostly" interactive once you connect. This next command uses ncat to execute a bash shell that listens on a TCP port. For this example, I'm using port 9922 on server1 (192.168.1.50). The -l option sets up a listening port. The -k option is a keepalive flag, which maintains the socket. If you don't issue the -k option, then the socket dies after you disconnect the session, and no other connections can be made to it.

[bashful@server1 ~] $ ncat -e "/bin/bash" -l 9922 -k &

The -e option executes the command in quotes, which in our case is the bash shell (/bin/bash). I use the ampersand (&) after the command to release my prompt and put the ncat listener into background mode. If you don't use the &, then your terminal will "hang" and not allow you to interact with it. If that's not a problem for you, then leave it as is.

Issuing the netstat command shows that the listener is in place.

[bashful@server1 ~]$ netstat -an |grep 9922
tcp        0      0 0.0.0.0:9922            0.0.0.0:*               LISTEN     
tcp6       0      0 :::9922                 :::*                    LISTEN     
[bashful@server1 ~]$

To connect to the listening port from a remote system, you also have to open an exception in the host-based firewall for port 9922.

[ken@server1 ~]$ sudo firewall-cmd --add-port=9922/tcp
success

Do you see the failsafe here? It's the firewall exception that I had to create using my account and sudo. If you have a host-based firewall or IPTables running (and you'd better have), then this service won't work until you allow that port, which means that no ordinary user can make this work without administrative access. Otherwise, ncat-educated users would be opening ports all over the place and driving you crazy in the process. Not to mention the security issues you'd have. I digress.

Access the shell from a remote system

Now you can access the bash shell from a remote system on port 9922.

[ken@server2 ~]$ ncat 192.168.1.50 9922

From server2, issue the ncat command with the target IP address of server1 and the listening port 9922. Once you're connected, nothing happens, or so you might believe because the terminal seems to sort of hang. But what's really happening is that you're communicating with the raw socket and therefore, will not see a prompt. Prove it by issuing the who command.

[ken@server2 ~]$ ncat 192.168.1.50 9922
who
ken    pts/0        2020-08-26 13:39 (server2)

You can issue any command you wish that user bashful has access to. If you issue a command that requires root access, you will likely not see a response. The terminal will appear to stay in the "hung" state. Your response will actually appear on the terminal of server1. For example, if you issue the following command:

firewall-cmd --list-all

You see nothing on server2's screen. On server1's screen, the following appears:

[bashful@server1 ~]$ Authorization failed.
    Make sure polkit agent is running or run the application as superuser.

To disconnect from server2's clandestine shell, issue the Ctrl+C combination and your local prompt returns.

Don't try this at work

Just for fun, or if you don't believe me, kill the current ncat process using your service account or as root. Then re-issue the same command as the root user to execute that bash shell as root. Connect again from a remote system and re-issue that firewall command. This time you'll see the results. You can issue any command as root, which is why you never want to set up this type of service as the root user.

And now you see the real danger of using ncat as root. Malicious actors will set up such a shell on a clandestine port that's missed by a port scan and have full root access without authentication.

Wrap up

The very useful and potentially very dangerous ncat command is your best friend and your worst enemy. Like every other tool in the shed, it has no intent other than what you give it. You should study the ncat command, its uses, and its limitations in your environment. Remember to kill any ncat process that you don't want to continuously run once you're finished with it and remove the firewall exception that allows its access. Also, remember that with great power comes the ability to really screw things up.

[ Want to test your sysadmin skills? Take a skills assessment today. ]


저자 소개

Ken has used Red Hat Linux since 1996 and has written ebooks, whitepapers, actual books, thousands of exam review questions, and hundreds of articles on open source and other topics. Ken also has 20+ years of experience as an enterprise sysadmin with Unix, Linux, Windows, and Virtualization.

Follow him on Twitter: @kenhess for a continuous feed of Sysadmin topics, film, and random rants.

In the evening after Ken replaces his red hat with his foil hat, he writes and makes films with varying degrees of success and acceptance. He is an award-winning filmmaker who constantly tries to convince everyone of his Renaissance Man status, also with varying degrees of success and acceptance.

Read full bio
UI_Icon-Red_Hat-Close-A-Black-RGB

채널별 검색

automation icon

오토메이션

기술, 팀, 인프라를 위한 IT 자동화 최신 동향

AI icon

인공지능

고객이 어디서나 AI 워크로드를 실행할 수 있도록 지원하는 플랫폼 업데이트

open hybrid cloud icon

오픈 하이브리드 클라우드

하이브리드 클라우드로 더욱 유연한 미래를 구축하는 방법을 알아보세요

security icon

보안

환경과 기술 전반에 걸쳐 리스크를 감소하는 방법에 대한 최신 정보

edge icon

엣지 컴퓨팅

엣지에서의 운영을 단순화하는 플랫폼 업데이트

Infrastructure icon

인프라

세계적으로 인정받은 기업용 Linux 플랫폼에 대한 최신 정보

application development icon

애플리케이션

복잡한 애플리케이션에 대한 솔루션 더 보기

Original series icon

오리지널 쇼

엔터프라이즈 기술 분야의 제작자와 리더가 전하는 흥미로운 스토리