diff --git a/lib/snmpkit/snmp_lib/host_parser.ex b/lib/snmpkit/snmp_lib/host_parser.ex index 14bedb00..f5426865 100644 --- a/lib/snmpkit/snmp_lib/host_parser.ex +++ b/lib/snmpkit/snmp_lib/host_parser.ex @@ -329,28 +329,37 @@ defmodule SnmpKit.SnmpLib.HostParser do end end - defp validate_ipv4_tuple({a, b, c, d}) - when is_integer(a) and is_integer(b) and is_integer(c) and is_integer(d) and a >= 0 and a <= 255 and b >= 0 and - b <= 255 and c >= 0 and c <= 255 and d >= 0 and d <= 255 do - :ok + defp validate_ipv4_tuple({a, b, c, d}) do + if valid_ipv4_octet?(a) and valid_ipv4_octet?(b) and + valid_ipv4_octet?(c) and valid_ipv4_octet?(d) do + :ok + else + {:error, :invalid_ipv4_tuple} + end end defp validate_ipv4_tuple(_), do: {:error, :invalid_ipv4_tuple} - defp validate_ipv6_tuple({a, b, c, d, e, f, g, h}) - when is_integer(a) and is_integer(b) and is_integer(c) and is_integer(d) and is_integer(e) and is_integer(f) and - is_integer(g) and is_integer(h) and a >= 0 and a <= 65_535 and b >= 0 and b <= 65_535 and c >= 0 and - c <= 65_535 and d >= 0 and d <= 65_535 and e >= 0 and e <= 65_535 and f >= 0 and f <= 65_535 and g >= 0 and - g <= 65_535 and h >= 0 and h <= 65_535 do - :ok + defp valid_ipv4_octet?(n), do: is_integer(n) and n >= 0 and n <= 255 + + defp validate_ipv6_tuple({a, b, c, d, e, f, g, h}) do + octets = [a, b, c, d, e, f, g, h] + + if Enum.all?(octets, &valid_ipv6_segment?/1) do + :ok + else + {:error, :invalid_ipv6_tuple} + end end defp validate_ipv6_tuple(_), do: {:error, :invalid_ipv6_tuple} + defp valid_ipv6_segment?(n), do: is_integer(n) and n >= 0 and n <= 65_535 + defp validate_port(port) when is_integer(port) and port >= 1 and port <= 65_535, do: :ok defp validate_port(_), do: {:error, :invalid_port} - # Validate that a charlist contains only valid characters (0-255 for bytes, but more restrictively for reasonable text) + # Validate charlist contains only valid characters (0-255 for bytes) defp valid_charlist?(charlist) do # Additional check: ensure it would create valid UTF-8 when converted to string Enum.all?(charlist, fn char ->