It should be pretty easy to validate an IP address. IPv4 addresses are 32-bit unsigned integers, and IPv6 addresses are 128-bit unsigned integers. Things get "interesting" when developers attempt to validate IP addresses as a string. There have been a few interesting vulnerabilities around this issue (CVE-2021-28918, CVE-2021-29921, CVE-2021-29418).
So, let's take a look at how IPv4 addresses may be represented:
This all becomes important if you are attempting to validate if the IP address is syntactically valid and if you are also interested in restricting the IP address to a specific subnet. And the most common mistake is to treat IPv4 addresses as a string.
In my opinion, there is only one "right" way to validate IPv4 addresses:
Anything else is likely going to get you into trouble. The socket library is handy because it is usually used to establish connections. By using inet_aton, your chances increase significantly so that your input validation interprets the IP address the same way it will be when a connection is established using this IP address.
Any other suggestions?
---
Johannes B. Ullrich, Ph.D. , Dean of Research, SANS.edu
Twitter|