Enable PHP fsockopen with CSF
Recently started some sites with Liquid Web hosting, everything going extremely well all around. There was one hiccup (at least for me) where PHP’s
fsockopen was not working. At the time, I was trying to figure out why the Whois Lookup feature used by Blackhole Bad Bots was not working. Initial investigation revealed that
fsockopen() external HTTP requests were getting blocked somewhere. Everything else worked, including making the requests via
Further investigation revealed that outgoing requests were blocked only on certain ports. Some ports worked fine but not the one I needed at the time (port 43). After some digging, turns out that CSF firewall is enabled on the server. And guess what, the CSF configuration specifically whitelists which ports are allowed access for incoming, outgoing, and other requests.
To enable outgoing/external requests to port 43, open
/etc/csf/csf.conf via Terminal/SSH (or whatever you’re using to access the server). Make a backup of the file, and then open the original and edit the “outgoing TCP ports” to include your port number(s). Here are the default CSF ports with “43” added to the list:
# Allow incoming TCP ports TCP_IN = "20,21,22,25,53,80,110,143,443,465,587,993,995,26" # Allow outgoing TCP ports TCP_OUT = "20,21,22,25,37,43,53,80,110,113,443,587,873"
Save changes and done.
fsockopen (and anything else) now allowed to make outgoing requests and therefore function properly.
Looking at the code, here is the command that was failing:
$sock = fsockopen($server, 43, $num, $error, 20);
Notice the “43”, that is the port number. Now, if we look at the
csf.conf file, we see the default whitelisted ports for outgoing requests:
# Allow outgoing TCP ports TCP_OUT = "20,21,22,25,53,80,110,113,443,587,993,995"
Notice that 43 is not on the list, so not allowed. And THAT my friends is why PHP
fsockopen is not working for certain ports.
Now to fix, let’s add our port 43 to the CSF whitelist. Here are detailed steps for those who may need them.
- Connect to your server via SSH/Terminal (or whatever you prefer)
- Locate the configuration file,
- Make a quick backup:
cp csf.conf csf.conf.bak
- Use vi to edit the file (or install/use nano:
yum install nano)
- In the file, scroll to:
TCP_OUT = "20,21,22,25,53,80,110,..."
- Add your port(s) to the list, save changes, and exit editor
- Now restart CSF so changes take effect:
Effective results immediately,
fsockopen able to connect on port 43 as required (or whatever port numbers you are working with). And keep in mind that this same process can be used for customizing other aspects of CSF.
Have fun! :)