def check_and_mount_smb():
    """1. Checks /proc/mounts to see if <cagent_constants.smbMountPath> is mounted
       2. If not, mount it
       3. Check if the entry is present in /etc/fstab
       4. If not, add it
    """
    logger.debug(" Check and Mount SMB")
    config = Configs().get_yaml_node_as_tuple("agents", "generic_cagent_unix")
    ssh_session = SshUtil(config)

    config = Configs().get_yaml_node_as_tuple("agents", "cagent_constants")
    testConfig = Configs().get_yaml_node_as_tuple("agents",
                                                  "cagent_test_constants")

    retval, output, stderr = ssh_session.send_command(
        f"cat /proc/mounts | grep {testConfig.localMountPath}")
    assert len(stderr) == 0, f'Failure in Checking Mounted Drives: {stderr}'
    mountedFlag = re.findall(f"{testConfig.localMountPath}", output)
    if len(mountedFlag) == 0:
        retval, _, stderr = ssh_session.send_command(
            f"sudo mkdir -p {testConfig.localMountPath}")
        assert retval == 0 and len(
            stderr) == 0, f'Unable to Create local Mount Directory: {stderr}'

        retval, output, stderr = ssh_session.send_command(
            f"sudo mount -t cifs -o username={config.buildSystemFileAccessUserName},password={config.buildSystemFileAccessPassword} {testConfig.buildMountPath} {testConfig.localMountPath}"
        )

        assert retval == 0 and len(
            stderr) == 0, f'Mounting Build Machine Path Failed: {stderr}'

    retval, output, stderr = ssh_session.send_command(
        f"cat /etc/fstab | grep {testConfig.localMountPath}")
    assert len(stderr) == 0, f'Failure in Checking /etc/fstab: {stderr}'

    if len(re.findall(f"{testConfig.localMountPath}", output)) == 0:

        # Create Credentails file
        retval, output, stderr = ssh_session.send_command(
            f"echo -e 'username={config.buildSystemFileAccessUserName}\npassword={config.buildSystemFileAccessPassword}' > /root/.smbcredentials"
        )
        assert len(stderr) == 0, f'Failure in creating smbCredentials file'

        retval, output, stderr = ssh_session.send_command(
            f" chmod 600 /root/.smbcredentials")
        assert len(
            stderr) == 0, f'Failure in setting smbCrednetials file permissions'

        command = 'echo "' + testConfig.buildMountPath + " " + testConfig.localMountPath + \
            ' cifs _netdev,credentials=/root/.smbcredentials,dir_mode=0755,file_mode=0755,uid=0,gid=0 0 0" | sudo tee -a /etc/fstab'

        retval, output, stderr = ssh_session.send_command(f"{command}")
        assert len(stderr) == 0, f'Failure in adding an entry to /etc/fstab'
    yield True
def test_check_ui_on_subnet_mapping_page(core_session, cleanup_system_subnet_mapping):
    """
    TC:C2197 Check UI on Subnet Mappings page.
        1) Login Admin Portal as cloud admin
        2) Add System subnet mapping by calling API add_system_subnet_mapping
        3) Checking through UI for assertion

    :param core_session: Authenticated Centrify session.
    :param core_admin_ui: Authenticated Centrify browser session.
    :param: cleanup_system_subnet_mapping: cleanup for created system subnet.
    """
    subnet = Configs.get_environment_node('update_discovery_profile',
                                          'automation_main')['port_scan_scope']['subnet_mask']
    subnet_list = cleanup_system_subnet_mapping

    # Adding System Subnet Mapping.
    result, success, message = ResourceManager.add_system_subnet_mapping(core_session, subnet, chooseConnector="on")
    system_subnet_id = result['ID']
    assert success, f'Failed to add System subnet mapping with API response: {message}'
    subnet_list.append(system_subnet_id)
    logger.info(f"System subnet mapping added successfully, {system_subnet_id}")

    # Checking on ui for assertion
    query = "select * from ProxyGroup"
    results = RedrockController.get_result_rows(RedrockController.redrock_query(core_session, query))
    assert results[0]['Subnet'] == subnet, \
        f'Failed to see the detail of System Subnet Mapping with API response: {message}'
Ejemplo n.º 3
0
def test_checkout_password_for_unmanaged_account_from_system_page(
        core_session, setup_pas_system_for_unix, core_admin_ui):
    """
    TC: C2506 - Checkout password for unmanaged account from system page
    :param setup_pas_system_for_unix: Adds and yield UUID of a Unix system and account associated to it.
    :param core_admin_ui: Authenticated Centrify browser session with cloud admin credentials from core.yaml
    """
    added_system_id, account_id, sys_info = setup_pas_system_for_unix
    resource_data = Configs.get_environment_node('resources_data',
                                                 'automation_main')
    acc_password = resource_data['Unix_infrastructure_data']['password']
    ui = core_admin_ui
    ui.navigate('Resources', 'Systems')
    ui.search(sys_info[0])
    ui.click_row(sys_info[0])
    ui.right_click_action(
        Selector(By.XPATH, f'//tr[@test-id = "{account_id}"]'), 'Checkout')
    ui._waitUntilSettled()
    logger.info(
        f'checking out password for "test_user" account from Unix system {sys_info[0]}'
    )
    logger.info(
        f"Password checkout successful for account: {account_id} from 'Systems' page."
    )
    ui.switch_context(Modal())
    ui.button('Show Password')
    logger.info(
        "Successfully clicked on 'Show password' button to reveal the password."
    )
    password_field = ui.check_exists(
        ('XPATH', '//div[@itemid="passwordPlainText"]'))
    assert password_field, "Password field not available even after clicking 'Show password' button"
    logger.info(f"Password is visible after clicking 'Show password' button.")
def generic_cagent_enroll_root():
    """Prepare SSH session for cagent enrollment test.

    :return: Returns SshUtil() object to be used to run commands."""
    config = Configs().get_yaml_node_as_tuple("agents", "generic_cagent_unix")
    sshutil = SshUtil(config)
    yield sshutil
    logger.info("unenrolling the cagent")
    sshutil.send_command("cunenroll -md")
def generic_cagent_enroll_win_admin():
    """
    Provide a WinRM connection to the Windows server as Administrator
    """
    sys_config = Configs().get_yaml_node_as_tuple("agents",
                                                  "generic_cagent_win")

    winrm_config = collections.namedtuple('winrm_config',
                                          ('hostname username password'))
    config = winrm_config(hostname=sys_config.hostname,
                          username=sys_config.admin_username,
                          password=sys_config.admin_password)
    logger.debug(f"winrm instantiated, Hostname {sys_config.hostname}")
    winrm = WinRM(config)
    yield winrm

    winrm.send_command("cunenroll -md")
    winrm.close()
def test_add_unmanaged_account_using_proxy_account(core_session, cleanup_accounts, setup_pas_system_for_unix,
                                                   core_admin_ui):
    """
    TC- C2500: Add unmanaged account using proxy account
    :param core_session: Authenticated Centrify session.
    :param setup_pas_system_for_unix: Adds and yields GUID for a unix system and account associated with it.
    :param core_admin_ui: Authenticated Centrify browser session.
    """
    added_system_id, account_id, sys_info = setup_pas_system_for_unix
    test_data = Configs.get_environment_node('resources_data', 'automation_main')
    unix_data = test_data['Unix_infrastructure_data']
    user_name = f"{unix_data['account_name']}{guid()}"
    ui = core_admin_ui
    accounts_list = cleanup_accounts[0]

    result, success = ResourceManager.update_system(core_session, added_system_id, sys_info[0], sys_info[1],
                                                    sys_info[2], proxyuser=unix_data['proxy_user'],
                                                    proxyuserpassword=unix_data['proxy_password'],
                                                    proxyuserismanaged=False)
    assert success, f"Unable to add a managed proxy user for {sys_info[0]}. API response result: {result}"
    logger.info(f"Proxy account {unix_data['proxy_user']} added to Unix system: {sys_info[0]}")

    ui.navigate('Resources', 'Systems')
    ui.search(sys_info[0])
    ui.click_row(sys_info[0])
    ui.launch_modal("Add", "Add Account")
    ui.switch_context(Modal())
    ui.input('User', user_name)
    ui.input('Password', unix_data['password'])
    ui.check('UseWheel')
    ui.button('Add')
    ui._waitUntilSettled()
    ui.remove_context()
    assert ui.check_exists(('XPATH', f'//div[text()="{user_name}"]')), \
        f"Account {user_name} couldn't be added to system: {sys_info[0]} using proxy account: {unix_data['proxy_user']}"
    logger.info(f"Account {user_name} added to system: {sys_info[0]} using proxy account: {unix_data['proxy_user']}.")

    # Teardown for the added account
    added_account_id = RedrockController.get_account_id_by_username(core_session, user_name)
    accounts_list.append(added_account_id)
Ejemplo n.º 7
0
def test_checkout_password_for_unmanaged_account_from_account_page(
        setup_pas_system_for_unix, core_session):
    """
    TC: C2506 - Checkout password for unmanaged account from account page
    :param setup_pas_system_for_unix: Adds and yield UUID of a Unix system and account associated to it.
    :param core_admin_ui: Authenticated Centrify browser session with cloud admin credentials from core.yaml
    """

    added_system_id, account_id, sys_info = setup_pas_system_for_unix

    automation_data = Configs.get_environment_node('resources_data',
                                                   'automation_main')
    password = automation_data['Unix_infrastructure_data']['password']

    result, success = ResourceManager.check_out_password(
        core_session, 1, account_id, "Copy the password")
    assert success, f"Password checkout failed with API response result: {result}"
    logger.info(
        f"Password successfully checked out for account: '{sys_info[4]}'")

    assert result[
        'Password'] == password, "Clipboard contents didn't change after clicking 'Copy Password' button."
    logger.info(
        "Successfully clicked on 'Copy Password' button to copy the password.")
Ejemplo n.º 8
0
from Utils.config_loader import Configs

PATHS = Configs.get_test_node("da_installation", "paths")
DZWIN_PATHS = Configs.get_test_node("dz_win_mfa", "paths")

remote_da_root_path = PATHS['remote_da_root_path']
repo_da_root_path = PATHS['repo_da_root_path']

remote_apps_root_path = PATHS['remote_apps_root_path']
repo_apps_root_path = PATHS['repo_apps_root_path']

remote_framework_path = PATHS['remote_framework_path']
remote_da_testscripts_dir = r'.\Tests\CSS\DA\DABAT'
remote_dz_testscripts_dir = r'.\Tests\CSS\DZWin'

remote_testees_root_dir = DZWIN_PATHS['remote_testees_root_dir']
remote_testagent_root_dir = DZWIN_PATHS['remote_testagent_root_dir']
remote_testframework_root_dir = DZWIN_PATHS['remote_testframework_root_dir']
remote_testscripts_root_dir = DZWIN_PATHS['remote_testscripts_root_dir']

remote_da_administrator_console_path = remote_da_root_path + r'\DirectAudit\Console\Centrify DirectAudit Administrator Console64.msi'
repo_da_administrator_console_path = repo_da_root_path + r'\DirectAudit\Console\Centrify DirectAudit Administrator Console64.msi'
da_administrator_startup_path = r'C:\Program Files\Centrify\Audit\AuditManager\Centrify Audit Manager.msc'

remote_da_auditor_path = remote_da_root_path + r'\DirectAudit\Console\Centrify DirectAudit Auditor Console64.msi'
repo_da_auditor_path = repo_da_root_path + r'\DirectAudit\Console\Centrify DirectAudit Auditor Console64.msi'
da_auditor_startup_path = r'C:\Program Files\Centrify\Audit\AuditAnalyzer\Centrify Audit Analyzer.msc'

remote_audit_manager_path = remote_da_root_path + r'\DirectAudit\Audit Management Server\Centrify DirectAudit Audit Management Server64.msi'
repo_audit_manager_path = repo_da_root_path + r'\DirectAudit\Audit Management Server\Centrify DirectAudit Audit Management Server64.msi'
audit_manager_startup_path = r'C:\Program Files\Centrify\Audit\AuditManagementServer\AuditManagementServer.configure.exe'
from time import sleep

from appium import webdriver
from appium.webdriver import WebElement
from appium.webdriver.webdriver import WebDriver
from selenium.common.exceptions import *
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
from Utils.config_loader import Configs

from Fixtures.CSS.misc import *
from Shared.css_utils import *

logger = logging.getLogger('test')

settings = Configs.get_test_node("da_installation", "settings")
small_retry = settings['small_retry']

###### Test helper functions ######


def rdp_session(user_name, password, public_ip):
    logger.info("Launch RDP session for user %s" % user_name)

    cmdline = 'cmdkey /generic:"%s" /user:"******" /pass:"******"' % \
              (public_ip, user_name, password)
    # os.system(cmdline)

    os.system(cmdline + ' & start mstsc /f /v:%s' % public_ip)
    logger.info("Launch RDP session done")
Ejemplo n.º 10
0
def test_connector_setting(core_session, pas_windows_setup, users_and_roles,
                           core_pas_admin_ui):
    """
    TC:C2170 Check connectors setting.
    :param core_session: Returns a API session.
    :param pas_windows_setup: Returns a fixture.
    :param users_and_roles: Gets user and role on demand.
    :param core_pas_admin_ui: Returns browser session.
    """

    # Creating a system and account.
    system_id, account_id, sys_info, connector_id, user_password = pas_windows_setup(
    )

    # Cloud user session with "Privileged Access Service Administrator".
    cloud_user_session = users_and_roles.get_session_for_user(
        'Privileged Access Service Administrator')
    user_name = cloud_user_session.auth_details['User']
    user_id = cloud_user_session.auth_details['UserId']

    # Assigning "Edit" permission for system to limited user.
    assign_system_perm_res, assign_system_perm_success = ResourceManager.assign_system_permissions(
        core_session, "Edit", user_name, user_id, 'User', system_id)

    assert assign_system_perm_success, f"Failed to assign 'Edit' permissions to user for the system: API Response " \
                                       f"result: {assign_system_perm_res}. "
    logger.info(
        f"Successfully assign 'Edit' permissions to user for the system: {assign_system_perm_res}."
    )

    # Getting the connectors Details.
    connector_details = Configs.get_environment_node('connector_data',
                                                     'automation_main')
    connector_name = connector_details['connector']
    list_connectors_id = []
    connectors_details = RedrockController.get_all_proxy(cloud_user_session)
    for connector_detail in connectors_details:
        if connector_detail['Name'] == connector_name:
            list_connectors_id.append(connector_detail['ID'])

    # Choosing the connector for the system.
    update_system_result, update_system_success = ResourceManager.update_system(
        cloud_user_session,
        system_id=system_id,
        name=sys_info[0],
        fqdn=sys_info[1],
        computerclass=sys_info[2],
        proxycollectionlist=connector_id,
        chooseConnector="on",
        filterConnectorCombo="all",
    )
    assert update_system_success, f'Failed to save the connector for the system:' \
                                  f'API response result:{update_system_result}. '
    logger.info(
        f'Successfully save the connector {update_system_result} for the system.'
    )

    # UI Launch
    ui = core_pas_admin_ui
    ui.navigate('Resources', 'Systems')
    ui.search(sys_info[0])
    ui.click_row(GridRowByGuid(system_id))
    ui.tab('Connectors', check_rendered_tab=False)
    assert ui.check_exists(GridRowCheckbox(connector_name, checked=True)), 'Expect the find connector checked but ' \
                                                                           'failed to find it. '
    logger.info(
        f'Successfully found the correct connector setting:{connector_name}.')
Ejemplo n.º 11
0
class AppiumGui(unittest.TestCase):
    system_data = Configs.get_environment_node('gui', 'automation_main')
    system_data_values = system_data['Windows_infrastructure_data']
    remote_ip = system_data_values['remote_ip']
    script_file = system_data_values['script_file_name']
    remote_username = system_data_values['remote_username']
    remote_password = system_data_values['remote_password']
    local_server = system_data_values['local_appium_server']
    remote_server = system_data_values['remote_appium_server']
    remote_installation_path = system_data_values['remote_installation_path']
    remote_setup_path = system_data_values['remote_setup_directory']
    remote_headless_script = system_data_values['remote_headless_script']

    def remoteDesktopConnection(self, class_name):
        desired_caps = {}
        desired_caps["app"] = "Root"
        self.DesktopSession = webdriver.Remote(
            command_executor=self.local_server,
            desired_capabilities=desired_caps)
        CortanaWindow = self.DesktopSession.find_element_by_class_name(
            class_name)
        CortanaTopLevelWindowHandle = CortanaWindow.get_attribute(
            "NativeWindowHandle")
        CortanaTopLevelWindowHandle1 = hex(int(CortanaTopLevelWindowHandle))
        desired_caps1 = {}
        desired_caps1["appTopLevelWindow"] = CortanaTopLevelWindowHandle1
        self.driver = webdriver.Remote(command_executor=self.local_server,
                                       desired_capabilities=desired_caps1)
        return self.driver

    def tearDown(self):
        self.driver.quit()

    def close_rdp_session(self):
        os.system("TASKKILL /F /IM mstsc.exe")

    def open_rdp_session(self):
        os.startfile(r"C:\Windows\system32\mstsc.exe")
        time.sleep(5)

    def remove_remote_file(self):
        powershell.remote_execute_using_ip_and_creds(
            self.remote_ip, self.remote_username, self.remote_password,
            f"Remove-Item {self.remote_installation_path}{self.script_file}")

    def run_remote_headless_installation(self):
        powershell.remote_execute_using_ip_and_creds(
            self.remote_ip, self.remote_username, self.remote_password,
            f"python {self.remote_headless_script}")

    def get_remote_installation_folder(
            self,
            password=remote_password,
            ad_user=remote_username,
            splitter=";",
            script_block1=f"Get-ChildItem {remote_setup_path}",
            computer_name=remote_ip):
        remote_command1 = f'$password = ConvertTo-SecureString “{password}” -AsPlainText -Force{splitter} ' \
                          f'$Cred = New-Object System.Management.Automation.PSCredential ("{ad_user}", $password){splitter}' \
                          f'Invoke-Command -ComputerName ' + computer_name + ' -ScriptBlock{' + script_block1 + '} -Credential $Cred;'
        command1 = self.build_powershell_command([remote_command1])
        proc1 = Popen(command1, shell=True, stdout=PIPE, stderr=PIPE)
        _stdout_buff = proc1.communicate()
        return _stdout_buff

    def build_powershell_command(self, variables):
        """
        Takes a list of variables and concatentaes them into a command line for powershell
        :param list variables: ['list', 'of', 'strings']
        :return: Popen list of commands for powershell
        """
        command = []
        command.extend(['powershell.exe'])
        command.extend([''])
        command.extend(variables)
        return command

    def copy_remote_sys_file(
        self,
        computer_name=remote_ip,
        ad_user=remote_username,
        password=remote_password,
        splitter=";",
        cp_file="",
        d_path=remote_installation_path,
    ):
        remote_command = f'$password = ConvertTo-SecureString “{password}” -AsPlainText -Force{splitter} ' \
                         f'$Cred = New-Object System.Management.Automation.PSCredential ("{ad_user}", $password){splitter}' \
                         f'$Session = New-PSSession -ComputerName {computer_name} -Credential $Cred{splitter}' \
                         f'Copy-Item "{cp_file}" -Destination "{d_path}" -ToSession $Session{splitter}' \
                         f'Remove-PSSession -Session $Session{splitter}'
        command = self.build_powershell_command([remote_command])
        Popen(command, shell=True, stdout=PIPE, stderr=PIPE)

    def remote_ipconfig(self, file):
        desired_caps1 = {}
        desired_caps1["app"] = f'{self.remote_installation_path}{file}'
        self.driver = webdriver.Remote(command_executor=self.remote_server,
                                       desired_capabilities=desired_caps1)
        return self.driver

    def test_remote_rdp_script(self):
        self.open_rdp_session()
        screen = self.remoteDesktopConnection(class_name="#32770")
        screen.find_element_by_class_name("ComboBox").send_keys(self.remote_ip)
        screen.find_element_by_name("Connect").click()
        time.sleep(3)
        screen = self.remoteDesktopConnection("Credential Dialog Xaml Host")
        time.sleep(1)
        screen.find_element_by_class_name("PasswordBox").send_keys(
            self.remote_password)
        screen.find_element_by_name("OK").click()
        time.sleep(3)
        screen = self.remoteDesktopConnection("TscShellContainerClass")
        assert screen is not None, "Unable to get the Remote session."
        path = get_asset_path(self.script_file)
        self.copy_remote_sys_file(cp_file=path)
        time.sleep(4)
        screen = self.remote_ipconfig(self.script_file)
        assert screen is not None, "Unable to get the Remote session."
        time.sleep(30)
        self.remove_remote_file()
        installation_folder = self.get_remote_installation_folder()
        if "Centrify.DirectAudit.AuditDatabase" in installation_folder:
            assert True, "The installation is not successful"
        self.close_rdp_session()

    def test_remote_headless_installation(self):
        path = get_asset_path(self.remote_headless_script)
        self.copy_remote_sys_file(cp_file=path)
        time.sleep(4)
        self.run_remote_headless_installation()
        time.sleep(30)
        self.remove_remote_file()
        installation_folder = self.get_remote_installation_folder()
        if "Centrify.DirectAudit.AuditDatabase" in installation_folder:
            assert True, "The installation is not successful"
def agent_enrolled_unix_system_with_users(core_tenant, core_session_global,
                                          agent_enrolled_unix_system,
                                          users_and_roles, cleanup_accounts,
                                          create_unix_users, proxy_start_stop,
                                          detect_proxy):

    config = Configs().get_yaml_node_as_tuple("agents", "generic_cagent_unix")
    accounts_list = cleanup_accounts[0]
    proxycontrol = proxy_start_stop

    logger.info("adding users on the enrolled system")
    system_id = agent_enrolled_unix_system["ResourceId"]
    ssh_session = agent_enrolled_unix_system["Session"]
    adminuser = {"Name": config.username, "Password": config.password}

    # add users on target system
    accountusers = create_unix_users(ssh_session, "agent_", 2)
    logger.info("Users created " + str(len(accountusers)))
    for i, val in enumerate(accountusers):
        logger.info(
            str(i) + ", Name: " + val["Name"] + "Password:"******"Password"])

    right_data = ("Privileged Access Service Power User",
                  "role_Privileged Access Service Power User")

    requester_session = users_and_roles.get_session_for_user(right_data[0])
    role_info = users_and_roles.get_role(right_data[0])

    permission_string = 'Grant,View,Edit,Delete,ManageSession,AgentAuth,RequestZoneRole,AddAccount,UnlockAccount'
    result, success = ResourceManager.assign_system_permissions(
        core_session_global, permission_string, role_info['Name'],
        role_info['ID'], "Role", system_id)
    assert success, "Did not set system permissions " + result

    # Step 3 Create Accounts for testing
    logger.info("Adding root account")
    admin_account_id, add_account_success = ResourceManager.add_account(
        requester_session,
        adminuser['Name'],
        adminuser["Password"],
        system_id,
        ismanaged=False)
    assert add_account_success, "Failed to create Account user: root"
    logger.info(f"Added root Account.  Id {admin_account_id}")
    accounts_list.append(admin_account_id)

    logger.info("Adding user for reconciliation")
    new_account_id, add_account_success = ResourceManager.add_account(
        requester_session,
        accountusers[0]['Name'],
        accountusers[0]['Password'],
        system_id,
        ismanaged=True)
    assert add_account_success, "Failed to create manged Account user: "******", Verify CC  or agent settings and status"
    logger.info(f"Added Account for testing.  Id {new_account_id}")
    accounts_list.append(new_account_id)

    permission_string = "Owner,View,Manage,Delete,Login,Naked,UpdatePassword,RotatePassword,FileTransfer,UserPortalLogin"
    result, success = ResourceManager.assign_account_permissions(
        core_session_global, permission_string, role_info['Name'],
        role_info['ID'], "Role", new_account_id)
    assert success, "Did not set account permissions " + result

    # Get computer details for update
    result = RedrockController.get_system(requester_session, system_id)
    system = result[0]["Row"]

    # wait for managed password change event
    filter = [['AccountName', accountusers[0]['Name']]]
    RedrockController.wait_for_event_by_type_filter(
        requester_session,
        "Cloud.Server.LocalAccount.PasswordChange",
        filter=filter,
        maximum_wait_second=120)  # wait for 20 seonds
    accounts = [{
        "Name": adminuser['Name'],
        "Password": adminuser["Password"],
        "Id": admin_account_id
    }, {
        "Name": accountusers[0]["Name"],
        "Password": accountusers[0]["Password"],
        "Id": new_account_id
    }]

    proxy = start_proxy_with_machinename(requester_session, proxycontrol,
                                         config.proxy_name)
    assert proxy != None, (
        f'Failed to find the connector {config.proxy_name}, Setup the  connector properly.'
    )

    #  Set Admin Account and enable local account maintenance
    result, success = ResourceManager.update_system(
        requester_session,
        system_id,
        system["Name"],
        system["FQDN"],
        'Unix',
        proxycollectionlist=proxy,
        adminaccountid=admin_account_id,
        allowautomaticlocalaccountmaintenance=True)
    assert success, (f'Failed to set administrative account {result}')

    # return acount ids, computer,
    yield [{
        "ResourceId": system_id,
        "ProxyId": proxy,
        "ResourceName": system["Name"],
        "Accounts": accounts,
        "Session": ssh_session
    }]

    result, success, message = ResourceManager.set_system_administrative_account(
        requester_session, system_id)
    assert success, f'Failed to remove administrative account on {message}'
def test_login_stored_account(core_session, setup_pas_system_for_unix,
                              set_cleaner, core_admin_ui):
    """
    Test Case ID: C2087
    Test Case Description: Login as stored account after proxy account enabled
    :param core_session: Returns API session
    :param setup_pas_system_for_unix: Creates Unix System and Account
    :param set_cleaner: Delete Set
    :param core_admin_ui: Authenticates Centrify UI session
    """
    system_id, account_id, sys_info = setup_pas_system_for_unix
    system_name = sys_info[0]
    FQDN = sys_info[1]
    computer_class = sys_info[2]
    account_name = sys_info[4]
    systems_data = Configs.get_environment_node('resources_data',
                                                'automation_main')
    expected_system_class = systems_data['Unix_infrastructure_data']
    result, success = ResourceManager.update_system(
        core_session,
        system_id,
        system_name,
        FQDN,
        computer_class,
        proxyuser=expected_system_class['proxy_user'],
        proxyuserpassword=expected_system_class['proxy_password'],
        proxyuserismanaged=False,
        allowremote=True)
    assert success, 'Failed to update system'
    logger.info(f'System successfully updated with result: {result}')
    ui = core_admin_ui
    name_of_set = f'Set{guid()}'
    ui.navigate('Resources', 'Systems')
    ui.launch_add('Add', 'Create Set')
    ui.input('Name', name_of_set)
    ui.tab('Members')
    ui.launch_modal('Add', 'Add System')
    ui.search(system_name)
    ui.check_row(system_name)
    ui.close_modal('Add')
    ui.save()
    id_of_set = SetsManager.get_collection_id(core_session, name_of_set,
                                              'Server')
    assert id_of_set, 'Set creation Failed'
    logger.info(f"Set: '{name_of_set}' created successfully")
    set_cleaner.append(id_of_set)

    # Login into Stored Account
    ui._waitUntilSettled()
    ui.switch_context(ActiveMainContentArea())
    ui.right_click_action(Div(system_name), 'Select/Request Account')
    ui.switch_context(Modal(system_name + ' Login'))
    ui.expect_disappear(LoadingMask(),
                        'Expected to find account but it did not', 30)
    ui.search(account_name)
    ui.expect(GridCell(account_name),
              'Expected to find account name but it did not.').try_click()
    ui.close_modal('Select')
    ui.switch_to_pop_up_window()
    ui.expect_disappear(LoadingMask(),
                        'Expected to login in account but it did not', 30)
    logger.info(f'Successfully logged in Account:{account_name}.')
    ui.switch_to_main_window()
def test_update_un_managed_using_managed_proxy_account_check_password_history(
        core_session, pas_windows_setup, test_proxy, pas_config):
    """
    TC: C2550 Update un managed account with using proxy account.
    :param core_session: Returns a API session.
    :param pas_windows_setup: Fixture for adding a system and an account associated with it.
    :param pas_config: fixture reading data from resource_data.yaml file.

    """
    # Creating a system with un managed account using un managed proxy account.
    system_id, account_id, sys_info, connector_id, user_password = pas_windows_setup(
    )

    # Updating the proxy user password.
    payload_data = pas_config['Windows_infrastructure_data']
    update_proxy_result, update_proxy_success = ResourceManager.update_system(
        core_session,
        system_id,
        sys_info[0],
        sys_info[1],
        sys_info[2],
        proxyuser=payload_data['proxy_username'],
        proxyuserpassword=payload_data['proxy_password'],
        proxyuserismanaged=False)
    assert update_proxy_success, f"Failed to update proxy user password:API response result:{update_proxy_result}."
    logger.info(
        f"Successfully able to update the proxy user password without error {update_proxy_result}."
    )

    # Updating the un managed account with invalid password.
    invalid_data = Configs.get_test_node('invalid_resources_data',
                                         'automation_main')
    invalid_payload_data = invalid_data['System_infrastructure_data']
    invalid_acc_password = invalid_payload_data['invalid_password']
    result_update_account, result_update_success = ResourceManager.update_password(
        core_session, account_id, invalid_acc_password)

    assert result_update_success, f"Failed to update account with invalid password:"******"API response result:{result_update_account}"
    logger.info(f"Successfully able to update the un managed "
                f"account with invalid password:{result_update_account}.")

    # Getting the Account information and validating the status.
    status = 'BadCredentials'
    get_account_info, get_account_status = ResourceManager.get_accounts_from_resource(
        core_session, system_id)
    assert get_account_info[0][
        'Healthy'] == status, f'Status does not change to Unknown: {status}'
    logger.info(
        f"Successfully able to change status to Unknown {get_account_info}.")

    # Updating the un managed account with correct password.
    updated_account_correct_result, updated_account_correct_success = ResourceManager.update_password(
        core_session, account_id, payload_data['password'])
    assert updated_account_correct_result, f"Failed to update account with correct password:{payload_data['password']}"
    logger.info(
        f"Successfully able to update the un managed account with correct password: {updated_account_correct_result}."
    )

    # Getting the system activity and validating update local account password is done or not.
    username = core_session.get_user().get_login_name()
    result_activity = ResourceManager.get_system_activity(
        core_session, system_id)
    assert f'{username} updated local account "{sys_info[4]}" password for "{sys_info[0]}"' \
           f'({sys_info[1]})' in result_activity[0]['Detail'], \
        f"fail to update local account password :{sys_info[4]} "
    logger.info(f"Successfully update un managed password : {result_activity}")
Ejemplo n.º 15
0
 def __init__(self, config=None):
     self.agent_gui = Configs().get_yaml_node_as_tuple(
         'windows_agent', 'windows_agent_config')
     self.test_config = Configs().get_yaml_node_as_tuple(
         'suvp_test_config', 'config')
     self.powershell_config = Configs().get_yaml_node_as_tuple(
         'powershell', 'powershell')
     self.powershell_app = App(self.powershell_config)
     self.agent_app = App(self.agent_gui)
     self.desktop = WinGui()
     self.rdp_app = None
     if config:
         self.hostname = config.hostname
         self.username = config.username
         self.password = config.password
         self.admin = config.admin
         self.clwmfa = config.clwmfa
         self.endpoints = config.endpoints
         self.rwpmfa = config.rwpmfa
         self.rwpnomfa = config.rwpnomfa
         self.sdwmfa = config.sdwmfa
         self.rdp_window = config.rdp_window
         self.win_version = config.windows_version
         self.defaultwintrayx = config.defaultwintrayx
         self.defaultwintrayy = config.defaultwintrayy
         self.defaultdztrayx = config.defaultdztrayx
         self.defaultdztrayy = config.defaultdztrayy
         self.newdeskdztrayy = config.newdeskdztrayy
         self.newdeskdztrayx = config.newdeskdztrayx
         self.enrolldevicex = config.enrolldevicex
         self.enrolldevicey = config.enrolldevicey
         self.startmenux = config.startmenux
         self.startmenuy = config.startmenuy
         self.powershellx = config.powershellx
         self.servicemenux = config.servicemenux
         self.servicemenuy = config.servicemenuy
         self.altdefaultwintrayx = config.altdefaultwintrayx
         self.altdefaultwintrayy = config.altdefaultwintrayy
         self.winrm = WinRM(config)
     else:
         self.hostname = None
         self.username = None
         self.password = None
         self.admin = None
         self.clwmfa = None
         self.endpoints = None
         self.rwpmfa = None
         self.rwpnomfa = None
         self.sdwmfa = None
         self.rdp_window = None
         self.win_version = None
         self.defaultwintrayx = None
         self.defaultwintrayy = None
         self.defaultdztrayx = None
         self.defaultdztrayy = None
         self.newdeskdztrayx = None
         self.newdeskdztrayy = None
         self.startmenux = None
         self.startmenuy = None
         self.powershellx = None
         self.servicemenux = None
         self.servicemenuy = None
         self.altdefaultwintrayx = None
         self.altdefaultwintrayy = None
def agent_enrolled_windows_system_with_users(
        core_session_global, agent_enrolled_windows_system, users_and_roles,
        remote_users_qty1, cleanup_accounts, pas_ad_domain,
        pas_ad_administrative_account, cleanup_lapr_systems_and_domains,
        proxy_start_stop):
    config = Configs().get_yaml_node_as_tuple("agents", "generic_cagent_win")
    accounts_list = cleanup_accounts[0]
    domains_list = cleanup_lapr_systems_and_domains[1]
    systems_list = cleanup_lapr_systems_and_domains[0]
    user = remote_users_qty1
    proxycontrol = proxy_start_stop
    accountusers = [{"Name": user[0], "Password": "******"}]

    logger.info("Users created " + str(len(accountusers)))
    for i, val in enumerate(accountusers):
        logger.info(
            str(i) + ", Name: " + val["Name"] + "Password:"******"Password"])

    logger.info("adding users on the enrolled system")
    system_id = agent_enrolled_windows_system["ResourceId"]
    winrm_session_as_admin = agent_enrolled_windows_system["Session"]
    adminuser = {
        "Name": config.admin_username,
        "Password": config.admin_password
    }

    domain_id = pas_ad_domain['ID']
    admin_id = pas_ad_administrative_account['ID']

    right_data = ("Privileged Access Service Power User",
                  "role_Privileged Access Service Power User")

    requester_session = users_and_roles.get_session_for_user(right_data[0])
    role_info = users_and_roles.get_role(right_data[0])

    domains_list.append(pas_ad_domain)
    systems_list.append(system_id)

    logger.info(
        "Setting Domain Administrator user as Administrative Account on domain."
    )
    result, success, response = ResourceManager.set_administrative_account(
        core_session_global, [pas_ad_domain['Name']],
        pas_ad_administrative_account['User'],
        pas_ad_administrative_account['ID'])

    logger.info(
        "Setting Administrative Account on domain, but with no lapr settings enabled."
    )
    result, success = ResourceManager.update_domain_accounts(
        core_session_global,
        pas_ad_domain['Name'],
        admin_id,
        domain_id,
        allowautomaticlocalaccountmaintenance=True,
        allowmanuallocalaccountunlock=True)

    permission_string = 'Grant,View,Edit,Delete,ManageSession,AgentAuth,RequestZoneRole,AddAccount,UnlockAccount'
    result, success = ResourceManager.assign_system_permissions(
        core_session_global, permission_string, role_info['Name'],
        role_info['ID'], "Role", system_id)
    assert success, f"Did not set system permissions {result}"

    # Step 3 Create Accounts for testing
    logger.info("Adding Admin account")
    admin_account_id, add_account_success = ResourceManager.add_account(
        requester_session,
        adminuser['Name'],
        adminuser["Password"],
        system_id,
        ismanaged=False)
    assert add_account_success, "Failed to create  admin user"
    logger.info(f"Added root Account.  Id {admin_account_id}")
    accounts_list.append(admin_account_id)

    logger.info("Adding user for reconciliation")
    new_account_id, add_account_success = ResourceManager.add_account(
        requester_session,
        accountusers[0]['Name'],
        accountusers[0]['Password'],
        system_id,
        ismanaged=True)
    assert add_account_success, "Failed to create manged Account user: "******", Verify CC  or agent settings and status"
    logger.info(f"Added Account for testing.  Id {new_account_id}")
    accounts_list.append(new_account_id)

    permission_string = "Owner,View,Manage,Delete,Login,Naked,UpdatePassword,RotatePassword,FileTransfer,UserPortalLogin"
    result, success = ResourceManager.assign_account_permissions(
        core_session_global, permission_string, role_info['Name'],
        role_info['ID'], "Role", new_account_id)
    assert success, "Did not set account permissions " + result

    # Get computer details for update
    result = RedrockController.get_system(requester_session, system_id)
    system = result[0]["Row"]

    # wait for managed password change event
    filter = [['AccountName', accountusers[0]['Name']]]
    RedrockController.wait_for_event_by_type_filter(
        requester_session,
        "Cloud.Server.LocalAccount.PasswordChange",
        filter=filter,
        maximum_wait_second=120)  # wait for 120 seonds
    accounts = [{
        "Name": adminuser['Name'],
        "Password": adminuser["Password"],
        "Id": admin_account_id
    }, {
        "Name": accountusers[0]["Name"],
        "Password": accountusers[0]["Password"],
        "Id": new_account_id
    }]

    #  set proxy
    proxy = start_proxy_with_machinename(requester_session, proxycontrol,
                                         config.proxy_name)
    assert proxy != None, (
        f'Failed to find the connector {config.proxy_name}, Setup the connector properly before the test'
    )

    result, success = ResourceManager.update_system(requester_session,
                                                    system_id,
                                                    system["Name"],
                                                    system["FQDN"],
                                                    'Windows',
                                                    domainid=domain_id,
                                                    proxycollectionlist=proxy)
    assert success, (f'Failed to set reconciliation settings  {result}')

    result, success = ResourceManager.update_system(
        requester_session,
        system_id,
        system["Name"],
        system["FQDN"],
        'Windows',
        proxycollectionlist=proxy,
        allowautomaticlocalaccountmaintenance=True,
        allowmanuallocalaccountunlock=True)
    assert success, (f'Failed to set reconciliation settings  {result}')

    #  update_system  reset the  proxycollectionlist setting?  Set it again.
    result, success = ResourceManager.update_system(requester_session,
                                                    system_id,
                                                    system["Name"],
                                                    system["FQDN"],
                                                    'Windows',
                                                    domainid=domain_id,
                                                    proxycollectionlist=proxy)
    assert success, (f'Failed to set reconciliation settings  {result}')

    # return acount ids, computer,
    yield [{
        "ResourceId": system_id,
        "ProxyId": proxy,
        "ResourceFQDN": system["FQDN"],
        "Accounts": accounts,
        "Session": winrm_session_as_admin
    }]

    result, success, message = ResourceManager.set_system_administrative_account(
        requester_session, system_id)
    assert success, f'Failed to remove administrative account on {message}'
class TestForWindowsAgent:
    """
       To create shared query and report for new sessions
    """
    settings = Configs.get_test_node("da_installation", "settings")
    med_retry = settings['med_retry']
    vry_small_retry = settings['vry_small_retry']
    small_retry = settings['small_retry']
    filename = "test_DAWinBAT_test_for_windows_agent.py"
    class_name = "TestForWindowsAgent"

    @pytest.mark.bhavna
    @pytest.mark.css
    @pytest.mark.da_win_bat
    def test_master_create_shared_query(self, dawin_testagent_uploaded,
                                        dawin_installed,
                                        css_testee_login_as_domain_admin):
        username = r"%s\%s" % (dawin_installed['domain_name'].split('.')[0],
                               "administrator")
        login_and_execute_cmds(username, dawin_installed['admin_password'],
                               dawin_installed['public_ip'],
                               css_testee_login_as_domain_admin, self.filename,
                               self.class_name, 'test_create_shared_query')

    @pytest.mark.bhavna
    @pytest.mark.css
    @pytest.mark.da_win_bat
    def test_master_create_report(self, css_testee_machine,
                                  css_testee_login_as_domain_admin):
        username = r"%s\%s" % (css_testee_machine['domain_name'].split('.')[0],
                               "administrator")
        login_and_execute_cmds(username, css_testee_machine['admin_password'],
                               css_testee_machine['public_ip'],
                               css_testee_login_as_domain_admin, self.filename,
                               self.class_name, 'test_create_report')

    @pytest.mark.bhavna
    @pytest.mark.css
    @pytest.mark.da_win_bat
    @pytest.mark.parametrize('admin', ['domain_admin', 'local_admin'])
    def test_master_remote_login_with_domain_and_local_admin_user(
            self, admin, css_testee_machine, css_testee_login_as_domain_admin):
        if admin == 'domain_admin':
            logger.info("--- Case C1238811")
            username = r"%s\%s" % (css_testee_machine['domain_name'],
                                   "administrator")
            password = css_testee_machine['admin_password']
        else:
            logger.info("--- Case C1238814")
            username = r"%s\%s" % (css_testee_machine['hostname'],
                                   "administrator")
            password = css_testee_machine['local_password']
        login_and_execute_cmds(
            username, password, css_testee_machine['public_ip'],
            css_testee_login_as_domain_admin, self.filename, self.class_name,
            'test_remote_login_with_domain_and_local_admin_user')
        # To kill the WinAppDriver.exe
        rc, result, error = kill_application(css_testee_login_as_domain_admin,
                                             'WinAppDriver.exe')
        assert rc == 0, "Failed to kill Winappdriver.exe"

    @pytest.mark.bhavna
    @pytest.mark.css
    @pytest.mark.da_win_bat
    def test_master_replay_session_windows_agent(
            self, dawin_testagent_uploaded, dawin_installed,
            css_testee_login_as_domain_admin):
        username = r"%s\%s" % (dawin_installed['domain_name'].split('.')[0],
                               "administrator")
        login_and_execute_cmds(username, dawin_installed['admin_password'],
                               dawin_installed['public_ip'],
                               css_testee_login_as_domain_admin, self.filename,
                               self.class_name,
                               'test_replay_session_windows_agent')

    @pytest.mark.bhavna
    @pytest.mark.css
    @pytest.mark.da_win_bat
    def test_master_verify_audited_sessions_windows_agent(
            self, dawin_testagent_uploaded, dawin_installed,
            css_testee_login_as_domain_admin):
        username = r"%s\%s" % (dawin_installed['domain_name'].split('.')[0],
                               "administrator")
        login_and_execute_cmds(username, dawin_installed['admin_password'],
                               dawin_installed['public_ip'],
                               css_testee_login_as_domain_admin, self.filename,
                               self.class_name,
                               'test_verify_audited_sessions_windows_agent')

    @pytest.mark.bhavna
    @pytest.mark.css
    @pytest.mark.da_win_bat
    def test_master_run_ps_cmd_for_windows_session_data(
            self, dawin_testagent_uploaded, dawin_installed,
            css_testee_login_as_domain_admin):
        username = r"%s\%s" % (dawin_installed['domain_name'].split('.')[0],
                               "administrator")
        login_and_execute_cmds(
            username, dawin_installed['admin_password'],
            dawin_installed['public_ip'], css_testee_login_as_domain_admin,
            self.filename, self.class_name,
            'test_run_powershell_cmd_to_get_windows_session_data')

    @pytest.mark.bhavna
    @pytest.mark.css
    @pytest.mark.da_win_bat
    def test_master_run_ps_cmd_to_get_user_login_event(
            self, dawin_testagent_uploaded, dawin_installed,
            css_testee_login_as_domain_admin):
        username = r"%s\%s" % (dawin_installed['domain_name'].split('.')[0],
                               "administrator")
        login_and_execute_cmds(
            username, dawin_installed['admin_password'],
            dawin_installed['public_ip'], css_testee_login_as_domain_admin,
            self.filename, self.class_name,
            'test_run_powershell_cmd_to_get_user_login_event')

    # 2.1 New query and report for windows session

    def test_create_shared_query(self):
        logger.info("--- Case C1238808")

        query_name = 'Test_window_session_1'
        desktop = get_desktop()
        shared_query_itm = create_query_func(desktop, query_name, [SessionType.UNIX_session, \
                                                                   SessionType.Linux_Desktop_session])
        assert shared_query_itm is not None, f"{query_name} is not found"

    def test_create_report(self, css_testee_machine):
        logger.info("--- Case C1238809")
        report_name = "Test_report_1"
        desktop = get_desktop()
        reports_tr_itm, main_app_win, main_desktop, report_tr_itm = create_reports_func(
            ReportType.user_report, desktop)

        report_win = try_find_element(main_desktop,
                                      FindElementBy.AUTOMATION_ID,
                                      'ReportQueryCriteria', self.small_retry)

        # Select the machine box and enter full windows machine name
        try_find_element(report_win, FindElementBy.AUTOMATION_ID, 'cb_machine',
                         self.small_retry).click()
        full_machine_name = r"%s.%s" % (css_testee_machine['hostname'],
                                        css_testee_machine['domain_name'])

        try_find_element(main_desktop, FindElementBy.AUTOMATION_ID,
                         'm_machineName',
                         self.med_retry).send_keys(full_machine_name)

        # Check the Event time checkbox and select the time
        try_find_element(report_win, FindElementBy.AUTOMATION_ID,
                         'cb_eventTime', self.med_retry).click()

        time_criteria_lst_item = try_find_element(report_win,
                                                  FindElementBy.AUTOMATION_ID,
                                                  'm_timeNormalOpList',
                                                  self.small_retry)
        click_hold(main_desktop, time_criteria_lst_item)
        time_attribute_itm = try_find_element(main_desktop, FindElementBy.NAME,
                                              'Is after', self.small_retry)
        click_hold(main_desktop, time_attribute_itm)

        # Check the Event level checkbox and select the 'Succeeded' option
        try_find_element(report_win, FindElementBy.AUTOMATION_ID,
                         'cb_accessGranted', self.small_retry).click()

        # Save the query
        try_find_element(report_win, FindElementBy.AUTOMATION_ID, 'button1',
                         self.small_retry).click()

        # Enter the Report name
        try_find_element(main_desktop, FindElementBy.AUTOMATION_ID, 'textBox1',
                         self.med_retry).send_keys("Test_report_1")

        try_find_element(main_desktop, FindElementBy.AUTOMATION_ID, 'button2',
                         self.small_retry).click()

        if try_find_element(reports_tr_itm, FindElementBy.NAME, report_name, \
                            self.small_retry, ignore_if_not_found=True) is None:
            double_click(main_desktop, reports_tr_itm)

            double_click(main_desktop, report_tr_itm)

        report_itm = try_find_element(reports_tr_itm, FindElementBy.NAME,
                                      report_name, self.small_retry)

        #  Close the Audit Analyzer app
        click_hold(
            main_desktop,
            try_find_element(main_app_win, FindElementBy.NAME, 'Close',
                             self.small_retry))

        assert report_itm is not None, f"{report_name} is not found"

    def test_remote_login_with_domain_and_local_admin_user(self):
        launch_and_close_applications(
            css_win_constants.da_auditor_startup_path, 'MMCMainFrame', True)

        launch_and_close_applications(
            css_win_constants.wf_advanced_security_startup_path,
            'MMCMainFrame')

        launch_and_close_applications(
            css_win_constants.event_viewer_startup_path, 'MMCMainFrame')

        launch_and_close_applications(css_win_constants.cmd_startup_path,
                                      'ConsoleWindowClass')

        launch_and_close_applications(css_win_constants.rdp_startup_path,
                                      '#32770')

        launch_and_close_applications(
            css_win_constants.task_scheduler_startup_path, 'MMCMainFrame')

        launch_and_close_applications(css_win_constants.ie_startup_path,
                                      'IEFrame')

        launch_and_close_applications(css_win_constants.notepad_startup_path,
                                      'Notepad')

        launch_and_close_applications(
            css_win_constants.powershell_startup_path, 'ConsoleWindowClass')

    # 2.3 Verify audited data from Audit Analyzer

    def test_replay_session_windows_agent(self, css_test_machine,
                                          css_client_test_machine,
                                          get_aduser_from_yaml):
        logger.info("--- Case C1238818")
        query_name = 'Test_window_session_1'
        desktop = get_desktop()
        host_name = css_test_machine['hostname']
        domain_name = css_client_test_machine['domain_name']
        command_list = [
            'Notepad', 'Windows PowerShell', 'Task Scheduler', 'Event Viewer',
            'Remote Desktop Connection'
        ]
        users = ['Administrator']
        session_events = validate_sessions(query_name, command_list, host_name,
                                           domain_name, users,
                                           get_aduser_from_yaml, desktop,
                                           AuditType.audit_sessions.value,
                                           AuditType.shared_query.value)
        all_false_events = [
            command for command in session_events
            if session_events[command] == False
        ]
        assert len(
            all_false_events
        ) == 0, f"Failed to create session for commands: {all_false_events}"

    def test_verify_audited_sessions_windows_agent(self, css_test_machine,
                                                   css_client_test_machine,
                                                   get_aduser_from_yaml):
        logger.info("--- Case C1238819")
        query_name = 'windows sessions'
        desktop = get_desktop()
        host_name = css_test_machine['hostname']
        domain_name = css_client_test_machine['domain_name']
        command_list = [
            'Notepad', 'Windows PowerShell', 'Task Scheduler', 'Event Viewer',
            'Remote Desktop Connection'
        ]
        user = '******'
        audit_session_file, review_comment, review_status = validate_event_file(
            query_name, domain_name, user, get_aduser_from_yaml, desktop,
            host_name, True)

        # Verify session command list, review comment and status
        assert review_comment == True, "Review comment not found"
        assert review_status == True, "Review status not found"
        for command in command_list:
            substring_search = command in audit_session_file
            assert substring_search == True, f"Session for {command} command not created"

    # 2.4 Verify audited data from DA powershell

    def test_run_powershell_cmd_to_get_windows_session_data(
            self, css_testee_login_as_domain_admin):
        logger.info("--- Case C1238821")
        windows_events_file = os.path.join(os.environ["HOMEPATH"], "Desktop",
                                           "windowsevent.txt")
        rc, result, error = css_testee_login_as_domain_admin.send_command \
            (("powershell.exe -command \".\windows.ps1\""))

        windows_event_list = ["Windows Firewall", "Event Viewer", "Command Prompt", "Remote Desktop Connection", \
                              "Task Scheduler", "Untitled - Notepad", "Windows PowerShell"]

        events_file_content = file_read(windows_events_file,
                                        mode="rb").decode('utf-16-le')
        if rc == 0:
            not_found = []
            for win_event in windows_event_list:
                if win_event not in events_file_content:
                    not_found.append(win_event)

            assert len(
                not_found) == 0, f"Windows Event(s) {not_found} Not Found"

        else:
            assert False, f"Failed to execute the powershell script, {error,result}"

    def test_run_powershell_cmd_to_get_user_login_event(
            self, css_testee_machine, css_testee_login_as_domain_admin):
        logger.info("--- Case C1238822")

        domain_admin_user = "******" + "@" + css_testee_machine[
            'domain_name']
        login_event_file = os.path.join(os.environ["HOMEPATH"], "Desktop",
                                        "windowsloginevents.txt")
        rc, result, error = css_testee_login_as_domain_admin.send_command \
            (("powershell.exe -command \".\windows.ps1\""))

        login_event_list = [
            "Session auditing started", "Session auditing ended",
            domain_admin_user
        ]
        login_file_content = file_read(login_event_file,
                                       mode="rb").decode('utf-16-le')

        if rc == 0:
            not_found = []
            for login_event in login_event_list:
                if login_event not in login_file_content:
                    not_found.append(login_event)

            assert len(not_found) == 0, f"Login Event(s) {not_found} Not Found"

        else:
            assert False, f"Failed to execute the powershell script, {error, result}"
Ejemplo n.º 18
0
def test_user_type_parameter(core_session, cleanup_accounts, cleanup_reports):
    """
    TCID: C6341 Create report with User type parameter required
    :param core_session: Centrify Authentication session
    """
    user_list = cleanup_accounts[2]
    session_user = core_session.__dict__
    display_name_1 = session_user['auth_details']['DisplayName']
    user_create_data = Configs.get_test_node('platform_report_data',
                                             'automation_main')
    prefix = user_create_data['prefix']
    user_alias = core_session.auth_details['User'].split('@')[1]

    user_name_2 = prefix + guid() + "@" + user_alias
    user_props = {
        "Mail": user_create_data['user_email'],
        "Password": user_create_data['password'],
        "PasswordNeverExpire": True,
        "DisplayName": user_create_data['display_name'],
        "Username": user_name_2,
        "Name": user_name_2
    }
    success, result_user_2 = UserManager.create_user_with_args(
        core_session, user_props)
    assert success, f'Failed to create an user:{result_user_2}'
    logger.info(f'Successfully created an user:{result_user_2}')

    reports = Reports(core_session, pop_prefix_base)
    report = reports.create_report({
        "Name":
        "report_A",
        "Query":
        "select Username, LastLogin from user where DisplayName= @userNM",
        "Parameters": [{
            "Type": "User",
            "Name": "userNM",
            "Label": "Input searched username",
            "ObjectProperty": "DisplayName"
        }]
    })
    assert report, f'Failed to create the report:{report}'
    logger.info(f'Successfully Created report: {report}')

    # Actual result for all user list with display name same as session user display name.
    # and this details will compare all the user from reports page
    actual_script_1 = f'Select Username, LastLogin from user where DisplayName = "{display_name_1}"'
    actual_user_list_1 = []
    actual_result_1 = RedrockController.redrock_query(core_session,
                                                      actual_script_1)
    for user in actual_result_1:
        actual_user_list_1.append(user['Row'])

    # Expected result for all users which user name same as session user display name and will assert the list
    # of users of actual session user display name list
    expected_result_1 = RedrockController.get_report_result_list_of_user(
        core_session, "userNM", display_name_1, "Input searched username")
    expected_user_list_1 = []
    for expected_result in expected_result_1:
        expected_user_list_1.append(expected_result['Row'])
    assert expected_user_list_1 == actual_user_list_1, f'The report result list all users whose DisplayName is not ' \
                                                       f'same with selected users DisplayName:{actual_user_list_1}'
    logger.info(f'The report result list all users whose DisplayName is '
                f'same with selected users displayname:{expected_user_list_1}')

    # Actual result for all user list with display name same as another user display name.
    # and this details will compare all the user from reports page
    actual_script_2 = f'Select Username, LastLogin from user where DisplayName = "{user_create_data["display_name"]}"'
    actual_user_list_2 = []
    actual_result_2 = RedrockController.redrock_query(core_session,
                                                      actual_script_2)
    for user in actual_result_2:
        actual_user_list_2.append(user['Row'])

    # Expected result for all users which user name same as another user display name and will assert the list
    # of users of actual another user display name list
    expected_result_2 = RedrockController.get_report_result_list_of_user(
        core_session, "userNM", user_create_data['display_name'],
        "Input searched username")
    expected_user_list_2 = []
    for user in expected_result_2:
        expected_user_list_2.append(user['Row'])
    assert expected_user_list_2 == actual_user_list_2, f'The report result list all users whose DisplayName is not ' \
                                                       f'same with selected users DisplayName:{actual_user_list_2}'
    logger.info(f'The report result list all users whose DisplayName is '
                f'same with selected users displayname:{expected_user_list_2}')

    # Delete the created user
    user_list.append(result_user_2)
    found_report = reports.get_report_by_name(core_session,
                                              report['Name'] + ".report")
    cleanup_reports.append(found_report['Path'])
Ejemplo n.º 19
0
class TestforNixAgentHzoneLibAuditMode:
    """
       To create shared query and report for new sessions
    """

    settings = Configs.get_test_node("da_installation", "settings")
    med_retry = settings['med_retry']
    vry_small_retry = settings['vry_small_retry']
    small_retry = settings['small_retry']
    filename = "test_DAWinBAT_test_for_NIX_Agent_H_zone_LibAudit_mode.py"
    class_name = "TestforNixAgentHzoneLibAuditMode"

    @pytest.mark.bhavna
    @pytest.mark.css
    @pytest.mark.da_win_bat
    def test_master_create_shared_query_for_nix_session_libaudit_mode(
            self, dawin_testagent_uploaded, dawin_installed,
            css_testee_login_as_domain_admin):
        username = r"%s\%s" % (dawin_installed['domain_name'].split('.')[0],
                               "administrator")
        login_and_execute_cmds(
            username, dawin_installed['admin_password'],
            dawin_installed['public_ip'], css_testee_login_as_domain_admin,
            self.filename, self.class_name,
            'test_create_shared_query_for_nix_session_libaudit_mode')

    @pytest.mark.bhavna
    @pytest.mark.css
    @pytest.mark.da_win_bat
    def test_master_create_file_monitor_report_for_nix_session_libaudit_mode(self, css_testee_machine,\
                                                                css_testee_login_as_domain_admin):
        username = r"%s\%s" % (css_testee_machine['domain_name'].split('.')[0],
                               "administrator")
        login_and_execute_cmds(username, css_testee_machine['admin_password'], css_testee_machine['public_ip'],
                               css_testee_login_as_domain_admin, self.filename, self.class_name, \
                               'test_create_file_monitor_report_for_nix_session_libaudit_mode')

    @pytest.mark.bhavna
    @pytest.mark.css
    @pytest.mark.da_win_bat
    def test_master_create_monitored_execution_for_nix_session_libaudit_mode(self, css_testee_machine, \
                                                                             css_testee_login_as_domain_admin):
        username = r"%s\%s" % (css_testee_machine['domain_name'].split('.')[0],
                               "administrator")
        login_and_execute_cmds(username, css_testee_machine['admin_password'], css_testee_machine['public_ip'],
                               css_testee_login_as_domain_admin, self.filename, self.class_name, \
                               'test_create_monitored_execution_report_for_nix_session_libaudit_mode')

    @pytest.mark.bhavna
    @pytest.mark.css
    @pytest.mark.da_win_bat
    def test_master_create_detailed_report_for_nix_session_libaudit_mode(self, css_testee_machine, \
                                                                         css_testee_login_as_domain_admin):
        username = r"%s\%s" % (css_testee_machine['domain_name'].split('.')[0],
                               "administrator")
        login_and_execute_cmds(username, css_testee_machine['admin_password'], css_testee_machine['public_ip'],
                               css_testee_login_as_domain_admin, self.filename, self.class_name, \
                               'test_create_detailed_execution_report_for_nix_session_libaudit_mode')

    @pytest.mark.bhavna11
    @pytest.mark.css
    @pytest.mark.da_win_bat
    def test_master_audit_event_query_for_nix_session_libaudit_mode(self, css_testee_machine, \
                                                                             css_testee_login_as_domain_admin):
        username = r"%s\%s" % (css_testee_machine['domain_name'].split('.')[0],
                               "administrator")
        login_and_execute_cmds(username, css_testee_machine['admin_password'], css_testee_machine['public_ip'],
                               css_testee_login_as_domain_admin, self.filename, self.class_name, \
                               'test_create_audit_event_query_for_nix_session_libaudit_mode')

    # 3.1.1  New query and report for *NIX session

    def test_create_shared_query_for_nix_session_libaudit_mode(self):

        logger.info("--- Case C1238825")

        query_name = 'Test_Unix_session_1'
        desktop = get_desktop()
        shared_query_itm = create_query_func(desktop, query_name, [SessionType.Windows_session, \
                                                                       SessionType.Linux_Desktop_session])
        assert shared_query_itm is not None, f"{query_name} is not found"

    def test_create_file_monitor_report_for_nix_session_libaudit_mode(
            self, css_testee_machine):

        logger.info("--- Case C1238826")
        report_name = "File_Monitor_report_1"
        desktop = get_desktop()
        reports_tr_itm, main_app_win, main_desktop, report_tr_itm = create_reports_func(
            ReportType.file_report, desktop)

        file_report_win = try_find_element(main_desktop, FindElementBy.AUTOMATION_ID, 'FileMonitorReportCriteria', \
                                           self.med_retry)

        # Select the machine box and enter full windows machine name
        try_find_element(file_report_win, FindElementBy.AUTOMATION_ID,
                         'm_machineOption', self.med_retry).click()
        full_machine_name = r"%s.%s" % (css_testee_machine['hostname'],
                                        css_testee_machine['domain_name'])

        try_find_element(main_desktop, FindElementBy.AUTOMATION_ID,
                         'm_machineName',
                         self.med_retry).send_keys(full_machine_name)

        # Check the Event time checkbox and select the time
        try_find_element(file_report_win, FindElementBy.AUTOMATION_ID,
                         'm_eventTimeOption', self.med_retry).click()

        time_cbox = try_find_element(file_report_win,
                                     FindElementBy.AUTOMATION_ID,
                                     'm_timeNormalOpList', self.med_retry)
        click_hold(main_desktop, time_cbox)
        time_lst_itm = try_find_element(main_desktop, FindElementBy.NAME,
                                        'Is after', self.med_retry)
        if time_lst_itm is not None:
            click_hold(main_desktop, time_lst_itm)

        # Save the created Query

        save_query_btn = try_find_element(file_report_win,
                                          FindElementBy.AUTOMATION_ID,
                                          'm_saveQuery', self.med_retry)
        click_hold(main_desktop, save_query_btn)

        # Add report name

        try_find_element(main_desktop, FindElementBy.AUTOMATION_ID, 'textBox1',
                         self.med_retry).send_keys("File_Monitor_Report_1")

        try_find_element(main_desktop, FindElementBy.AUTOMATION_ID, 'button2',
                         self.med_retry).click()

        if try_find_element(reports_tr_itm, FindElementBy.NAME, report_name, \
                            self.small_retry, ignore_if_not_found=True) is None:
            double_click(main_desktop, reports_tr_itm)

            double_click(main_desktop, report_tr_itm)

        report_itm = try_find_element(reports_tr_itm, FindElementBy.NAME,
                                      report_name, self.med_retry)

        #  Close the Audit Analyzer app
        click_hold(
            main_desktop,
            try_find_element(main_app_win, FindElementBy.NAME, 'Close',
                             self.med_retry))

        assert report_itm is not None, "'File_Monitor_Report_1' is not found"

    def test_create_monitored_execution_report_for_nix_session_libaudit_mode(
            self, css_testee_machine):

        logger.info("--- Case C1238827")
        report_name = "Monitored_Execution_report_1"
        desktop = get_desktop()
        reports_tr_itm, main_app_win, main_desktop, report_tr_itm = create_reports_func(ReportType.monitored_report,\
                                                                                        desktop)

        monitored_report_win = try_find_element(main_desktop, FindElementBy.AUTOMATION_ID, \
                                                'MonitoredCommandReportQueryCriteria', self.med_retry)

        # Select the machine box and enter full windows machine name
        try_find_element(monitored_report_win, FindElementBy.AUTOMATION_ID,
                         'm_machineOption', self.med_retry).click()
        full_machine_name = r"%s.%s" % (css_testee_machine['hostname'],
                                        css_testee_machine['domain_name'])

        try_find_element(main_desktop, FindElementBy.AUTOMATION_ID,
                         'm_machineName',
                         self.med_retry).send_keys(full_machine_name)

        # Check the Event time checkbox and select the time
        try_find_element(monitored_report_win, FindElementBy.AUTOMATION_ID,
                         'm_eventTimeOption', self.med_retry).click()

        time_cbox = try_find_element(monitored_report_win, FindElementBy.AUTOMATION_ID, 'm_timeNormalOpList',\
                                     self.med_retry)
        click_hold(main_desktop, time_cbox)
        time_lst_itm = try_find_element(main_desktop, FindElementBy.NAME,
                                        'Is after', self.med_retry)
        if time_lst_itm is not None:
            click_hold(main_desktop, time_lst_itm)

        # Save the created Query

        save_query_btn = try_find_element(monitored_report_win, FindElementBy.AUTOMATION_ID, 'm_saveQuery',\
                                          self.med_retry)
        click_hold(main_desktop, save_query_btn)

        # Add report name

        try_find_element(
            main_desktop, FindElementBy.AUTOMATION_ID, 'textBox1',
            self.med_retry).send_keys("Monitored_Execution_report_1")

        try_find_element(main_desktop, FindElementBy.AUTOMATION_ID, 'button2',
                         self.med_retry).click()

        if try_find_element(reports_tr_itm, FindElementBy.NAME, report_name, \
                            self.small_retry, ignore_if_not_found=True) is None:
            double_click(main_desktop, reports_tr_itm)

            double_click(main_desktop, report_tr_itm)

        report_itm = try_find_element(reports_tr_itm, FindElementBy.NAME,
                                      report_name, self.med_retry)

        #  Close the Audit Analyzer app
        click_hold(
            main_desktop,
            try_find_element(main_app_win, FindElementBy.NAME, 'Close',
                             self.med_retry))

        assert report_itm is not None, "'Monitored_Execution_report_1' is not found"

    def test_create_detailed_execution_report_for_nix_session_libaudit_mode(
            self, css_testee_machine):

        logger.info("--- Case C1238828")
        report_name = "Detailed_Execution_report_1"
        desktop = get_desktop()
        reports_tr_itm, main_app_win, main_desktop, report_tr_itm = create_reports_func(ReportType.detailed_report, \
                                                                                        desktop)

        detailed_report_win = try_find_element(main_desktop, FindElementBy.AUTOMATION_ID, \
                                               'CommandDetailReportQueryCriteria', self.med_retry)

        # Select the machine box and enter full windows machine name
        try_find_element(detailed_report_win, FindElementBy.AUTOMATION_ID,
                         'm_machineOption', self.med_retry).click()
        full_machine_name = r"%s.%s" % (css_testee_machine['hostname'],
                                        css_testee_machine['domain_name'])

        try_find_element(main_desktop, FindElementBy.AUTOMATION_ID,
                         'm_machineName',
                         self.med_retry).send_keys(full_machine_name)

        # Check the Event time checkbox and select the time
        try_find_element(detailed_report_win, FindElementBy.AUTOMATION_ID,
                         'm_eventTimeOption', self.med_retry).click()

        time_cbox = try_find_element(detailed_report_win, FindElementBy.AUTOMATION_ID, 'm_timeNormalOpList', \
                                     self.med_retry)
        click_hold(main_desktop, time_cbox)
        time_lst_itm = try_find_element(main_desktop, FindElementBy.NAME,
                                        'Is after', self.med_retry)
        if time_lst_itm is not None:
            click_hold(main_desktop, time_lst_itm)

        # Save the created Query

        save_query_btn = try_find_element(detailed_report_win, FindElementBy.AUTOMATION_ID, 'm_saveQuery', \
                                          self.med_retry)
        click_hold(main_desktop, save_query_btn)

        # Add report name

        try_find_element(
            main_desktop, FindElementBy.AUTOMATION_ID, 'textBox1',
            self.med_retry).send_keys("Detailed_Execution_report_1")

        try_find_element(main_desktop, FindElementBy.AUTOMATION_ID, 'button2',
                         self.med_retry).click()

        if try_find_element(reports_tr_itm, FindElementBy.NAME, report_name, \
                            self.small_retry, ignore_if_not_found=True) is None:
            double_click(main_desktop, reports_tr_itm)

            double_click(main_desktop, report_tr_itm)

        report_itm = try_find_element(reports_tr_itm, FindElementBy.NAME,
                                      report_name, self.med_retry)

        #  Close the Audit Analyzer app
        click_hold(
            main_desktop,
            try_find_element(main_app_win, FindElementBy.NAME, 'Close',
                             self.med_retry))

        assert report_itm is not None, "'Detailed_Execution_report_1' is not found"

    def test_create_audit_event_query_for_nix_session_libaudit_mode(
            self, css_testee_machine):

        logger.info("--- Case C1238829")

        audit_event_query_name = "Audit_Event_query_1"
        desktop = get_desktop()
        audit_event_itm = create_audit_event_function(desktop, audit_event_query_name, [AuditEventType.Advanced_Monitoring], \
                                                  css_testee_machine)
        assert audit_event_itm is not None, f"{audit_event_query_name} is not found"
Ejemplo n.º 20
0
from datetime import datetime
from enum import Enum
from time import sleep

import paramiko
import pytest
from paramiko import SSHClient
from scp import SCPClient
from Shared.CSS import css_win_constants
from Utils.config_loader import Configs
from Utils.putty_util import *
from Utils.winrm import WinRM

logger = logging.getLogger('framework')

tear_down = Configs.get_test_node("da_installation", "settings")["tear_down"]

repo_python_path = css_win_constants.repo_python_path
remote_python_path = css_win_constants.remote_python_path
python_install_path = css_win_constants.python_install_path

repo_da_administrator_console_path = css_win_constants.repo_da_administrator_console_path
remote_da_administrator_console_path = css_win_constants.remote_da_administrator_console_path

repo_da_auditor_path = css_win_constants.repo_da_auditor_path
remote_da_auditor_path = css_win_constants.remote_da_auditor_path

remote_audit_manager_path = css_win_constants.remote_audit_manager_path
repo_audit_manager_path = css_win_constants.repo_audit_manager_path

repo_da_agent_path = css_win_constants.repo_da_agent_path
Ejemplo n.º 21
0
import pathlib
import pytest
import subprocess
import uuid
import re
import shutil
import Utils.settings
from collections import namedtuple
from datetime import timezone

from Shared.elasticsearch_data_manager import ElasticsearchRequestData
from Utils.cent_logger import setup_root_logger
from Utils.config_loader import Configs
from Utils.elasticsearch import Elasticsearch

settings = Configs.get_node("framework", "framework")
for i in settings:
    setattr(Utils.settings, i, settings[i])
setattr(Utils.settings, 'options', {})

_session_es_info = {}  # alias for elasticsearch_run_data

# fixtures which use syntax not acceptable as a plugin from a conftest.py file
excluded_fixtures = [
    'application_management_fixtures', 'cis_fixtures', 'core_bat_fixtures',
    'credman_fixtures', 'pdst_fixtures', 'selenium_webdriver_fixtures',
    'suvp_fixtures', 'user_login_with_mfa_rts_fixture'
]

pytest_plugins = []
# import all fixtures automatically, except for those being excluded.
class TestforNixAgentCzoneNSSMode:
    """
    To create shared query and report for new sessions
    """

    settings = Configs.get_test_node("da_installation", "settings")
    med_retry = settings['med_retry']
    vry_small_retry = settings['vry_small_retry']
    small_retry = settings['small_retry']
    filename = "test_DAWinBAT_test_for_NIX_Agent_C_zone_NSS_mode.py"
    class_name = "TestforNixAgentCzoneNSSMode"

    @pytest.mark.bhavna
    @pytest.mark.css
    @pytest.mark.da_win_bat
    def test_master_create_shared_query_for_nix_session_nss_mode(
            self, dawin_testagent_uploaded, dawin_installed,
            css_testee_login_as_domain_admin):
        username = r"%s\%s" % (dawin_installed['domain_name'].split('.')[0],
                               "administrator")
        login_and_execute_cmds(
            username, dawin_installed['admin_password'],
            dawin_installed['public_ip'], css_testee_login_as_domain_admin,
            self.filename, self.class_name,
            'test_create_shared_query_for_nix_session_nss_mode')

    @pytest.mark.bhavna
    @pytest.mark.css
    @pytest.mark.da_win_bat
    def test_master_verify_audited_sessions_nix_session_nss_mode(
            self, dawin_testagent_uploaded, dawin_installed,
            css_testee_login_as_domain_admin):
        username = r"%s\%s" % (dawin_installed['domain_name'].split('.')[0],
                               "administrator")
        login_and_execute_cmds(username, dawin_installed['admin_password'],
                               dawin_installed['public_ip'],
                               css_testee_login_as_domain_admin, self.filename,
                               self.class_name,
                               'test_verify_audited_sessions_nss_mode')

    def test_create_shared_query_for_nix_session_nss_mode(self):
        logger.info("--- Case C1238979")

        query_name = 'pershell_c'
        desktop = get_desktop()
        shared_query_itm = create_query_func(desktop, query_name, [SessionType.Windows_session, \
                                                                   SessionType.Linux_Desktop_session])
        assert shared_query_itm is not None, f"{query_name} is not found"

    def test_verify_audited_sessions_nss_mode(self, css_test_machine,
                                              css_test_env,
                                              get_aduser_from_yaml):
        logger.info("--- Case C1238987")
        query_name = 'pershell_c'
        desktop = get_desktop()
        host_name = css_test_machine['hostname']
        domain_name = css_test_env['domain_name']
        command_list = ['adinfo', 'dainfo', 'exit']
        user = '******'
        audit_session_file, review_comment, review_status = validate_event_file(
            query_name, domain_name, user, get_aduser_from_yaml, desktop,
            host_name)

        # Verify session command list, review comment and status
        assert review_comment == True, "Review comment not found"
        assert review_status == True, "Review status not found"
        for command in command_list:
            assert (command in audit_session_file
                    ) == True, f"Session for {command} command not created"
Ejemplo n.º 23
0
def parallel_agent_install():
    list_of_dicts = Configs.get_yaml_node('suvp_test_hosts', 'tested_hosts')
    p = Pool(len(list_of_dicts))
    p.map(static_agent_install, list_of_dicts)
    p.join()
    p.close()
def navigation_visibility(request):
    return Configs.get_environment_node('navigation', 'automation_main')
Ejemplo n.º 25
0
class TestConfigureDAInstallation:
    """
    Install and configure the DA installation
    """
    settings = Configs.get_test_node("da_installation", "settings")
    vry_small_retry = settings['vry_small_retry']
    small_retry = settings['small_retry']
    med_retry = settings['med_retry']
    big_retry = settings['big_retry']
    filename = "test_DAWinBAT_Configure_DA_installation.py"
    class_name = "TestConfigureDAInstallation"

    @pytest.mark.bhavna
    @pytest.mark.css
    @pytest.mark.da_win_bat
    def test_master_create_da_installation(self, dawin_testagent_uploaded, dawin_installed, \
                                           css_testee_login_as_domain_admin):
        username = r"%s\%s" % (dawin_installed['domain_name'].split('.')[0],
                               "administrator")
        login_and_execute_cmds(username, dawin_installed['admin_password'],
                               dawin_installed['public_ip'],
                               css_testee_login_as_domain_admin, self.filename,
                               self.class_name, 'test_create_da_installation')

    @pytest.mark.bhavna
    @pytest.mark.css
    @pytest.mark.da_win_bat
    def test_master_configure_connector_and_verify_version(
            self, dawin_installed, css_testee_login_as_domain_admin):
        username = r"%s\%s" % (dawin_installed['domain_name'].split('.')[0],
                               "administrator")
        login_and_execute_cmds(username, dawin_installed['admin_password'],
                               dawin_installed['public_ip'],
                               css_testee_login_as_domain_admin, self.filename,
                               self.class_name,
                               'test_configure_collector_and_verify_version')

    @pytest.mark.bhavna
    @pytest.mark.css
    @pytest.mark.da_win_bat
    def test_master_centrify_da_agent_configure(self, css_client_login,
                                                css_client_test_machine):
        username = r"%s\%s" % (css_client_test_machine['domain_name'].split(
            '.')[0], "administrator")
        login_and_execute_cmds(username,
                               css_client_test_machine['admin_password'],
                               css_client_test_machine['public_ip'],
                               css_client_login, self.filename,
                               self.class_name,
                               'test_centrify_da_agent_configure')

    # 1.Configure DA installation

    def test_create_da_installation(self):
        logger.info("--- Case C1238801")

        dsksession = get_desktop()
        logger.info("Creating the DA installation")
        self.test_centrify_da_console_install(dsksession)

        logger.info("Checking the DA package version")
        self.test_centrify_da_console_version(dsksession)

        logger.info("Adding the audit store")
        self.test_configure_audit_store(dsksession)

        logger.info("Exiting")
        dsksession.quit()

    def test_centrify_da_console_install(self, desktop):
        da_console_config = self.settings['audit_console']
        sql_instance_name = self.settings['sql_instance_name']
        sql_machine_name = self.settings['sql_machine_name']
        new_management_db_name = self.settings['new_management_db_name']
        da_instance_name = self.settings['da_instance_name']
        licence_key = self.settings['licence_key']
        disable_video_capturing = da_console_config['disable_video_capturing']
        review_own_session = da_console_config['review_own_session']
        delete_own_session = da_console_config['delete_own_session']
        disable_audit_store_install_now = da_console_config[
            'disable_audit_store_install_now']

        launch_application(css_win_constants.da_administrator_startup_path)

        ok_centrify_license_dlg(desktop)
        window = try_find_element(
            desktop, FindElementBy.CLASS,
            'WindowsForms10.Window.8.app.0.141b42a_r41_ad1', self.med_retry,
            True)
        da_installed = False
        if window is not None:
            # if multiple da installations are present
            installed_da_popup = try_find_element(window,
                                                  FindElementBy.AUTOMATION_ID,
                                                  'm_forest',
                                                  self.vry_small_retry, True)
            if installed_da_popup is not None:
                cancel = try_find_element(window, FindElementBy.AUTOMATION_ID,
                                          'm_cancelButton',
                                          self.vry_small_retry)
                click_hold(desktop, cancel)
                da_installed = True

        if window is None or da_installed:
            da_node = get_da_installation_node(desktop)
            click_hold(desktop, da_node)
            click_context_menu(desktop, da_node, "New Installation...")

        new_install = try_find_element(desktop, FindElementBy.NAME,
                                       'New Installation Wizard',
                                       self.small_retry, True)
        try_find_element(new_install, FindElementBy.AUTOMATION_ID, 'm_name',
                         self.small_retry).send_keys(da_instance_name)
        click_hold(
            desktop,
            try_find_element(new_install, FindElementBy.AUTOMATION_ID,
                             'm_nextButton', self.small_retry))
        click_hold(
            desktop,
            try_find_element(new_install, FindElementBy.AUTOMATION_ID,
                             'm_createOption', self.small_retry))

        sql_to_connect = sql_machine_name + '\\' + sql_instance_name
        sql_to_connect = sql_to_connect.strip("\\")

        try_find_element(new_install, FindElementBy.AUTOMATION_ID, '1001',
                         self.small_retry).send_keys(sql_to_connect)

        try_find_element(new_install, FindElementBy.AUTOMATION_ID,
                         'm_database',
                         self.small_retry).send_keys(new_management_db_name)
        click_hold(
            desktop,
            try_find_element(new_install, FindElementBy.AUTOMATION_ID,
                             'm_nextButton', self.small_retry))

        ## Page 3
        set_sql_login_account(new_install, desktop,
                              self.settings["sql_login_account"])
        click_hold(
            desktop,
            try_find_element(new_install, FindElementBy.AUTOMATION_ID,
                             'm_nextButton', self.small_retry))

        ## For AdminPopUp
        popup_handle = try_find_element(desktop, FindElementBy.NAME, 'OK',
                                        self.vry_small_retry, True)

        if popup_handle is not None:
            click_hold(desktop, popup_handle)

        key_page = try_find_element(new_install, FindElementBy.AUTOMATION_ID,
                                    'm_key', self.vry_small_retry, True)
        while key_page is None:
            click_hold(
                desktop,
                try_find_element(new_install, FindElementBy.AUTOMATION_ID,
                                 'm_nextButton', self.small_retry))
            key_page = try_find_element(new_install,
                                        FindElementBy.AUTOMATION_ID, 'm_key',
                                        self.vry_small_retry, True)

        key_page.send_keys(licence_key)

        ## Product key Page
        # try_find_element(window, FindElementBy.AUTOMATION_ID, 'm_key', SMALL_RETRY).send_keys(licence_key)
        click_hold(
            desktop,
            try_find_element(new_install, FindElementBy.AUTOMATION_ID,
                             'm_addButton', self.small_retry))
        click_hold(
            desktop,
            try_find_element(new_install, FindElementBy.AUTOMATION_ID,
                             'm_nextButton', self.small_retry))

        ## location page
        click_hold(
            desktop,
            try_find_element(new_install, FindElementBy.AUTOMATION_ID,
                             'm_nextButton', self.small_retry))

        ## permissions
        if disable_video_capturing:
            click_hold(
                desktop,
                try_find_element(new_install, FindElementBy.AUTOMATION_ID,
                                 'EnableVideoAuditCheckBox', self.small_retry))
        if review_own_session:
            click_hold(
                desktop,
                try_find_element(new_install, FindElementBy.AUTOMATION_ID,
                                 'DisableSelfReviewCheckBox',
                                 self.small_retry))
        if delete_own_session:
            click_hold(
                desktop,
                try_find_element(new_install, FindElementBy.AUTOMATION_ID,
                                 'DisableSelfDeleteCheckBox',
                                 self.small_retry))

        click_hold(
            desktop,
            try_find_element(new_install, FindElementBy.AUTOMATION_ID,
                             'm_nextButton', self.small_retry))

        ## review
        click_hold(
            desktop,
            try_find_element(new_install, FindElementBy.AUTOMATION_ID,
                             'm_nextButton', self.small_retry))

        ## finish
        if disable_audit_store_install_now:
            click_hold(
                desktop,
                try_find_element(desktop, FindElementBy.AUTOMATION_ID,
                                 'm_option', self.big_retry))

        click_hold(
            desktop,
            try_find_element(desktop, FindElementBy.AUTOMATION_ID,
                             'm_nextButton', self.big_retry))

    def test_centrify_da_console_version(self, desktop):
        window = try_find_element(desktop, FindElementBy.CLASS, 'MMCMainFrame',
                                  self.small_retry)
        pop_up = try_find_element(window, FindElementBy.NAME, 'OK',
                                  self.vry_small_retry, True)
        if pop_up is not None:
            click_hold(desktop, pop_up)

        help_elements = window.find_elements_by_name('Help')

        for element in help_elements:
            if element.get_attribute('LocalizedControlType') == 'menu item':
                click_hold(desktop, element)
                element.send_keys(Keys.ARROW_DOWN)
                element.send_keys(Keys.ARROW_DOWN)
                element.send_keys('b')

        complete_text = str(
            try_find_element(window, FindElementBy.AUTOMATION_ID, '4160',
                             self.small_retry).text)
        click_hold(desktop, window.find_element_by_accessibility_id('1'))
        index = complete_text.index('Version')
        version = complete_text[index:]

        assert (self.settings['version'] == version
                ), 'version mismatch it should be:' + self.settings['version']

    def test_configure_audit_store(self, desktop):
        """
        Configures audit store in a pre-configured Direct Audit installation.
        Expects Audit Manager window to be open
        """
        ok_centrify_license_dlg(desktop)
        da_node = get_da_installation_node(desktop)
        double_click(desktop, da_node)
        ok_centrify_license_dlg(desktop)

        audit_store_setting = self.settings["audit_store"]
        da_instance_name = self.settings['da_instance_name']
        cntry_install = get_da_installation_node(desktop, da_instance_name)

        # double click to open tree-node
        double_click(desktop, cntry_install)
        ok_centrify_license_dlg(desktop)
        open_tree_node(desktop, cntry_install)

        # region go to Audit Stores tree-node and context-click Add Audit Store...
        cntry_audit_stores = cntry_install.find_element_by_name("Audit Stores")
        double_click(desktop, cntry_audit_stores)
        click_context_menu(desktop, cntry_audit_stores, "Add Audit Store...")
        # endregion

        # region Add Audit Store Wizard
        audit_store_wizard = try_find_element(desktop, FindElementBy.NAME,
                                              "Add Audit Store Wizard",
                                              self.med_retry)
        if audit_store_setting["store_display_name"] == "":
            raise Exception("store_display_name cannot be blank")
        clear_txtbox(try_find_element(audit_store_wizard, FindElementBy.NAME, "Display name:", self.med_retry)) \
            .send_keys(audit_store_setting["store_display_name"])

        while try_find_element(audit_store_wizard,
                               FindElementBy.AUTOMATION_ID,
                               "m_winAndUnixRadioBtn",
                               self.vry_small_retry,
                               ignore_if_not_found=True) is None:
            click_hold(
                desktop,
                try_find_element(audit_store_wizard, FindElementBy.NAME,
                                 "Next >", self.med_retry))

        while try_find_element(audit_store_wizard,
                               FindElementBy.NAME,
                               "Add Site",
                               self.vry_small_retry,
                               ignore_if_not_found=True
                               ) is None:  # retry until next screen found
            affinity = audit_store_setting["affinity"].lower()
            if affinity == "windows and unix":
                click_hold(
                    desktop,
                    try_find_element(audit_store_wizard,
                                     FindElementBy.AUTOMATION_ID,
                                     "m_winAndUnixRadioBtn", self.med_retry))
            elif affinity == "windows":
                click_hold(
                    desktop,
                    try_find_element(audit_store_wizard,
                                     FindElementBy.AUTOMATION_ID,
                                     "m_winRadioBtn", self.med_retry))
            elif affinity == "unix":
                click_hold(
                    desktop,
                    try_find_element(audit_store_wizard,
                                     FindElementBy.AUTOMATION_ID,
                                     "m_unixRadioBtn", self.med_retry))
            click_hold(
                desktop,
                try_find_element(audit_store_wizard, FindElementBy.NAME,
                                 "Next >", self.med_retry))

        # select AD-site
        add_site = try_find_element(audit_store_wizard, FindElementBy.NAME,
                                    "Add Site", self.med_retry)
        while try_find_element(audit_store_wizard,
                               FindElementBy.NAME,
                               "Select Active Directory Sites",
                               self.vry_small_retry,
                               ignore_if_not_found=True) is None:
            click_hold(desktop,
                       add_site)  # retry click until next screen loaded

        ad_sites = try_find_element(audit_store_wizard, FindElementBy.NAME,
                                    "Select Active Directory Sites",
                                    self.med_retry)
        click_hold(
            desktop,
            try_find_element(ad_sites, FindElementBy.NAME,
                             "Select a site from current forest",
                             self.med_retry))
        sites_list = try_find_element(ad_sites, FindElementBy.AUTOMATION_ID,
                                      "m_siteList", self.med_retry)

        if audit_store_setting["ad_site"] == "":
            click_hold(
                desktop,
                try_find_element(sites_list, FindElementBy.AUTOMATION_ID,
                                 "ListViewItem-0", self.med_retry))
        else:
            # all child in list

            found = listbox_select_item(desktop, sites_list,
                                        audit_store_setting["ad_site"])

            if not found:
                raise Exception("AD Site '" + audit_store_setting["ad_site"] +
                                "' not found")

        while not try_find_element(audit_store_wizard, FindElementBy.NAME,
                                   "Next >", self.med_retry).is_enabled():
            click_hold(desktop,
                       try_find_element(
                           ad_sites, FindElementBy.NAME, "OK",
                           self.med_retry))  # retry clicks until next enables

        click_hold(
            desktop,
            try_find_element(audit_store_wizard, FindElementBy.NAME, "Next >",
                             self.med_retry))
        while try_find_element(audit_store_wizard,
                               FindElementBy.NAME,
                               "Finish",
                               self.vry_small_retry,
                               ignore_if_not_found=True
                               ) is None:  # retry clicks until Finish found
            click_hold(
                desktop,
                try_find_element(audit_store_wizard, FindElementBy.NAME,
                                 "Next >", self.med_retry))
        click_hold(
            desktop,
            try_find_element(audit_store_wizard, FindElementBy.NAME, "Finish",
                             self.med_retry))

        # endregion

        # region Add Audit Store Database Wizard
        audit_store_db_wizard = try_find_element(
            desktop, FindElementBy.NAME, "Add Audit Store Database Wizard",
            self.med_retry)
        clear_txtbox(try_find_element(audit_store_db_wizard, FindElementBy.NAME, "Display name:", self.med_retry)) \
            .send_keys(audit_store_setting["db_display_name"])
        click_hold(
            desktop,
            try_find_element(audit_store_db_wizard, FindElementBy.NAME,
                             "Next >", self.med_retry))

        sql_to_connect = self.settings[
            "sql_machine_name"] + "\\" + self.settings["sql_instance_name"]
        sql_to_connect = sql_to_connect.strip("\\")
        clear_txtbox(try_find_element(audit_store_db_wizard, FindElementBy.CLASS, "Edit", self.med_retry)) \
            .send_keys(sql_to_connect)
        click_hold(
            desktop,
            try_find_element(audit_store_db_wizard, FindElementBy.NAME,
                             "Next >", self.med_retry))

        clear_txtbox(try_find_element(audit_store_db_wizard, FindElementBy.NAME, "Database name:", self.med_retry)) \
            .send_keys(audit_store_setting["db_name"])
        active_chk = try_find_element(audit_store_db_wizard,
                                      FindElementBy.NAME,
                                      "Set as active database", self.med_retry)

        if audit_store_setting["db_set_active"]:
            if not active_chk.is_selected():
                click_hold(desktop, active_chk)
        else:
            if active_chk.is_selected():
                click_hold(desktop, active_chk)
        click_hold(
            desktop,
            try_find_element(audit_store_db_wizard, FindElementBy.NAME,
                             "Next >", self.vry_small_retry))

        set_sql_login_account(audit_store_db_wizard, desktop,
                              self.settings["sql_login_account"])

        click_hold(
            desktop,
            try_find_element(audit_store_db_wizard, FindElementBy.NAME,
                             "Next >", self.vry_small_retry))
        click_hold(
            desktop,
            try_find_element(audit_store_db_wizard, FindElementBy.NAME,
                             "Next >", self.vry_small_retry))
        click_hold(
            desktop,
            try_find_element(audit_store_db_wizard, FindElementBy.NAME,
                             "Finish", self.med_retry))

        # endregion

        # region open tree-node, check Audit Store

        # refresh and open Audit Stores tree-node
        click_context_menu(desktop, cntry_audit_stores, "Refresh")
        open_tree_node(desktop, cntry_audit_stores)
        # open Audit Store tree-node
        cntry_audit_store = cntry_audit_stores.find_element_by_name(
            audit_store_setting["store_display_name"])
        open_tree_node(desktop, cntry_audit_store)
        # open Databases tree-node
        databases = cntry_audit_store.find_element_by_name("Databases")
        double_click(desktop, databases)

        # endregion
        assert databases is not None, "test_config_audit_store PASSED"
        cntry_main_screen = try_find_element(desktop, FindElementBy.CLASS,
                                             "MMCMainFrame", self.small_retry)
        click_hold(
            desktop,
            try_find_element(cntry_main_screen, FindElementBy.NAME, "Close",
                             self.med_retry))
        logger.info('application closed')

    def test_configure_collector_and_verify_version(self):
        """
        Configures controller in a pre-configured Direct Audit installation and verify the version.
        """
        logger.info("--- Case C1238802")
        logger.info("------Step 1")

        logger.info("Configuring the collector")
        desktop = get_desktop()
        collector_setting = settings["collector"]
        collector_session = start_collector_configure()

        collector_win = try_find_element(desktop, FindElementBy.AUTOMATION_ID,
                                         "CollectorControlPanel",
                                         self.med_retry)
        click_hold(
            desktop,
            try_find_element(collector_win, FindElementBy.AUTOMATION_ID,
                             "m_configureButton", self.med_retry))
        config_win = try_find_element(
            desktop, FindElementBy.NAME,
            "Centrify DirectAudit Collector Configuration Wizard",
            self.med_retry)
        install_list = try_find_element(config_win,
                                        FindElementBy.AUTOMATION_ID,
                                        "m_installList", self.med_retry)

        found_instance_name = listbox_select_item(desktop, install_list,
                                                  settings["da_instance_name"])

        if not found_instance_name:
            raise Exception("DA instance '" + settings["da_instance_name"] +
                            "' not found. ")
        click_hold(
            desktop,
            try_find_element(config_win, FindElementBy.AUTOMATION_ID,
                             "m_nextButton", self.med_retry))

        clear_txtbox(try_find_element(config_win, FindElementBy.AUTOMATION_ID, "m_port", self.med_retry)). \
            send_keys(collector_setting["listening_port"])

        while try_find_element(config_win,
                               FindElementBy.AUTOMATION_ID,
                               "m_windowsOption",
                               self.vry_small_retry,
                               ignore_if_not_found=True) is None:
            click_hold(
                desktop,
                try_find_element(config_win, FindElementBy.AUTOMATION_ID,
                                 "m_nextButton", self.med_retry))

        click_hold(
            desktop,
            try_find_element(config_win, FindElementBy.AUTOMATION_ID,
                             "m_windowsOption", self.med_retry))
        click_hold(
            desktop,
            try_find_element(config_win, FindElementBy.AUTOMATION_ID,
                             "m_nextButton", self.med_retry))

        clear_txtbox(try_find_element(config_win, FindElementBy.AUTOMATION_ID, "m_maxPoolSize", self.med_retry)). \
            send_keys(collector_setting["max_pool_size"])
        click_hold(
            desktop,
            try_find_element(config_win, FindElementBy.AUTOMATION_ID,
                             "m_nextButton", self.med_retry))

        click_hold(
            desktop,
            try_find_element(config_win, FindElementBy.AUTOMATION_ID,
                             "m_nextButton", self.med_retry))

        click_hold(
            desktop,
            try_find_element(config_win, FindElementBy.NAME, "Finish",
                             self.med_retry))

        click_hold(
            desktop,
            try_find_element(collector_win, FindElementBy.AUTOMATION_ID,
                             "m_restartButton", self.med_retry))
        status_txt = try_find_element(collector_win,
                                      FindElementBy.AUTOMATION_ID, "m_status",
                                      self.med_retry).text.lower()
        timer = 0
        while status_txt != "running" and timer < self.big_retry:
            timer = timer + 1
            status_txt = try_find_element(collector_win,
                                          FindElementBy.AUTOMATION_ID,
                                          "m_status",
                                          self.med_retry).text.lower()
        assert status_txt == "running", "Collector not started " + status_txt

        logger.info("Verifying the Collector version")
        logger.info("------Step 2")

        version_lbl = try_find_element(collector_win,
                                       FindElementBy.AUTOMATION_ID,
                                       "m_verLabel", self.med_retry)
        actual_version = ''.join(
            re.compile(r'([0-9]+)+').findall(
                re.search(
                    r"\(.*?\)",
                    version_lbl.text).group().split(": ")[1].rstrip(r'\)')))
        expected_version = ''.join(
            re.compile(r'([0-9]+)+').findall(settings['version']))

        # Close the Collector application
        collector_session.quit()
        assert (expected_version == actual_version
                ), 'Collector version mismatch it should be:' + self.settings[
                    'version']

    def test_centrify_da_agent_configure(self, css_client_test_machine):
        logger.info("--- Case C1238803")
        logger.info("------Step 1")
        desktop = get_desktop()
        da_agent = settings['agent']
        ad_admin = r"%s\%s" % (css_client_test_machine['domain_name'].split(
            '.')[0], 'administrator')
        ad_admin_password = css_client_test_machine['ad_admin_password']
        enable_session_capture = da_agent['enable_session_capture']
        da_instance_name = settings['da_instance_name']

        launch_application(css_win_constants.remote_da_agent_start_path)

        window = try_find_element(desktop, FindElementBy.NAME,
                                  'Centrify Agent Configuration',
                                  self.small_retry)
        # add_services
        try_find_element(window, FindElementBy.NAME, 'Add service',
                         self.small_retry).click()

        # select the services
        if enable_session_capture:
            click_hold(
                desktop,
                try_find_element(window, FindElementBy.NAME,
                                 'Enable session capture and replay',
                                 self.small_retry))

        try_find_element(window, FindElementBy.NAME, 'OK',
                         self.small_retry).click()

        # select da instance name
        popup_win = try_find_element(
            desktop, FindElementBy.NAME,
            'Centrify Auditing and Monitoring Service', self.small_retry)
        found_instance_name = try_find_element(desktop, FindElementBy.NAME,
                                               da_instance_name,
                                               self.vry_small_retry, True)
        try_find_element(desktop, FindElementBy.CLASS, 'ListView',
                         self.small_retry).click()

        retry = 0
        while not found_instance_name or not found_instance_name.is_selected(
        ) and retry < self.med_retry:
            ActionChains(desktop).key_down(Keys.ARROW_DOWN).perform()
            found_instance_name = try_find_element(desktop, FindElementBy.NAME,
                                                   da_instance_name,
                                                   self.vry_small_retry, True)
        else:
            found_instance_name.click()
        if found_instance_name is None:
            raise Exception("DA instance '" + settings["da_instance_name"] +
                            "' not found. ")

        try_find_element(popup_win, FindElementBy.NAME, '_Next',
                         self.vry_small_retry).click()

        popup_win = try_find_element(
            desktop, FindElementBy.NAME,
            'Centrify Auditing and Monitoring Service', self.vry_small_retry,
            True)
        if popup_win is None:
            actions = ActionChains(desktop)
            actions.send_keys(ad_admin)
            actions.send_keys(Keys.TAB)
            actions.send_keys(ad_admin_password)
            actions.send_keys(Keys.ENTER)
            actions.perform()
        else:
            popup_win = try_find_element(
                desktop, FindElementBy.NAME,
                'Centrify Auditing and Monitoring Service',
                self.vry_small_retry, True)
        retry = 0
        while try_find_element(popup_win, FindElementBy.NAME, 'Progress',
                               self.vry_small_retry,
                               True) is None and retry < 10:
            retry = retry + 1

        list_item = try_find_element(
            window, FindElementBy.NAME,
            'Centrify.WinAgent.ServiceConfig.ViewModel.AuditService',
            self.small_retry, True)

        if list_item is not None:
            service_installed = try_find_element(
                list_item, FindElementBy.NAME,
                'Centrify Auditing and Monitoring Service', self.small_retry,
                True)

        assert list_item is not None and service_installed is not None, "Agent service configuration failed"

        logger.info("Verifying the Agent version")
        logger.info("------Step 2")

        try_find_element(window, FindElementBy.CLASS, 'ListBoxItem',
                         small_retry).click()
        try_find_element(window, FindElementBy.NAME, 'Settings',
                         small_retry).click()
        agent_panel_win = try_find_element(desktop,
                                           FindElementBy.AUTOMATION_ID,
                                           'AgentControlPanel', small_retry)

        version_lbl = try_find_element(agent_panel_win,
                                       FindElementBy.AUTOMATION_ID,
                                       "m_verLabel", self.med_retry)
        actual_version = ''.join(
            re.compile(r'([0-9]+)+').findall(
                re.search(
                    r"\(.*?\)",
                    version_lbl.text).group().split(": ")[1].rstrip(r'\)')))
        expected_version = ''.join(
            re.compile(r'([0-9]+)+').findall(settings['version']))

        # Close the Agent app
        try_find_element(agent_panel_win, FindElementBy.NAME, 'Close',
                         self.small_retry).click()
        try_find_element(window, FindElementBy.NAME, 'Close',
                         self.small_retry).click()
        assert (expected_version == actual_version), 'Collector version mismatch it should be:' + \
                                                     self.settings['version']
def test_check_connector_page_for_system(core_session, pas_windows_setup,
                                         users_and_roles):
    """
    TC:C2171 Check UI on Connectors page for a system.
    :param:core_session: Returns Authenticated Centrify session.
    :param:users_and_roles:Fixture to manage roles and user.
    :param pas_windows_setup: Return a fixture.
    """

    # Creating a system and account.
    system_id, account_id, sys_info, connector_id, user_password = pas_windows_setup(
    )

    # Cloud user session with "Privileged Access Service Administrator".
    cloud_user_session = users_and_roles.get_session_for_user(
        'Privileged Access Service Administrator')
    user_name = cloud_user_session.auth_details['User']
    user_id = cloud_user_session.auth_details['UserId']

    # UI session with "Privileged Access Service Administrator" rights.
    ui = users_and_roles.get_ui_as_user(
        'Privileged Access Service Administrator')

    # Assigning system "View,Delete" permission
    assign_system_result, assign_system_success = ResourceManager.assign_system_permissions(
        core_session, "View,Delete", user_name, user_id, 'User', system_id)
    assert assign_system_success, f"Failed to assign system permissions: API response result: {assign_system_result}"
    logger.info(
        f'Successfully assigned "View" permission to user:{assign_system_result}.'
    )

    # Getting the connectors Details.
    connector_details = Configs.get_environment_node('connector_data',
                                                     'automation_main')
    list_connectors_id = []
    connectors_details = RedrockController.get_all_proxy(core_session)
    for connector_detail in connectors_details:
        if connector_detail['Name'] == connector_details['connector']:
            list_connectors_id.append(connector_detail['ID'])

    # Choosing the connector for the system.
    result, success = ResourceManager.update_system(
        core_session,
        system_id=system_id,
        name=sys_info[0],
        fqdn=sys_info[1],
        computerclass=sys_info[2],
        proxycollectionlist=connector_id,
        chooseConnector="on",
        filterConnectorCombo="all")
    assert success, f'Failed to save the connector for the system: API response result: {result}.'
    logger.info(
        f'Successfully save the connector  for the system: API response result: {result}.'
    )

    # UI Launch
    ui.navigate('Resources', 'Systems')
    ui.search(sys_info[0])
    ui.click_row(GridRowByGuid(system_id))
    ui.tab('Connectors', check_rendered_tab=False)
    ui.switch_context(ActiveMainContentArea())
    ui.expect(
        ReadOnlyTextField('filterConnectorCombo'),
        'Expected the username field to be readonly for this filterConnectorCombo strategy but it is not.'
    )
    logger.info(
        'Successfully found connector settings  grayed and no error icon')