Anonymize IPv4 address

Sometimes you need to anonymize IPv4 address. There are lot of solutions, one simple is to replace last octet with some text. This little snippet uses this approach to replace all ipv4 address in message:

rule "Anonymize IPv4"
when
   has_field("message")
then
      let anon_ip = regex_replace(pattern: "(?<![0-9])(?:([0-1]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])[.]([0-1]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])[.]([0-1]?[0-9]{1,2}|2[0-4][0-9]|25[0-5])[.]([0-1]?[0-9]{1,2}|2[0-4][0-9]|25[0-5]))(?![0-9])",
        value: to_string($message.message),
        replacement: "$1.$2.$3.xxx"
    );
    set_field("message", anon_ip);
end
2 Likes

Thanks for the first post, @shoothub . Let us know if we need to add anything to this category

Hey @shoothub, great post! (even if it was 2 years ago) Really helped me with syntax.

Although for recognizing IPv4 addresses with a regex pattern a simpler alternative would be:

let anon_ip = regex_replace(pattern: "(\\d{1,3}\\.)(\\d{1,3}\\.)(\\d{1,3}\\.)(\\d{1,3})",
value: to_string($message.message), 
replacement: "$1$2$3X"
);

PS: Don’t forget to use double escapes in pipelines, this has caught me out multiple times

2 Likes

@Linedo Thanks for reviving a member’s “blast from the past!” Yes, those of us who have been hanging out in this community of a few years now know of the legendary @shoothub . He contributed several gems of awesome help. We haven’t seen him the community for some time now, but @shoothub , thanks for your contributions, and if you’re still out there, stop by again. The Open Community misses you! :slight_smile: