How to Take the Bite Out Of Malicious Links
Leetcode problem #1108 involved writing a quite method to “defang” ip addresses. The problem was simple enough (answer is further down), however I was intrigued to find out more about IP defanging. I have been working in the technology sector for three years and I had never heard the term. All due respect, I may have been under a rock?
I wasn’t able to find too much on the topic, however, some good documentation from IBM answered my question.
Essentially, when handling artifacts (contents) from an email or just generally passing data blobs which contain IP addresses, URLS or domains, we can “defang” them from accidental user-navigation by obscuring the address by messing it up a bit. Messing the adddress will ensure automatic click-through links don’t action.
What Are Some Defanging Methods?
The following are some accepted methods for defanging addresses:
- IP Addresses have brackets added to the dot separators: 18.104.22.168 -> 8[.]8[.]8[.]8
- Domains have brackets added to the dot separators: www.toddtee.sh -> www[.]toddtee[.]sh
- http / https converted to hxxp / hxxps
- ftp converted to fxp
How Could We Quickly Defang With Python
The leetcode question simply wants to take an input IP address and return it in a defanged format.
I first attempted this question without using any string methods. And WOW; was it UGLY!!! But… you know what… it worked!
1class Solution:2 def defangIPaddr(self, address: str) -> str:3 split_ip_chars = 4 defanged_ip = ""5 for char in address:6 if char != ".":7 split_ip_chars.append(char)8 elif char == ".":9 split_ip_chars.append("[.]")1011 for char in split_ip_chars:12 defanged_ip = defanged_ip+char1314 return defanged_ip
A Simple Way
Good software developers write as little code as possible; and when forced to, they keep the code
simple and clean. The simpler way to defang would be to use string methods
1class Solution:2 def defangIPaddr(self, address: str) -> str:3 return "[.]".join(address.split("."))
So this is a much simpler way of solving the issue; first we split the address on the dot seperators and then return the split array joined by the bracketed dots.
This is great, however I think we can write this even cleaner (and human friendly).
A Human Way
I personally prefer solving this issue with the
replace() method. It is simple and even easier to
read; so I am assuming 9/10 humans would prefer this way:
1class Solution:2 def defangIPaddr(self, address: str) -> str:3 return address.replace(".", "[.]")
That is my preferred method… keep it reeeeeeal simple.