Apache 2.4 – How to Require Exclude IP Range

apache-2.4

I have an apache 2.4 server with Kerberos auth for localnet users. Now I need to allow public access to it without auth but still require auth for localnet.

If I simply remove "Require valid-user" directive then local users do not authenticate.

If I allow one public ip, everyting works perfectly, local users get authenticated, remote user from this IP gets access:

<RequireAny>
   Require ip 11.22.33.44
   Require valid-user
</RequireAny>

But if try to allow everyone EXCEPT locallet:

<RequireAny>
   Require ip not 192.168
   Require valid-user
</RequireAny>

then I get "Syntax error: negative Require directive has no effect in directive"

If I embed exclusion into RequireAll:

<RequireAny>
   <RequireAll>
      Require ip not 192.168
   <RequireAll>
   Require valid-user
</RequireAny>

then I get an error "RequireAll directive contains only negative authorization directives".

Similarly, adding

<RequireAny>
   <RequireNone>
      Require ip 192.168
   <RequireNone>
   Require valid-user
</RequireAny>

gives an error "RequireNone directive has no effect in directive".

So how such exclusion should be done?

Best Answer

A subtle detail when using the not in a Require directive to negate the match is that it cannot be used by itself to allow or deny a request, as "not true" does not constitute a "false".

Thus, to deny a visit using a negation, the block must have one element that does evaluate as true or false.

To create an IP-address blacklist, rather than a whitelist, you use the following construct:

<RequireAll>
  # Block IP-addresses from 192.168.2.1 and the 193.37.0.0/16 and 10.9.8.0/24 networks 
  Require not ip 192.168.2.1 193.37 10.9.8

  # Allow all other IP's
  Require all granted
</RequireAll> 

To allow public access without authenticating but still require auth for localnet you get a an authorisation container like:

<RequireAny>
   # users from the ip-range localnet must be authenticated 
   <RequireAll>
      Require ip "localnet"
      Require valid-user
   </RequireAll>
   # users not from the ip-range localnet are allowed anonymous access
   <RequireAll> 
       Require not ip "localnet"
       Require all granted
   <RequireAll>
</RequireAny>
Related Topic