def test_get_all_interfaces(self): loopback_count = 0 non_loopback_count = 0 for iface in osutil.DefaultOSUtil()._get_all_interfaces(): if iface == 'lo': loopback_count += 1 else: non_loopback_count += 1 self.assertEqual(loopback_count, 1, 'Exactly 1 loopback network interface should exist') self.assertGreater( loopback_count, 0, 'At least 1 non-loopback network interface should exist')
def test_mount_dvd_failure(self, _): msg = 'message' with patch.object(osutil.DefaultOSUtil, 'get_dvd_device', return_value='/dev/cdrom'): with patch.object(shellutil, 'run_get_output', return_value=(1, msg)) as patch_run: with patch.object(os, 'makedirs'): try: osutil.DefaultOSUtil().mount_dvd() self.fail('OSUtilError was not raised') except OSUtilError as ose: self.assertTrue(msg in ustr(ose)) self.assertTrue(patch_run.call_count == 6)
def test_get_firewall_dropped_packets(self): osutil._enable_firewall = True destination = '168.63.129.16' with TestOSUtil._mock_iptables() as mock_iptables: mock_iptables.set_command(osutil._get_firewall_packets_command(mock_iptables.wait), output=''' Chain OUTPUT (policy ACCEPT 104 packets, 43628 bytes) pkts bytes target prot opt in out source destination 0 0 ACCEPT tcp -- any any anywhere 168.63.129.16 owner UID match daemon 32 1920 DROP tcp -- any any anywhere 168.63.129.16 ''') self.assertEqual(32, osutil.DefaultOSUtil().get_firewall_dropped_packets(destination))
def test_enable_firewall_skips_if_disabled(self, mock_run, mock_output, mock_uid): osutil._enable_firewall = False util = osutil.DefaultOSUtil() dst = '1.2.3.4' uid = 42 version = "iptables v{0}".format(osutil.IPTABLES_LOCKING_VERSION) mock_run.side_effect = [1, 0, 0] mock_output.side_effect = [(0, version), (0, "Output")] self.assertFalse(util.enable_firewall(dst_ip=dst, uid=uid)) mock_run.assert_not_called() mock_output.assert_not_called() mock_uid.assert_not_called() self.assertFalse(osutil._enable_firewall)
def test_mount_dvd_failure(self, _): msg = 'message' exception = shellutil.CommandError("mount dvd", 1, "", msg) with patch.object(osutil.DefaultOSUtil, 'get_dvd_device', return_value='/dev/cdrom'): with patch.object(shellutil, 'run_command', side_effect=exception) as patch_run: with patch.object(os, 'makedirs'): try: osutil.DefaultOSUtil().mount_dvd() self.fail('OSUtilError was not raised') except OSUtilError as ose: self.assertTrue(msg in ustr(ose)) self.assertEqual(patch_run.call_count, 5)
def test_restart(self): # setup retries = 3 ifname = 'dummy' with patch.object(shellutil, "run") as run_patch: run_patch.return_value = 1 # execute osutil.DefaultOSUtil.restart_if(osutil.DefaultOSUtil(), ifname=ifname, retries=retries, wait=0) # assert self.assertEqual(run_patch.call_count, retries) self.assertEqual(run_patch.call_args_list[0][0][0], 'ifdown {0} && ifup {0}'.format(ifname))
def test_get_firewall_dropped_packets(self, mock_output): osutil._enable_firewall = True util = osutil.DefaultOSUtil() mock_output.side_effect = [ (0, "iptables v{0}".format(osutil.IPTABLES_LOCKING_VERSION)), (0, ''' Chain OUTPUT (policy ACCEPT 104 packets, 43628 bytes) pkts bytes target prot opt in out source destination 0 0 ACCEPT tcp -- any any anywhere 168.63.129.16 owner UID match daemon 32 1920 DROP tcp -- any any anywhere 168.63.129.16 ''')] dst = '168.63.129.16' self.assertEqual(32, util.get_firewall_dropped_packets(dst))
def test_enable_firewall_skips_if_drop_exists(self, mock_run, mock_output, mock_uid): osutil._enable_firewall = True util = osutil.DefaultOSUtil() dst = '1.2.3.4' uid = 42 version = "iptables v{0}".format(osutil.IPTABLES_LOCKING_VERSION) wait = "-w" mock_run.side_effect = [0, 0, 0] mock_output.return_value = (0, version) self.assertTrue(util.enable_firewall(dst_ip=dst, uid=uid)) mock_run.assert_has_calls([ call(osutil.FIREWALL_DROP.format(wait, "C", dst), chk_err=False), ]) mock_output.assert_has_calls([call(osutil.IPTABLES_VERSION)]) self.assertTrue(osutil._enable_firewall)
def test_remove_firewall(self): osutil._enable_firewall = True with TestOSUtil._mock_iptables() as mock_iptables: delete_commands = {} def mock_popen(command, *args, **kwargs): command_string = TestOSUtil._command_to_string(command) if " -D " in command_string: # The agent invokes the delete commands continuously until they return 1 to indicate the rules has been removed # The mock returns 0 (success) the first time it is invoked and 1 (rule does not exist) thereafter if command_string not in delete_commands: exit_code = 0 delete_commands[command_string] = 1 else: exit_code = 1 delete_commands[command_string] += 1 command = "echo '' && exit {0}".format(exit_code) kwargs["shell"] = True return mock_popen.original(command, *args, **kwargs) mock_popen.original = subprocess.Popen with patch("azurelinuxagent.common.cgroupapi.subprocess.Popen", side_effect=mock_popen): success = osutil.DefaultOSUtil().remove_firewall(mock_iptables.destination, mock_iptables.uid) delete_conntrack_accept_command = TestOSUtil._command_to_string(osutil._get_firewall_delete_conntrack_accept_command(mock_iptables.wait, mock_iptables.destination)) delete_owner_accept_command = TestOSUtil._command_to_string(osutil._get_firewall_delete_owner_accept_command(mock_iptables.wait, mock_iptables.destination, mock_iptables.uid)) delete_conntrack_drop_command = TestOSUtil._command_to_string(osutil._get_firewall_delete_conntrack_drop_command(mock_iptables.wait, mock_iptables.destination)) self.assertTrue(success, "Removing the firewall should have succeeded") self.assertEqual(len(delete_commands), 3, "Expected 3 delete commands: [{0}]".format(delete_commands)) # delete rules < 2.2.26 self.assertIn(delete_conntrack_accept_command, delete_commands, "The delete conntrack accept command was not executed") self.assertEqual(delete_commands[delete_conntrack_accept_command], 2, "The delete conntrack accept command should have been executed twice") self.assertIn(delete_owner_accept_command, delete_commands, "The delete owner accept command was not executed") self.assertEqual(delete_commands[delete_owner_accept_command], 2, "The delete owner accept command should have been executed twice") # delete rules >= 2.2.26 self.assertIn(delete_conntrack_drop_command, delete_commands, "The delete conntrack drop command was not executed") self.assertEqual(delete_commands[delete_conntrack_drop_command], 2, "The delete conntrack drop command should have been executed twice") self.assertTrue(osutil._enable_firewall)
def test_enable_firewall_should_set_up_the_firewall(self): osutil._enable_firewall = True with TestOSUtil._mock_iptables() as mock_iptables: # fail the rule check to force enable of the firewall mock_iptables.set_command(osutil._get_firewall_drop_command(mock_iptables.wait, "-C", mock_iptables.destination), exit_code=1) success = osutil.DefaultOSUtil().enable_firewall(dst_ip=mock_iptables.destination, uid=mock_iptables.uid) drop_check_command = TestOSUtil._command_to_string(osutil._get_firewall_drop_command(mock_iptables.wait, "-C", mock_iptables.destination)) accept_command = TestOSUtil._command_to_string(osutil._get_firewall_accept_command(mock_iptables.wait, "-A", mock_iptables.destination, mock_iptables.uid)) drop_add_command = TestOSUtil._command_to_string(osutil._get_firewall_drop_command(mock_iptables.wait, "-A", mock_iptables.destination)) self.assertTrue(success, "Enabling the firewall was not successful") self.assertEqual(len(mock_iptables.command_calls), 3, "Incorrect number of calls to iptables: [{0}]". format(mock_iptables.command_calls)) self.assertEqual(mock_iptables.command_calls[0], drop_check_command, "The first command should check the drop rule") self.assertEqual(mock_iptables.command_calls[1], accept_command, "The second command should add the accept rule") self.assertEqual(mock_iptables.command_calls[2], drop_add_command, "The third command should add the drop rule") self.assertTrue(osutil._enable_firewall, "The firewall should not have been disabled")
def test_remove_firewall(self, mock_run, mock_output, mock_uid): osutil._enable_firewall = True util = osutil.DefaultOSUtil() dst = '1.2.3.4' uid = 42 version = "iptables v{0}".format(osutil.IPTABLES_LOCKING_VERSION) wait = "-w" mock_run.side_effect = [0, 0] mock_output.side_effect = [(0, version), (0, "Output")] self.assertTrue(util.remove_firewall()) mock_run.assert_has_calls([ call(osutil.FIREWALL_FLUSH.format(wait), chk_err=True) ]) mock_output.assert_has_calls([ call(osutil.IPTABLES_VERSION) ]) self.assertTrue(osutil._enable_firewall)
def test_conf_sshd_with_match_last(self): new_file = "\ Port 22\n\ Match host 192.168.1.1\n\ ChallengeResponseAuthentication yes\n\ " expected_output = "\ Port 22\n\ PasswordAuthentication no\n\ ChallengeResponseAuthentication no\n\ ClientAliveInterval 180\n\ Match host 192.168.1.1\n\ ChallengeResponseAuthentication yes\n\ " with patch.object(fileutil, 'write_file') as patch_write: with patch.object(fileutil, 'read_file', return_value=new_file): osutil.DefaultOSUtil().conf_sshd(disable_password=True) patch_write.assert_called_once_with( conf.get_sshd_conf_file_path(), expected_output)
def test_is_current_instance_id_from_file(self, mock_read, mock_isfile): # pylint: disable=unused-argument util = osutil.DefaultOSUtil() mock_read.return_value = "11111111-2222-3333-4444-556677889900" self.assertFalse(util.is_current_instance_id( "B9F3C233-9913-9F42-8EB3-BA656DF32502")) mock_read.return_value = "B9F3C233-9913-9F42-8EB3-BA656DF32502" self.assertTrue(util.is_current_instance_id( "B9F3C233-9913-9F42-8EB3-BA656DF32502")) mock_read.return_value = "33C2F3B9-1399-429F-8EB3-BA656DF32502" self.assertTrue(util.is_current_instance_id( "B9F3C233-9913-9F42-8EB3-BA656DF32502")) mock_read.return_value = "b9f3c233-9913-9f42-8eb3-ba656df32502" self.assertTrue(util.is_current_instance_id( "B9F3C233-9913-9F42-8EB3-BA656DF32502")) mock_read.return_value = "33c2f3b9-1399-429f-8eb3-ba656df32502" self.assertTrue(util.is_current_instance_id( "B9F3C233-9913-9F42-8EB3-BA656DF32502"))
def test_dhcp_skip_cache(self): handler = dhcp.get_dhcp_handler() handler.osutil = osutil.DefaultOSUtil() open_file_mock = mock.mock_open(read_data=TestDHCP.DEFAULT_ROUTING_TABLE) with patch('os.path.exists', return_value=False): with patch.object(osutil.DefaultOSUtil, 'get_dhcp_lease_endpoint')\ as patch_dhcp_cache: with patch.object(dhcp.DhcpHandler, 'send_dhcp_req') \ as patch_dhcp_send: endpoint = 'foo' patch_dhcp_cache.return_value = endpoint # endpoint comes from cache self.assertFalse(handler.skip_cache) with patch("os.path.exists", return_value=True): with patch(open_patch(), open_file_mock): handler.run() self.assertTrue(patch_dhcp_cache.call_count == 1) self.assertTrue(patch_dhcp_send.call_count == 0) self.assertTrue(handler.endpoint == endpoint) # reset handler.skip_cache = True handler.endpoint = None # endpoint comes from dhcp request self.assertTrue(handler.skip_cache) with patch("os.path.exists", return_value=True): with patch(open_patch(), open_file_mock): handler.run() self.assertTrue(patch_dhcp_cache.call_count == 1) self.assertTrue(patch_dhcp_send.call_count == 1)
def test_enable_firewall_no_wait(self, mock_run, mock_output, mock_uid): osutil._enable_firewall = True util = osutil.DefaultOSUtil() dst = '1.2.3.4' uid = 42 version = "iptables v{0}".format(osutil.IPTABLES_LOCKING_VERSION-1) wait = "" mock_run.side_effect = [1, 0, 0] mock_output.side_effect = [(0, version), (0, "Output")] self.assertTrue(util.enable_firewall(dst_ip=dst, uid=uid)) mock_run.assert_has_calls([ call(osutil.FIREWALL_DROP.format(wait, "C", dst), chk_err=False), call(osutil.FIREWALL_ACCEPT.format(wait, "A", dst, uid)), call(osutil.FIREWALL_DROP.format(wait, "A", dst)) ]) mock_output.assert_has_calls([ call(osutil.IPTABLES_VERSION), call(osutil.FIREWALL_LIST.format(wait)) ]) self.assertTrue(osutil._enable_firewall)
def test_enable_firewall_checks_for_invalid_iptables_options( self, mock_run, mock_output): osutil._enable_firewall = True util = osutil.DefaultOSUtil() dst = '1.2.3.4' version = "iptables v{0}".format(osutil.IPTABLES_LOCKING_VERSION) wait = "-w" # iptables uses the following exit codes # 0 - correct function # 1 - other errors # 2 - errors which appear to be caused by invalid or abused command # line parameters mock_run.side_effect = [2] mock_output.return_value = (0, version) self.assertFalse(util.enable_firewall(dst_ip='1.2.3.4', uid=42)) self.assertFalse(osutil._enable_firewall) mock_run.assert_has_calls([ call(osutil.FIREWALL_DROP.format(wait, "C", dst), chk_err=False), ]) mock_output.assert_has_calls([call(osutil.IPTABLES_VERSION)])
def test_conf_sudoer(self, mock_dir): tmp_dir = tempfile.mkdtemp() mock_dir.return_value = tmp_dir util = osutil.DefaultOSUtil() # Assert the sudoer line is added if missing util.conf_sudoer("FooBar") waagent_sudoers = os.path.join(tmp_dir, 'waagent') self.assertTrue(os.path.isfile(waagent_sudoers)) count = -1 with open(waagent_sudoers, 'r') as f: count = len(f.readlines()) self.assertEqual(1, count) # Assert the line does not get added a second time util.conf_sudoer("FooBar") count = -1 with open(waagent_sudoers, 'r') as f: count = len(f.readlines()) print("WRITING TO {0}".format(waagent_sudoers)) self.assertEqual(1, count)
def test_isloopback(self): self.assertTrue(osutil.DefaultOSUtil().is_loopback(b'lo')) self.assertFalse(osutil.DefaultOSUtil().is_loopback(b'eth0'))
def test_get_instance_id_unexpected(self, mock_shell, mock_isfile): # pylint: disable=unused-argument util = osutil.DefaultOSUtil() self.assertEqual("", util.get_instance_id())
def test_get_dhcp_pid_should_return_a_list_of_pids(self): osutil_get_dhcp_pid_should_return_a_list_of_pids(self, osutil.DefaultOSUtil())
def test_get_firewall_dropped_packets_returns_zero_if_firewall_disabled(self): osutil._enable_firewall = False util = osutil.DefaultOSUtil() self.assertEqual(0, util.get_firewall_dropped_packets("not used"))
def test_get_dvd_device_success(self): with patch.object(os, 'listdir', return_value=['cpu', 'cdrom0']): osutil.DefaultOSUtil().get_dvd_device()
def test_get_instance_id_unexpected(self, mock_shell, mock_isfile): util = osutil.DefaultOSUtil() self.assertEqual("", util.get_instance_id())
def test_get_instance_id_from_dmidecode(self, mock_shell, mock_isfile): util = osutil.DefaultOSUtil() self.assertEqual( util.get_instance_id(), "B9F3C233-9913-9F42-8EB3-BA656DF32502")
def test_get_instance_id_malformed_from_file(self, mock_read, mock_isfile): util = osutil.DefaultOSUtil() self.assertEqual( "Value", util.get_instance_id())
def test_get_instance_id_empty_from_file(self, mock_read, mock_isfile): util = osutil.DefaultOSUtil() self.assertEqual( "", util.get_instance_id())
def test_device_for_ide_port_none( self, os_path_exists, # pylint: disable=unused-argument os_listdir): # pylint: disable=unused-argument dev = osutil.DefaultOSUtil().device_for_ide_port(1) self.assertIsNone(dev, 'None should be returned if no resource disk found')
def test_dhcp_lease_default(self): self.assertTrue(osutil.DefaultOSUtil().get_dhcp_lease_endpoint() is None)
def test_empty_proc_net_route(self): routing_table = "" mo = mock.mock_open(read_data=routing_table) with patch(open_patch(), mo): self.assertEqual(len(osutil.DefaultOSUtil().read_route_table()), 0)
def test_isloopback(self): for iface in osutil.DefaultOSUtil()._get_all_interfaces(): if iface == 'lo': self.assertTrue(osutil.DefaultOSUtil().is_loopback(iface)) else: self.assertFalse(osutil.DefaultOSUtil().is_loopback(iface))