July 3, 2011, 1:41 a.m.
posted by unixgeek
Prevent Services from Binding to an Interface
Keep services from listening on a port instead of firewalling them.
Sometimes, you might want to limit a service to listen on only a specific interface. For instance, Apache [Hack #55] can be configured to listen on a specific interface as opposed to all available interfaces. You can do this by using the Listen directive in your configuration file and specifying the IP address of the interface:
If you use VirtualHost entries, you can specify interfaces to bind to on a per-virtual-host basis:
<VirtualHost 192.168.0.23> ... </VirtualHost>
You might even have services that are listening on a TCP port but don't need to be. Database servers such as MySQL are often used in conjunction with Apache and are frequently set up to coexist on the same server when used in this way. Connections that come from the same machine that MySQL is installed on use a domain socket in the filesystem for communications. Therefore, MySQL doesn't need to listen on a TCP socket. To keep it from listening, you can either use the --skip-networking command-line option when starting MySQL or specify it in the [mysqld] section of your my.cnf file:
[mysqld] ... skip-networking ...
Another program that you'll often find listening on a port is your X11 server, which listens on TCP port 6000 by default. This port is traditionally used to enable remote clients to connect to your X11 server so they can draw their windows and accept keyboard and mouse input; however, with the advent of SSH and X11 forwarding, this really isn't needed anymore. With X11 forwarding enabled in ssh, any client that needs to connect to your X11 server will be tunneled through your SSH connection and will bypass the listening TCP port when connecting to your X11 server.
To get your X Windows server to stop listening on this port, all you need to do is add -nolisten tcp to the command that is used to start the server. This can be tricky, thoughfiguring out which file controls how the server is started can be a daunting task. Usually, you can find what you're looking for in /etc/X11.
If you're using gdm, open gdm.conf and look for a line similar to this one:
Then, just add -nolisten tcp to the end of the line.
If you're using xdm, look for a file called Xservers and make sure it contains a line similar to this:
:0 local /usr/X11R6/bin/X -nolisten tcp
Alternatively, if you're not using a managed display and instead are using startx or a similar command to start your X11 server, you can just add -nolisten tcp to the end of your startx command. To be sure that it is passed to the X server process, start it after an extra set of hyphens:
$ startx -- -nolisten tcp
Once you start X, fire up a terminal and see what is listening using lsof or netstat [Hack #8]. You should no longer see anything bound to port 6000.