Closing Ports on LinuxRecently in my web server class I talked about things you can do to secure your machine. One of those things was detecting open ports and figuring out how to close them. I wrote up a little "script" explaining the common case for doing this on RedHat-based machines and sent it to my class, but I thought it warranted posting here for anyone who might have to do this.
In the below example we scan our machine using Nmap and see that there is a port listening that we don't recognize. The other ports were due to services that we installed and configured, but one of them is not something that we installed. So we walk through using 'netstat' and 'ps' to determine what process is exposing that port and then show how to immediately kill the service (thus closing the port) and make sure it never gets opened again.
Of course, this assumes the offending process is an actual service, not some random binary being executed via non-traditional means. If the process is not a service you have to do some digging, but the below example will fit most cases.
# # Scan our machine to see what ports are open # [root@server0 ~]# nmap 10.85.10.101 Starting Nmap 5.51 ( http://nmap.org ) at 2013-04-09 15:54 EDT Nmap scan report for server0.slonka.com (10.85.10.101) Host is up (0.0000070s latency). Not shown: 994 closed ports PORT STATE SERVICE 21/tcp open ftp 22/tcp open ssh 23/tcp open telnet 53/tcp open domain 80/tcp open http 111/tcp open rpcbind Nmap done: 1 IP address (1 host up) scanned in 0.08 seconds # # Port 111 is open and we don't know what it is. We probably want to close it. # Let's see what process on our machine is exposing port 111 # [root@server0 ~]# netstat -anp | grep :111 tcp 0 0 0.0.0.0:111 0.0.0.0:* LISTEN 2305/rpcbind tcp 0 0 :::111 :::* LISTEN 2305/rpcbind udp 0 0 0.0.0.0:111 0.0.0.0:* 2305/rpcbind udp 0 0 :::111 :::* 2305/rpcbind # # We see that process ID 2305 is exposing port 111 on all network interfaces (0.0.0.0) # Let's see what the name of the program is that's running as PID 2305 # [root@server0 ~]# ps ax | grep 2305 2305 ? Ss 0:00 rpcbind 2327 pts/0 S+ 0:00 grep 2305 # # We now know the name of the program is rpcbind. Let's see if it's a normal service. # [root@server0 ~]# chkconfig --list | grep rpcbind rpcbind 0:off 1:off 2:on 3:on 4:on 5:on 6:off # # It is, and it's turned "on" for runlevel 3 (multi-user text-mode), which is what we use. # Let's stop it right now so it's no longer open. # [root@server0 ~]# service rpcbind stop Stopping rpcbind: [OK] # # That's great, but the next time we reboot the service will start again because it's set to # "on". Let's turn off the service so it never runs again. # [root@server0 ~]# chkconfig rpcbind off