Best practice for implementing a blacklist IP / url check

I would like to know if anyone has recommendations or suggestions for adding a blacklist IP and/or url-path check in service stack and reject. Http error code?

My scenario is a self-hosted app, so I guess somewhere as a global request filter. Has anyone integrated the Google SafeBrowsing approach, or a home-brew IP list to ban if it requests things like…

  • /muieblackcat
  • /phpmyadmin/scripts/setup.php

Thanks!

Doing more research, I’m thinking a RawHttpHandlers filter based on posts

> ServiceStack/ServiceStack/wiki/Order-of-Operations
> servicestack-prevent-unauthorized-access-to-static-files

and a custom Blacklist service using a homebrew table with “bad” IP and Paths. Going the Raw handler way ensures that a bad request gets stopped before trying to dig around to find a matching route…

thoughts?

Global Request Filter or PreRequest Filter would be the way to go. If you’re making a network call I would be caching the results of IP lookups to prevent subsequent network requests for the same IP’s. In which case I’d probably just use a singleton ConcurrentDictionary<string,bool> to cache results of IP lookups.

Yeah that works to and is invoked first in the Request Pipeline, although you would need to return an IHttpHandler (i.e. you can’t end the Response in the HttpHandlerFactory directly), but the built-in CustomActionHandler makes this easy, e.g:

RawHttpHandlers.Add(r => 
  IpLookups.IsSafe(r.UserHostAddress) 
     ? null // Let the Request Pipeline Continue
     : new CustomActionHandler((req, res) => {
          res.StatusCode = 403;
          res.StatusDescription = "Thou Shall Not Pass!";
          res.EndHttpHandlerRequest(skipHeaders: true);
      }));
1 Like

That’s pretty much what I was going with; however, by reflex I made my lookup use a simple service with an Ormlite friendly POCO for BlacklistItem and used a built-in handler. I like your Gandalf reference, but I may opt for an xfiles Trust No One reference.

If others have used 3rd party blacklist services, I’m all ears!

Copied my code snippet for reference:

if (appSettings.Get<bool>("useBlacklist", false))
{
    RawHttpHandlers.Add(req =>
    {
       return Resolve<BlacklistService>().IsBlacklisted(req.RemoteIp, req.PathInfo)
               ? new ServiceStack.Host.Handlers.ForbiddenHttpHandler()
                : null;
         });
    }
}
[...]
public bool IsBlacklisted(string ip, string path = null)
{
    var ev = OrmLiteConfig.DialectProvider.SqlExpression<BlacklistInfo>();
        
    if (ip.HasValue())
        ev.Or(a => a.ip == ip);
    if (path.HasValue())
        ev.Or(a => a.path == path);
    
    if (Db.Count(ev) > 0)
        return true;

    return false;
}
1 Like