Пример #1
0
    def RunCryptohomeTest(self):
        """Test Cryptohome."""
        logging.info('RunCryptohomeTest: Starting chrome and logging in.')
        is_arc_available = utils.is_arc_available()
        arc_mode = arc_common.ARC_MODE_ENABLED if is_arc_available else None
        with chrome.Chrome(arc_mode=arc_mode, num_tries=1) as cr:
            # Check that the cryptohome is mounted.
            # is_vault_mounted throws an exception if it fails.
            logging.info('Checking mounted cryptohome.')
            cryptohome.is_vault_mounted(user=cr.username, allow_fail=False)
            # Navigate to about:blank.
            tab = cr.browser.tabs[0]
            tab.Navigate('about:blank')

            # Evaluate some javascript.
            logging.info('Evaluating JavaScript.')
            if tab.EvaluateJavaScript('2+2') != 4:
                raise TestFail('EvaluateJavaScript failed')

            # ARC test.
            if is_arc_available:
                arc.wait_for_adb_ready()
                logging.info('Android booted successfully.')
                arc.wait_for_android_process('org.chromium.arc.intent_helper')
                if not arc.is_package_installed('android'):
                    raise TestFail(
                        '"android" system package was not listed by '
                        'Package Manager.')

        if is_arc_available:
            utils.poll_for_condition(
                lambda: not arc.is_android_container_alive(),
                timeout=15,
                desc='Android container still running '
                'after Chrome shutdown.')
    def run_once(self):
        username = ''
        with chrome.Chrome() as cr:
            username = cr.username
            if not cryptohome.is_vault_mounted(user=username,
                                               allow_fail=False):
                raise error.TestFail('Expected to find a mounted vault.')

        if cryptohome.is_vault_mounted(user=username, allow_fail=True):
            raise error.TestFail('Expected to not find a mounted vault.')

        # Remove our vault, mount another vault, create a test file
        # in the other vault, and ensure that the file no longer exists
        # after we log back in.
        cryptohome.remove_vault(username)

        cryptohome.mount_vault(TEST_USER, TEST_PASS, create=True)
        test_file = os.path.join(cryptohome.user_path(TEST_USER), 'hello')
        open(test_file, 'w').close()
        cryptohome.unmount_vault(TEST_USER)

        with chrome.Chrome():
            if not cryptohome.is_vault_mounted(user=username,
                                               allow_fail=False):
                raise error.TestFail('Expected to find user\'s mounted vault.')
            if os.path.exists(test_file):
                raise error.TestFail('Expected to not find the test file.')
Пример #3
0
    def run_once(self, child_user, child_pass, parent_user, parent_pass):
        """Test function body."""
        if not (child_user and child_pass and parent_user and parent_pass):
            raise error.TestFail('Credentials not set.')

        with chrome.Chrome(auto_login=False) as cr:
            cr.browser.oobe.NavigateUnicornLogin(child_user=child_user,
                                                 child_pass=child_pass,
                                                 parent_user=parent_user,
                                                 parent_pass=parent_pass)
            if not cryptohome.is_vault_mounted(
                    user=chrome.NormalizeEmail(child_user)):
                raise error.TestFail(
                    'Expected to find a mounted vault for %s' % child_user)
            tab = cr.browser.tabs.New()
            # TODO(achuith): Use a better signal of being logged in, instead of
            # parsing accounts.google.com.
            tab.Navigate('http://accounts.google.com')
            tab.WaitForDocumentReadyStateToBeComplete()
            res = tab.EvaluateJavaScript('''
          var res = '',
          divs = document.getElementsByTagName('div');
          for (var i = 0; i < divs.length; i++) {
            res = divs[i].textContent;
            if (res.search('%s') > 1) {
              break;
            }
          }
          res;
      ''' % child_user)
            if not res:
                raise error.TestFail('No references to %s on accounts page.' %
                                     child_user)
            tab.Close()
    def run_once(self):
        with tempfile.NamedTemporaryFile() as pltp:
            file_utils.download_file(self._PLTP_URL, pltp.name)
            self._password = pltp.read().rstrip()

        with chrome.Chrome(gaia_login=True,
                           username=self._USERNAME,
                           password=self._password) as cr:
            if not cryptohome.is_vault_mounted(user=self._USERNAME):
                raise error.TestFail(
                    'Expected to find a mounted vault for %s' % self._USERNAME)
            tab = cr.browser.tabs.New()
            # TODO(achuith): Use a better signal of being logged in, instead of
            # parsing accounts.google.com.
            tab.Navigate('http://accounts.google.com')
            tab.WaitForDocumentReadyStateToBeComplete()
            res = tab.EvaluateJavaScript('''
                    var res = '',
                        divs = document.getElementsByTagName('div');
                    for (var i = 0; i < divs.length; i++) {
                        res = divs[i].textContent;
                        if (res.search('%s') > 1) {
                            break;
                        }
                    }
                    res;
            ''' % self._USERNAME_DISPLAY)
            if not res:
                raise error.TestFail('No references to %s on accounts page.' %
                                     self._USERNAME_DISPLAY)
            tab.Close()
Пример #5
0
    def run_once(self, username, password):
        """Test body."""
        if not username:
          raise error.TestFail('User not set.')
        if not password:
          raise error.TestFail('Password not set.')

        with chrome.Chrome(gaia_login=True,
                           username=username,
                           password=password) as cr:
            if not cryptohome.is_vault_mounted(
                    user=chrome.NormalizeEmail(username)):
                raise error.TestFail('Expected to find a mounted vault for %s'
                                     % username)
            tab = cr.browser.tabs.New()
            # TODO(achuith): Use a better signal of being logged in, instead of
            # parsing accounts.google.com.
            tab.Navigate('http://accounts.google.com')
            tab.WaitForDocumentReadyStateToBeComplete()
            res = tab.EvaluateJavaScript('''
                    var res = '',
                        divs = document.getElementsByTagName('div');
                    for (var i = 0; i < divs.length; i++) {
                        res = divs[i].textContent;
                        if (res.search('%s') > 1) {
                            break;
                        }
                    }
                    res;
            ''' % username)
            if not res:
                raise error.TestFail('No references to %s on accounts page.'
                                     % username)
            tab.Close()
Пример #6
0
    def run_once(self):
        """Entry point of test"""
        username = ''
        test_file = ''

        with chrome.Chrome() as cr:
            username = cr.username
            if not cryptohome.is_permanent_vault_mounted(username):
                raise error.TestError('Expected to find a mounted vault.')

            test_file =  '/home/.shadow/%s/mount/hello' \
                         % cryptohome.get_user_hash(username)

            logging.info("Test file: ", test_file)
            open(test_file, 'w').close()

        if cryptohome.is_vault_mounted(user=username, allow_fail=True):
            raise error.TestError('Expected to not find a mounted vault.')

        # At this point, the session is not active and the file name is expected
        # to be encrypted again.

        if os.path.isfile(test_file):
            raise error.TestFail('File still visible after end of session.')

        cryptohome.remove_vault(username)
def main(args):
    '''The main function.'''
    if args:
        print('No args for vm_sanity.py')
        return os.EX_USAGE

    start = datetime.datetime.now()
    logging.info('Starting chrome and logging in.')
    is_arc_available = utils.is_arc_available()
    arc_mode = arc_common.ARC_MODE_ENABLED if is_arc_available else None
    with chrome.Chrome(arc_mode=arc_mode) as cr:
        # Check that the cryptohome is mounted.
        # is_vault_mounted throws an exception if it fails.
        logging.info('Checking mounted cryptohome.')
        cryptohome.is_vault_mounted(user=cr.username, allow_fail=False)
        # Navigate to about:blank.
        tab = cr.browser.tabs[0]
        tab.Navigate('about:blank')

        # Evaluate some javascript.
        logging.info('Evaluating JavaScript.')
        if tab.EvaluateJavaScript('2+2') != 4:
            raise TestFail('EvaluateJavaScript failed')

        # ARC test.
        if is_arc_available:
            arc.wait_for_android_process('org.chromium.arc.intent_helper')
            arc.wait_for_adb_ready()
            logging.info('Android booted successfully.')
            if not arc.is_package_installed('android'):
                raise TestFail('"android" system package was not listed by '
                               'Package Manager.')

    if is_arc_available:
        utils.poll_for_condition(lambda: not arc.is_adb_connected(),
                                 timeout=15,
                                 desc='Android container still running after '
                                 'Chrome shutdown.')
    elapsed = datetime.datetime.now() - start
    logging.info('Test succeeded in %s seconds.', elapsed.seconds)
    def run_once(self):
        """
        Runs the test.
        """
        dbus_loop = DBusGMainLoop(set_as_default=True)
        listener = session_manager.SessionSignalListener(gobject.MainLoop())
        listener.listen_for_session_state_change('started')

        logging.info('Logging in...')
        with chrome.Chrome(init_network_controller=True) as cr:
            # Check that Chrome asks session_manager to start a session.
            listener.wait_for_signals(
                desc=('SessionStateChanged "started" D-Bus signal from '
                      'session_manager'),
                timeout=self._SESSION_START_TIMEOUT_SEC)
            logging.info('Successfully logged in as "%s"', cr.username)

            # Check that the user's encrypted home directory was mounted.
            if not cryptohome.is_vault_mounted(user=cr.username,
                                               allow_fail=False):
                raise error.TestFail(
                    'Didn\'t find mounted cryptohome for "%s"' % cr.username)

            # Check that Chrome is able to load a web page.
            cr.browser.platform.SetHTTPServerDirectories(self.bindir)
            url = cr.browser.platform.http_server.UrlOf(
                os.path.join(self.bindir, self._TEST_FILENAME))
            logging.info('Loading %s...', url)

            try:
                tab = cr.browser.tabs.New()
                tab.Navigate(url)
                tab.WaitForDocumentReadyStateToBeComplete()
                content = tab.EvaluateJavaScript(
                    'document.documentElement.innerText')
                if content != self._TEST_CONTENT:
                    raise error.TestFail(
                        'Expected page content "%s" but got "%s"' %
                        (self._TEST_CONTENT, content))
                logging.info('Saw expected content')
            except Exception as e:
                prefix = 'screenshot-%s' % time.strftime('%Y%m%d-%H%M%S')
                logging.info('Got exception; saving screenshot to %s/%s',
                             self._SCREENSHOT_DIR, prefix)
                if not os.path.exists(self._SCREENSHOT_DIR):
                    os.makedirs(self._SCREENSHOT_DIR)
                graphics_utils.take_screenshot(self._SCREENSHOT_DIR, prefix)

                if isinstance(e, error.TestFail):
                    raise e
                else:
                    raise error.TestFail(str(e))
    def setup_case(self,
                   policy_name,
                   policy_value,
                   mandatory_policies={},
                   suggested_policies={},
                   policy_name_is_suggested=False,
                   skip_policy_value_verification=False):
        """Set up and confirm the preconditions of a test case.

        If the AutoTest fake DM Server is used, make a JSON policy blob
        and upload it to the fake DM server.

        Launch Chrome and sign in to Chrome OS. Examine the user's
        cryptohome vault, to confirm user is signed in successfully.

        Open the Policies page, and confirm that it shows the specified
        |policy_name| and has the correct |policy_value|.

        @param policy_name: Name of the policy under test.
        @param policy_value: Expected value for the policy under test.
        @param mandatory_policies: optional dict of mandatory policies
                (not policy_name) in name -> value format.
        @param suggested_policies: optional dict of suggested policies
                (not policy_name) in name -> value format.
        @param policy_name_is_suggested: True if policy_name a suggested policy.
        @param skip_policy_value_verification: True if setup_case should not
                verify that the correct policy value shows on policy page.

        @raises error.TestError if cryptohome vault is not mounted for user.
        @raises error.TestFail if |policy_name| and |policy_value| are not
                shown on the Policies page.
        """
        logging.info('Setting up case: (%s: %s)', policy_name, policy_value)
        logging.info('Mandatory policies: %s', mandatory_policies)
        logging.info('Suggested policies: %s', suggested_policies)

        if self.dms_is_fake:
            if policy_name_is_suggested:
                suggested_policies[policy_name] = policy_value
            else:
                mandatory_policies[policy_name] = policy_value
            self.fake_dm_server.setup_policy(
                self._make_json_blob(mandatory_policies, suggested_policies))

        self._launch_chrome_browser()
        if not cryptohome.is_vault_mounted(user=self.username,
                                           allow_fail=True):
            raise error.TestError('Expected to find a mounted vault for %s.' %
                                  self.username)
        if not skip_policy_value_verification:
            self.verify_policy_value(policy_name, policy_value)
    def _poll_until_user_is_logged_out(self, timeout):
        """Return True when user logs out, False when user remains logged in.

        @returns boolean of user logged out status.

        """
        my_result = utils.poll_for_condition(
            lambda: not cryptohome.is_vault_mounted(user=self.username,
                                                    allow_fail=True),
            exception=None,
            timeout=timeout,
            sleep_interval=2,
            desc='Polling for user to be logged out.')
        return my_result
    def run_once(self):
        test_user = '******'
        test_password = '******'

        user_hash = cryptohome.get_user_hash(test_user)

        # Ensure that the user directory is unmounted and does not exist.
        cryptohome.unmount_vault(test_user)
        cryptohome.remove_vault(test_user)
        if os.path.exists(os.path.join(constants.SHADOW_ROOT, user_hash)):
            raise error.TestFail('Could not remove the test user.')

        # Mount the test user account, which ensures that the vault is
        # created, and that the mount succeeds.
        cryptohome.mount_vault(test_user, test_password, create=True)

        # Test credentials when the user's directory is mounted
        if not cryptohome.test_auth(test_user, test_password):
            raise error.TestFail('Valid credentials should authenticate '
                                 'while mounted.')

        # Make sure that an incorrect password fails
        if cryptohome.test_auth(test_user, 'badpass'):
            raise error.TestFail('Invalid credentials should not authenticate '
                                 'while mounted.')

        # Unmount the directory
        cryptohome.unmount_vault(test_user)
        # Ensure that the user directory is not mounted
        if cryptohome.is_vault_mounted(user=test_user, allow_fail=True):
            raise error.TestFail('Cryptohome did not unmount the user.')

        # Test valid credentials when the user's directory is not mounted
        if not cryptohome.test_auth(test_user, test_password):
            raise error.TestFail('Valid credentials should authenticate '
                                 ' while mounted.')

        # Test invalid credentials fails while not mounted.
        if cryptohome.test_auth(test_user, 'badpass'):
            raise error.TestFail('Invalid credentials should not authenticate '
                                 'when unmounted.')

        # Re-mount existing test user vault, verifying that the mount succeeds.
        cryptohome.mount_vault(test_user, test_password)

        # Finally, unmount and destroy the vault again.
        cryptohome.unmount_vault(test_user)
        cryptohome.remove_vault(test_user)
        if os.path.exists(os.path.join(constants.SHADOW_ROOT, user_hash)):
            raise error.TestFail('Could not destroy the vault.')
    def run_once(self):
        """Run the power management policy tests."""
        self._setup_lock_policy()
        with self._create_chrome() as cr:
            utils.poll_for_condition(
                    lambda: cr.login_status['isScreenLocked'],
                            exception=error.TestFail('User is not locked'),
                            timeout=self._screen_lock_delay*2,
                            sleep_interval=1,
                            desc='Expects to find Chrome locked.')

        self._setup_logout_policy()
        with self._create_chrome() as cr:
            utils.poll_for_condition(
                    lambda: not cryptohome.is_vault_mounted(user=self.username,
                            allow_fail=True),
                            exception=error.TestFail('User is not logged out'),
                            timeout=self._screen_logout_delay*2,
                            sleep_interval=1,
                            desc='Expects to find user logged out.')
Пример #13
0
    def setup_case(self, policy_name, policy_value, policies_json):
        """Set up and confirm the preconditions of a test case.

        If the AutoTest fake DM Server is initialized, make a policy blob
        from |policies_json|, and upload it to the fake server.

        Launch a chrome browser, and sign in to Chrome OS. Examine the user's
        cryptohome vault, to confirm it signed in successfully.

        Open the Policies page, and confirm that it shows the specified
        |policy_name| and has the correct |policy_value|.

        @param policy_name: Name of the policy under test.
        @param policy_value: Expected value to appear on chrome://policy page.
        @param policies_json: JSON string to set up the fake DMS policy value.

        @raises error.TestError if cryptohome vault is not mounted for user.
        @raises error.TestFail if |policy_name| and |policy_value| are not
                shown on the Policies page.

        """
        # Set up policy on AutoTest DM Server only if initialized.
        if self.env == 'dm-fake':
            self.setup_policy(self._make_json_blob(policies_json))

        self._launch_chrome_browser()
        tab = self.navigate_to_url('chrome://policy')
        if not cryptohome.is_vault_mounted(user=self.username,
                                           allow_fail=True):
            raise error.TestError('Expected to find a mounted vault for %s.'
                                  % self.username)
        value_shown = self._get_policy_value_shown(tab, policy_name)
        if not self._policy_value_matches_shown(policy_value, value_shown):
            raise error.TestFail('Policy value shown is not correct: %s '
                                 '(expected: %s)' %
                                 (value_shown, policy_value))
        tab.Close()
 def _validate(self):
     # Validate if the environment is expected.
     if not cryptohome.is_vault_mounted(
             user=chrome.NormalizeEmail(self.username)):
         raise error.TestFail('Expected to find a mounted vault for %s' %
                              self.username)
     tab = self.cr.browser.tabs.New()
     tab.Navigate('http://accounts.google.com')
     tab.WaitForDocumentReadyStateToBeComplete()
     res = tab.EvaluateJavaScript('''
             var res = '',
                 divs = document.getElementsByTagName('div');
             for (var i = 0; i < divs.length; i++) {
                 res = divs[i].textContent;
                 if (res.search('%s') > 1) {
                 break;
                 }
             }
             res;
     ''' % self.username)
     if not res:
         raise error.TestFail('No references to %s on accounts page.' %
                              self.username)
     tab.Close()
    def _create_chrome(self,
                       enroll=False,
                       auto_login=True,
                       extra_chrome_flags=[],
                       init_network_controller=False):
        """
        Create a Chrome object. Enroll and/or sign in.

        Function results in self.cr set as the Chrome object.

        @param enroll: enroll the device.
        @param auto_login: sign in to chromeos.
        @param extra_chrome_flags: list of flags to add.
        @param init_network_controller: whether to init network controller.
        """
        extra_flags = self._initialize_chrome_extra_flags(
        ) + extra_chrome_flags

        logging.info('Chrome Browser Arguments:')
        logging.info('  extra_browser_args: %s', extra_flags)
        logging.info('  username: %s', self.username)
        logging.info('  password: %s', self.password)
        logging.info('  gaia_login: %s', not self.dms_is_fake)

        if enroll:
            self.cr = chrome.Chrome(auto_login=False,
                                    extra_browser_args=extra_flags,
                                    expect_policy_fetch=True)
            if self.dms_is_fake:
                enrollment.EnterpriseFakeEnrollment(self.cr.browser,
                                                    self.username,
                                                    self.password,
                                                    self.gaia_id,
                                                    auto_login=auto_login)
            else:
                enrollment.EnterpriseEnrollment(self.cr.browser,
                                                self.username,
                                                self.password,
                                                auto_login=auto_login)

        elif auto_login:
            self.cr = chrome.Chrome(
                extra_browser_args=extra_flags,
                username=self.username,
                password=self.password,
                gaia_login=not self.dms_is_fake,
                disable_gaia_services=self.dms_is_fake,
                autotest_ext=True,
                init_network_controller=init_network_controller,
                expect_policy_fetch=True)
        else:
            self.cr = chrome.Chrome(auto_login=False,
                                    extra_browser_args=extra_flags,
                                    disable_gaia_services=self.dms_is_fake,
                                    autotest_ext=True,
                                    expect_policy_fetch=True)

        if auto_login:
            if not cryptohome.is_vault_mounted(user=self.username,
                                               allow_fail=True):
                raise error.TestError(
                    'Expected to find a mounted vault for %s.' % self.username)
    def run_once(self):
        with chrome.Chrome(logged_in=self._logged_in) as cr:
            username = (cr.username
                        if self._logged_in else cryptohome.GUEST_USER_NAME)
            """Check permissions within cryptohome for anything too permissive.
            """
            passes = []

            homepath = "/home/chronos"
            passes.append(self.check_owner_mode(homepath, "chronos", 0755))

            user_mountpt = cryptohome.user_path(username)
            passes.append(
                self.check_owner_mode(user_mountpt, "chronos",
                                      self._HOMEDIR_MODE))

            # TODO(benchan): Refactor the following code to use some helper
            # functions instead of find commands.

            # An array of shell commands, each representing a test that
            # passes if it emits no output. The first test is the main one.
            # In general, writable by anyone else is bad, as is owned by
            # anyone else. Any exceptions to that are pruned out of the
            # first test and checked individually by subsequent tests.
            cmds = [
                (
                    'find -L "%s" -path "%s" -o '
                    # Avoid false-positives on SingletonLock, SingletonCookie, etc.
                    ' \\( -name "Singleton*" -a -type l \\) -o '
                    ' -path "%s/user" -prune -o '
                    ' -path "%s/Downloads" -prune -o '
                    ' -path "%s/flimflam" -prune -o '
                    ' -path "%s/shill" -prune -o '
                    ' -path "%s/.chaps" -prune -o '
                    ' -path "%s/u-*" -prune -o '
                    ' -path "%s/crash" -prune -o '
                    ' \\( -perm /022 -o \\! -user chronos \\) -ls') %
                (homepath, homepath, homepath, user_mountpt, user_mountpt,
                 user_mountpt, user_mountpt, homepath, homepath),
                # /home/chronos/user and /home/chronos/user/Downloads are owned
                # by the chronos-access group and with a group execute
                # permission.
                'find -L "%s" -maxdepth 0 \\( \\! -perm 710 '
                '-o \\! -user chronos -o \\! -group chronos-access \\) -ls' %
                user_mountpt,
                'find -L "%s/Downloads" -maxdepth 0 \\( \\! -perm 710 '
                '-o \\! -user chronos -o \\! -group chronos-access \\) -ls' %
                user_mountpt,
                'find -L "%s/flimflam" \\( -perm /077 -o \\! -user root \\) -ls'
                % user_mountpt,
                'find -L "%s/shill" \\( -perm /077 -o \\! -user root \\) -ls' %
                user_mountpt,
                'find -L "%s/.chaps -name auth_data_salt -prune -o '
                '\\! -user chaps -o \\! -group chronos-access -o -perm /027 -ls'
                % user_mountpt,
                'find -L "%s/.chaps -name auth_data_salt -a '
                '\\( \\! -user root -o -perm /077 \\) -ls' % user_mountpt,
            ]

            for cmd in cmds:
                cmd_output = utils.system_output(cmd, ignore_status=True)
                if cmd_output:
                    passes.append(False)
                    logging.error(cmd_output)

            # This next section only applies if we have a real vault mounted
            # (ie, not a BWSI tmpfs).
            if cryptohome.is_vault_mounted(
                    username,
                    device_regex=constants.CRYPTOHOME_DEV_REGEX_REGULAR_USER):
                # Also check the permissions of the underlying vault and
                # supporting directory structure.
                vaultpath = cryptohome.get_mounted_vault_devices(username)[0]

                passes.append(self.check_owner_mode(vaultpath, "root", 0700))
                passes.append(
                    self.check_owner_mode(vaultpath + "/../master.0", "root",
                                          0600))
                passes.append(
                    self.check_owner_mode(vaultpath + "/../", "root", 0700))
                passes.append(
                    self.check_owner_mode(vaultpath + "/../../", "root", 0700))

            if False in passes:
                raise error.TestFail(
                    'Bad permissions found on cryptohome files')
Пример #17
0
    def _create_chrome(self,
                       enroll=False,
                       auto_login=True,
                       arc_mode=False,
                       init_network_controller=False,
                       disable_default_apps=True,
                       extension_paths=[],
                       extra_chrome_flags=[]):
        """
        Create a Chrome object. Enroll and/or sign in.

        Function results in self.cr set as the Chrome object.

        @param enroll: enroll the device.
        @param auto_login: sign in to chromeos.
        @param arc_mode: enable arc mode.
        @param extension_paths: list of extensions to install.
        @param init_network_controller: whether to init network controller.
        @param extra_chrome_flags: list of flags to add.
        """
        extra_flags = self._initialize_chrome_extra_flags(
        ) + extra_chrome_flags

        logging.info('Chrome Browser Arguments:')
        logging.info('  extra_browser_args: %s', extra_flags)
        logging.info('  username: %s', self.username)
        logging.info('  password: %s', self.password)
        logging.info('  gaia_login: %s', not self.dms_is_fake)

        if enroll:
            self.cr = chrome.Chrome(auto_login=False,
                                    extra_browser_args=extra_flags,
                                    extension_paths=extension_paths,
                                    expect_policy_fetch=True)
            if self.dms_is_fake:
                if self._kiosk_mode:
                    # This try is needed for kiosk; without it the test fails
                    # in telemtry code in _WaitForEnterpriseWebview. Webview
                    # never loads since it's kiosk.
                    # TODO(rzakarian): Try to modify telemetry code to not
                    # wait for Webview when in kiosk mode.
                    # http://crbug.com/934876.
                    try:
                        enrollment.EnterpriseFakeEnrollment(
                            self.cr.browser,
                            self.username,
                            self.password,
                            self.gaia_id,
                            auto_login=auto_login)
                    except TimeoutException:
                        pass
                else:
                    enrollment.EnterpriseFakeEnrollment(self.cr.browser,
                                                        self.username,
                                                        self.password,
                                                        self.gaia_id,
                                                        auto_login=auto_login)
            else:
                enrollment.EnterpriseEnrollment(self.cr.browser,
                                                self.username,
                                                self.password,
                                                auto_login=auto_login)

        elif auto_login:
            if arc_mode:
                self.cr = chrome.Chrome(extension_paths=extension_paths,
                                        username=self.username,
                                        password=self.password,
                                        arc_mode=arc_mode,
                                        disable_gaia_services=False,
                                        disable_arc_opt_in=False,
                                        enterprise_arc_test=True,
                                        extra_browser_args=extra_flags)

            else:
                self.cr = chrome.Chrome(
                    extra_browser_args=extra_flags,
                    username=self.username,
                    password=self.password,
                    gaia_login=not self.dms_is_fake,
                    disable_gaia_services=self.dms_is_fake,
                    autotest_ext=True,
                    init_network_controller=init_network_controller,
                    expect_policy_fetch=True,
                    extension_paths=extension_paths,
                    disable_default_apps=disable_default_apps)
        else:
            self.cr = chrome.Chrome(auto_login=False,
                                    extra_browser_args=extra_flags,
                                    disable_gaia_services=self.dms_is_fake,
                                    autotest_ext=True,
                                    expect_policy_fetch=True)

        # Used by arc.py to determine the state of the chrome obj
        self.initialized = True
        if auto_login:
            if not cryptohome.is_vault_mounted(user=self.username,
                                               allow_fail=True):
                raise error.TestError(
                    'Expected to find a mounted vault for %s.' % self.username)