Offensive PythonCompound Data TypesThe Counter Dictionary
Offensive PythonCompound Data TypesThe Counter Dictionary

     If we need to find the most common thing in an environment and we have, or can easily obtain a list, we can then use the Counter dictionary class from the collections module.  This is very useful on the defensive side, when it comes to counting hostnames, user agents, process names, and the like for incident response, forensics, or hunting use cases.   But there can be uses on the offensive side as well.  Maybe we’ve collected a large listing of Apache versions and want to count that data.  Here is an example below.

from collections import Counter

versions = [‘2.4.58’, ‘2.4.58’, ‘2.4.55’, ‘2.4.46’, ‘2.4.39’, ‘2.4.51’, ‘2.0.5’, ‘2.4.53’, ‘2.4.55’, ‘2.4.52’, ‘2.4.53’, ‘2.4.54’, ‘2.4.44’, ‘2.4.55’, ‘2.4.50’, ‘2.4.39’, ‘2.4.20’, ‘2.0.34’, ‘2.4.58’, ‘2.0.39’, ‘2.4.58’, ‘2.4.55’, ‘2.4.57’, ‘2.4.58’, ‘2.4.57’, ‘2.4.58’, ‘2.4.56’, ‘2.0.36’, ‘2.4.57’, ‘2.4.58’, ‘2.4.58’, ‘2.4.56’]

# Initialize counter with values already obtained
counter = Counter(versions)

# Or update the counter within your program as needed
# counter.update(versions)

# Obtain the most common entry and it’s count
print(counter.most_common(1))

# Obtain the least common entry and it’s count
print(counter.most_common(100)[-1])

# Obtain the 5 least common entries and their counts
print(counter.most_common(100)[-1:-6:-1])

Now we have a clear picture of Apache in the organization.   Output from above prints:

[(‘2.4.58’, 8)]
(‘2.0.36’, 1)
[(‘2.0.36’, 1), (‘2.0.39’, 1), (‘2.0.34’, 1), (‘2.4.20’, 1), (‘2.4.50’, 1)]

Leave a Reply

Your email address will not be published. Required fields are marked *