Analyzing user agents to identify bots with Elasticsearch

Most of you probably know my startup elmah.io. If not, check it out and head back here when you’ve signed up 🙂 At elmah.io we index errors generated at our customers websites. Among a lot of other things, we index the user agent causing the error. If you’ve ever logged uncaught errors (like 404’s) on a webserver, you know that bots, crawlers, spiders etc. are causing a lot of them.

To minimize the number of logged errors for ourselves and our customers, I want to be able to identify bots by looking at the user agent causing an error. I know that there are lists of both whitehat and blackhat bots out there, but for this purpose, I want a single, short and fast query, identifying as many whitehat bots as possible.

To have some data to play around with, I’ve fetched a list of browser user agents and another list of bot user agents (source: http://useragentstring.com/). Both lists are converted to Elasticsearch bulk index format. Since the purpose of this post is playing around with aggregations in Elasticsearch, I won’t go into detail on how to convert HTML to Elasticsearch bulk format.

To create a new Elasticsearch index to store all of the user agents, execute the following request:

To index the data and let Elasticsearch create the mapping for the browsers and bots types, POST all of the user agents using the _bulk endpoint:

All user agents are successfully indexed in Elasticsearch. Since the userAgent field in both browsers and bots is analyzed, Elasticsearch breaks down all of the user agent strings into terms. This actually helps us to find common keywords in bot user agents.

To find the most commonly used terms in bot user agents, create a new terms aggregation on all of the bot user agents:

Elasticsearch returns a list of buckets, ordered by the most frequent terms:

This is great input for our identifying bots-quest. Using terms like Mozilla and compatible probably isn’t a good idea, since browser user agents includes these as well. By scrolling down through the list, we find bot, spider, crawler and other interesting terms. Let’s create a query against all bot user agents with these terms:

As we can see from the result, Elasticsearch finds a lot of hits:

Time to test the query against browser user agents to make sure that browsers aren’t threated as bots:

The query returns zero hits.

Using Elasticsearch for analyzing user agents and creating a smart query based on terms, turned out as a great way to identify most bots without having to maintain long lists of user agents, making API calls or similar. Querying Elasticsearch takes a few milliseconds and the result is almost as good as writing a lot of code.