Nginx – How to force outgoing requests from webserver/PHP through squid proxy on same machine

nginxPROXYsquidtransparent-proxy

I have a Debian Squeeze VPS configured as an nginx web server. For security reasons I have blocked all outgoing connections except those to the Debian update servers (this stops bad scripts from calling home). PHP runs under a separate user as well. My problem is the following:

Various CMS-s and PHP/Perl/Python applications need to access web services on other servers (i.e. make outgoing HTTP connections). I have installed squid on that same VPS and want to use it as a transparent filter/proxy, by whitelisting the allowed domains.

I know how to force all outgoing port 80 connections through the proxy, but this would cause the proxy's own requests to be redirected to itself (i.e. infinite loop). I also can't use the ipt_owner module for iptables, as the VPS company unambiguously told me they are not going to install it.

Is there another clever way to force all other HTTP outgoing requests through the squid proxy on that same machine, while allowing the proxy's own requests out?

If it helps, I also have csf installed.

Thanks!

Best Answer

Ok, answering my own question:

Squid allows you to set the TOS on its outgoing packets. The setting is tcp_outgoing_tos . So, make an acl with the permitted IPs or domains and set, for example, tcp_outgoing_tos 0x10 whitelist

The packets from other applications usually have TOS 0x0.

Now follow the steps at squid's own tutorial http://wiki.squid-cache.org/ConfigExamples/Intercept/LinuxLocalhost#iptables_configuration, but instead of matching the packet's owner, we match the TOS.

# handle connections on the same box (SQUIDIP is a loopback instance)
iptables -t nat -A OUTPUT -p tcp --dport 80 -m tos --tos 0x10 -j ACCEPT
iptables -t nat -A OUTPUT -p tcp --dport 80 -j DNAT --to-destination SQUIDIP:3127

When using csf we may need to also accept these packets on the OUTPUT chain of the filter table. Put the rule at the beginning of the chain.

iptables -I OUTPUT -p tcp --dport 80 -m tos --tos 0x10 -j ACCEPT