Block Unauthorized Requests at Varnish [Code Optimization]

Uday Kumar uday.polu at indiamart.com
Thu Oct 12 17:14:21 UTC 2023


Hello everyone,

We use varnish in our production environment for caching content.

Our Requirement:

We are trying to block unauthorized requests at varnish based on the source
parameter in the URL and the client IP in the request header.

For example:

Sample URL:

www.hostname:port/path?source=mobile&keyword= bags

Let's assume there are 3 IPs [which are allowed to access varnish]
associated with the above request of mobile source.

i.e *IP1, IP2, IP3*

So if any request comes with the source as *mobile *and client-ip as *IP4*,
it's treated as an unauthorized request and should be blocked at varnish.


What we have done for blocking?

*Sample URL:*
www.hostname:port/path?source=mobile&keyword= bags

Created a map using ACL as below:

acl mobile_source{

              "IP1";

              "IP2";

              "IP3";

}

If(req.url ~ "source=mobile" && client.ip !~ mobile_source) {

           return(Synth(403, "varnish access denied!"))

}


The problem we are facing:

The source parameter can have different values like mobile, desktop,
laptop, tablet, etc. and each value can have different IPs associated with
it.

ACL Rules will be as below:

acl mobile_source{

              "IP1";

              "IP2";

              "IP3";

}

acl desktop_source{

              "IP4";

              "IP5";

              "IP6";

}

and so on,


If we wanted to block unauthorized access from different source vs IP
combinations, we would have to add that many conditions as below.

If(

(req.url ~ "source=mobile" && client.ip != mobile_source) ||

(req.url ~ "source=desktop" && client.ip != desktop_source) ||

(req.url ~ "source=laptop" && client.ip != laptop_source) ||

(req.url ~ "source=tablet" && client.ip != tablet_source)

){

           return(Synth(403, "access denied!"))

}

This becomes worse, if we have 10's or 20's of source values.

Our question:

We would like to know if there is any way to optimize the code by removing
redundant checks so that we can scale it even if we have many sources vs IP
combinations.


Thanks & Regards
Uday Kumar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://www.varnish-cache.org/lists/pipermail/varnish-misc/attachments/20231012/f5992842/attachment-0001.html>


More information about the varnish-misc mailing list