From 58da5b85a077b4d4738b64f048c8abf530849e7d Mon Sep 17 00:00:00 2001 From: vakarisz Date: Tue, 14 Dec 2021 17:08:55 +0200 Subject: [PATCH] Island, UT: fix target generator bug when big ip is specified first 192.168.56.2-192.168.56.1 is now a valid range, will return both of these addresses --- monkey/common/network/network_range.py | 19 ++++++++++--------- .../network/test_scan_target_generator.py | 3 ++- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/monkey/common/network/network_range.py b/monkey/common/network/network_range.py index e58fffcec..479f5f0d7 100644 --- a/monkey/common/network/network_range.py +++ b/monkey/common/network/network_range.py @@ -4,6 +4,7 @@ import random import socket import struct from abc import ABCMeta, abstractmethod +from typing import Tuple logger = logging.getLogger(__name__) @@ -55,15 +56,20 @@ class NetworkRange(object, metaclass=ABCMeta): @staticmethod def check_if_range(address_str): if -1 != address_str.find("-"): - ips = address_str.split("-") - ips = [ip.strip() for ip in ips] try: - ipaddress.ip_address(ips[0]) and ipaddress.ip_address(ips[1]) + NetworkRange._range_to_ips(address_str) except ValueError: return False return True return False + @staticmethod + def _range_to_ips(ip_range: str) -> Tuple[str, str]: + ips = ip_range.split("-") + ips = [ip.strip() for ip in ips] + ips = sorted(ips, key=lambda ip: socket.inet_aton(ip)) + return ips[0], ips[1] + @staticmethod def _ip_to_number(address): return struct.unpack(">L", socket.inet_aton(address))[0] @@ -97,12 +103,7 @@ class IpRange(NetworkRange): def __init__(self, ip_range=None, lower_end_ip=None, higher_end_ip=None, shuffle=True): super(IpRange, self).__init__(shuffle=shuffle) if ip_range is not None: - addresses = ip_range.split("-") - if len(addresses) != 2: - raise ValueError( - "Illegal IP range format: %s. Format is 192.168.0.5-192.168.0.20" % ip_range - ) - self._lower_end_ip, self._higher_end_ip = [x.strip() for x in addresses] + self._lower_end_ip, self._higher_end_ip = IpRange._range_to_ips(ip_range) elif (lower_end_ip is not None) and (higher_end_ip is not None): self._lower_end_ip = lower_end_ip.strip() self._higher_end_ip = higher_end_ip.strip() diff --git a/monkey/tests/unit_tests/infection_monkey/network/test_scan_target_generator.py b/monkey/tests/unit_tests/infection_monkey/network/test_scan_target_generator.py index 702298db8..8d3166268 100644 --- a/monkey/tests/unit_tests/infection_monkey/network/test_scan_target_generator.py +++ b/monkey/tests/unit_tests/infection_monkey/network/test_scan_target_generator.py @@ -57,7 +57,8 @@ def test_middle_of_range_subnet(): @pytest.mark.parametrize( - "ip_range", ["192.168.56.25-192.168.56.33", "192.168.56.25 - 192.168.56.33"] + "ip_range", + ["192.168.56.25-192.168.56.33", "192.168.56.25 - 192.168.56.33", "192.168.56.33-192.168.56.25"], ) def test_ip_range(ip_range): scan_targets = compile_ranges_only([ip_range])