ChooseLockGeneric.java revision 40ca78f6f3d75897a1a5fd3ec999f487430d4b40
1/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.settings;
18
19import android.accessibilityservice.AccessibilityServiceInfo;
20import android.app.Activity;
21import android.app.ActivityManagerNative;
22import android.app.PendingIntent;
23import android.app.admin.DevicePolicyManager;
24import android.content.Context;
25import android.content.Intent;
26import android.content.pm.UserInfo;
27import android.os.Bundle;
28import android.os.Process;
29import android.os.RemoteException;
30import android.os.UserHandle;
31import android.os.UserManager;
32import android.preference.Preference;
33import android.preference.PreferenceScreen;
34import android.security.KeyStore;
35import android.util.EventLog;
36import android.util.MutableBoolean;
37import android.view.LayoutInflater;
38import android.view.View;
39import android.view.ViewGroup;
40import android.view.accessibility.AccessibilityManager;
41import android.widget.ListView;
42
43import com.android.internal.widget.LockPatternUtils;
44
45import java.util.List;
46
47public class ChooseLockGeneric extends SettingsActivity {
48
49    @Override
50    public Intent getIntent() {
51        Intent modIntent = new Intent(super.getIntent());
52        modIntent.putExtra(EXTRA_SHOW_FRAGMENT, ChooseLockGenericFragment.class.getName());
53        return modIntent;
54    }
55
56    @Override
57    protected boolean isValidFragment(String fragmentName) {
58        if (ChooseLockGenericFragment.class.getName().equals(fragmentName)) return true;
59        return false;
60    }
61
62    public static class InternalActivity extends ChooseLockGeneric {
63    }
64
65    public static class ChooseLockGenericFragment extends SettingsPreferenceFragment {
66        private static final int MIN_PASSWORD_LENGTH = 4;
67        private static final String KEY_UNLOCK_BACKUP_INFO = "unlock_backup_info";
68        private static final String KEY_UNLOCK_SET_OFF = "unlock_set_off";
69        private static final String KEY_UNLOCK_SET_NONE = "unlock_set_none";
70        private static final String KEY_UNLOCK_SET_BIOMETRIC_WEAK = "unlock_set_biometric_weak";
71        private static final String KEY_UNLOCK_SET_PIN = "unlock_set_pin";
72        private static final String KEY_UNLOCK_SET_PASSWORD = "unlock_set_password";
73        private static final String KEY_UNLOCK_SET_PATTERN = "unlock_set_pattern";
74        private static final int CONFIRM_EXISTING_REQUEST = 100;
75        private static final int FALLBACK_REQUEST = 101;
76        private static final int ENABLE_ENCRYPTION_REQUEST = 102;
77        private static final String PASSWORD_CONFIRMED = "password_confirmed";
78        private static final String CONFIRM_CREDENTIALS = "confirm_credentials";
79        private static final String WAITING_FOR_CONFIRMATION = "waiting_for_confirmation";
80        private static final String FINISH_PENDING = "finish_pending";
81        public static final String MINIMUM_QUALITY_KEY = "minimum_quality";
82        public static final String ENCRYPT_REQUESTED_QUALITY = "encrypt_requested_quality";
83        public static final String ENCRYPT_REQUESTED_DISABLED = "encrypt_requested_disabled";
84
85        private static final boolean ALWAY_SHOW_TUTORIAL = true;
86
87        private ChooseLockSettingsHelper mChooseLockSettingsHelper;
88        private DevicePolicyManager mDPM;
89        private KeyStore mKeyStore;
90        private boolean mPasswordConfirmed = false;
91        private boolean mWaitingForConfirmation = false;
92        private boolean mFinishPending = false;
93        private int mEncryptionRequestQuality;
94        private boolean mEncryptionRequestDisabled;
95
96        @Override
97        public void onCreate(Bundle savedInstanceState) {
98            super.onCreate(savedInstanceState);
99
100            mDPM = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
101            mKeyStore = KeyStore.getInstance();
102            mChooseLockSettingsHelper = new ChooseLockSettingsHelper(this.getActivity());
103
104            // Defaults to needing to confirm credentials
105            final boolean confirmCredentials = getActivity().getIntent()
106                .getBooleanExtra(CONFIRM_CREDENTIALS, true);
107            if (getActivity() instanceof ChooseLockGeneric.InternalActivity) {
108                mPasswordConfirmed = !confirmCredentials;
109            }
110
111            if (savedInstanceState != null) {
112                mPasswordConfirmed = savedInstanceState.getBoolean(PASSWORD_CONFIRMED);
113                mWaitingForConfirmation = savedInstanceState.getBoolean(WAITING_FOR_CONFIRMATION);
114                mFinishPending = savedInstanceState.getBoolean(FINISH_PENDING);
115                mEncryptionRequestQuality = savedInstanceState.getInt(ENCRYPT_REQUESTED_QUALITY);
116                mEncryptionRequestDisabled = savedInstanceState.getBoolean(
117                        ENCRYPT_REQUESTED_DISABLED);
118            }
119
120            if (mPasswordConfirmed) {
121                updatePreferencesOrFinish();
122            } else if (!mWaitingForConfirmation) {
123                ChooseLockSettingsHelper helper =
124                        new ChooseLockSettingsHelper(this.getActivity(), this);
125                if (!helper.launchConfirmationActivity(CONFIRM_EXISTING_REQUEST, null, null)) {
126                    mPasswordConfirmed = true; // no password set, so no need to confirm
127                    updatePreferencesOrFinish();
128                } else {
129                    mWaitingForConfirmation = true;
130                }
131            }
132        }
133
134        @Override
135        public void onResume() {
136            super.onResume();
137            if (mFinishPending) {
138                mFinishPending = false;
139                finish();
140            }
141        }
142
143        @Override
144        public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
145                Preference preference) {
146            final String key = preference.getKey();
147            boolean handled = true;
148
149            EventLog.writeEvent(EventLogTags.LOCK_SCREEN_TYPE, key);
150
151            if (KEY_UNLOCK_SET_OFF.equals(key)) {
152                updateUnlockMethodAndFinish(
153                        DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, true);
154            } else if (KEY_UNLOCK_SET_NONE.equals(key)) {
155                updateUnlockMethodAndFinish(
156                        DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED, false);
157            } else if (KEY_UNLOCK_SET_BIOMETRIC_WEAK.equals(key)) {
158                maybeEnableEncryption(
159                        DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK, false);
160            }else if (KEY_UNLOCK_SET_PATTERN.equals(key)) {
161                maybeEnableEncryption(
162                        DevicePolicyManager.PASSWORD_QUALITY_SOMETHING, false);
163            } else if (KEY_UNLOCK_SET_PIN.equals(key)) {
164                maybeEnableEncryption(
165                        DevicePolicyManager.PASSWORD_QUALITY_NUMERIC, false);
166            } else if (KEY_UNLOCK_SET_PASSWORD.equals(key)) {
167                maybeEnableEncryption(
168                        DevicePolicyManager.PASSWORD_QUALITY_ALPHABETIC, false);
169            } else {
170                handled = false;
171            }
172            return handled;
173        }
174
175        /**
176         * If the device has encryption already enabled, then ask the user if they
177         * also want to encrypt the phone with this password.
178         *
179         * @param quality
180         * @param disabled
181         */
182        private void maybeEnableEncryption(int quality, boolean disabled) {
183            if (Process.myUserHandle().isOwner() && LockPatternUtils.isDeviceEncryptionEnabled()) {
184                mEncryptionRequestQuality = quality;
185                mEncryptionRequestDisabled = disabled;
186                Intent intent = EncryptionInterstitial.createStartIntent(getActivity(), quality);
187                startActivityForResult(intent, ENABLE_ENCRYPTION_REQUEST);
188            } else {
189                updateUnlockMethodAndFinish(quality, disabled);
190            }
191        }
192
193        @Override
194        public View onCreateView(LayoutInflater inflater, ViewGroup container,
195                Bundle savedInstanceState) {
196            View v = super.onCreateView(inflater, container, savedInstanceState);
197            final boolean onlyShowFallback = getActivity().getIntent()
198                    .getBooleanExtra(LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK, false);
199            if (onlyShowFallback) {
200                View header = v.inflate(getActivity(),
201                        R.layout.weak_biometric_fallback_header, null);
202                ((ListView) v.findViewById(android.R.id.list)).addHeaderView(header, null, false);
203            }
204
205            return v;
206        }
207
208        @Override
209        public void onActivityResult(int requestCode, int resultCode, Intent data) {
210            super.onActivityResult(requestCode, resultCode, data);
211            mWaitingForConfirmation = false;
212            if (requestCode == CONFIRM_EXISTING_REQUEST && resultCode == Activity.RESULT_OK) {
213                mPasswordConfirmed = true;
214                updatePreferencesOrFinish();
215            } else if (requestCode == FALLBACK_REQUEST) {
216                mChooseLockSettingsHelper.utils().deleteTempGallery();
217                getActivity().setResult(resultCode);
218                finish();
219            } else if (requestCode == ENABLE_ENCRYPTION_REQUEST
220                    && resultCode == Activity.RESULT_OK) {
221                updateUnlockMethodAndFinish(mEncryptionRequestQuality, mEncryptionRequestDisabled);
222            } else {
223                getActivity().setResult(Activity.RESULT_CANCELED);
224                finish();
225            }
226        }
227
228        @Override
229        public void onSaveInstanceState(Bundle outState) {
230            super.onSaveInstanceState(outState);
231            // Saved so we don't force user to re-enter their password if configuration changes
232            outState.putBoolean(PASSWORD_CONFIRMED, mPasswordConfirmed);
233            outState.putBoolean(WAITING_FOR_CONFIRMATION, mWaitingForConfirmation);
234            outState.putBoolean(FINISH_PENDING, mFinishPending);
235            outState.putInt(ENCRYPT_REQUESTED_QUALITY, mEncryptionRequestQuality);
236            outState.putBoolean(ENCRYPT_REQUESTED_DISABLED, mEncryptionRequestDisabled);
237        }
238
239        private void updatePreferencesOrFinish() {
240            Intent intent = getActivity().getIntent();
241            int quality = intent.getIntExtra(LockPatternUtils.PASSWORD_TYPE_KEY, -1);
242            if (quality == -1) {
243                // If caller didn't specify password quality, show UI and allow the user to choose.
244                quality = intent.getIntExtra(MINIMUM_QUALITY_KEY, -1);
245                MutableBoolean allowBiometric = new MutableBoolean(false);
246                quality = upgradeQuality(quality, allowBiometric);
247                final PreferenceScreen prefScreen = getPreferenceScreen();
248                if (prefScreen != null) {
249                    prefScreen.removeAll();
250                }
251                addPreferencesFromResource(R.xml.security_settings_picker);
252                disableUnusablePreferences(quality, allowBiometric);
253                updatePreferenceSummaryIfNeeded();
254            } else {
255                updateUnlockMethodAndFinish(quality, false);
256            }
257        }
258
259        /** increases the quality if necessary, and returns whether biometric is allowed */
260        private int upgradeQuality(int quality, MutableBoolean allowBiometric) {
261            quality = upgradeQualityForDPM(quality);
262            quality = upgradeQualityForKeyStore(quality);
263            return quality;
264        }
265
266        private int upgradeQualityForDPM(int quality) {
267            // Compare min allowed password quality
268            int minQuality = mDPM.getPasswordQuality(null);
269            if (quality < minQuality) {
270                quality = minQuality;
271            }
272            return quality;
273        }
274
275        private int upgradeQualityForKeyStore(int quality) {
276            if (!mKeyStore.isEmpty()) {
277                if (quality < CredentialStorage.MIN_PASSWORD_QUALITY) {
278                    quality = CredentialStorage.MIN_PASSWORD_QUALITY;
279                }
280            }
281            return quality;
282        }
283
284        /***
285         * Disables preferences that are less secure than required quality.
286         *
287         * @param quality the requested quality.
288         */
289        private void disableUnusablePreferences(final int quality, MutableBoolean allowBiometric) {
290            final PreferenceScreen entries = getPreferenceScreen();
291            final boolean onlyShowFallback = getActivity().getIntent()
292                    .getBooleanExtra(LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK, false);
293            final boolean weakBiometricAvailable =
294                    mChooseLockSettingsHelper.utils().isBiometricWeakInstalled();
295
296            // if there are multiple users, disable "None" setting
297            UserManager mUm = (UserManager) getSystemService(Context.USER_SERVICE);
298            List<UserInfo> users = mUm.getUsers(true);
299            final boolean singleUser = users.size() == 1;
300
301            for (int i = entries.getPreferenceCount() - 1; i >= 0; --i) {
302                Preference pref = entries.getPreference(i);
303                if (pref instanceof PreferenceScreen) {
304                    final String key = ((PreferenceScreen) pref).getKey();
305                    boolean enabled = true;
306                    boolean visible = true;
307                    if (KEY_UNLOCK_SET_OFF.equals(key)) {
308                        enabled = quality <= DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
309                        visible = singleUser; // don't show when there's more than 1 user
310                    } else if (KEY_UNLOCK_SET_NONE.equals(key)) {
311                        enabled = quality <= DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED;
312                    } else if (KEY_UNLOCK_SET_BIOMETRIC_WEAK.equals(key)) {
313                        enabled = quality <= DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK ||
314                                allowBiometric.value;
315                        visible = weakBiometricAvailable; // If not available, then don't show it.
316                    } else if (KEY_UNLOCK_SET_PATTERN.equals(key)) {
317                        enabled = quality <= DevicePolicyManager.PASSWORD_QUALITY_SOMETHING;
318                    } else if (KEY_UNLOCK_SET_PIN.equals(key)) {
319                        enabled = quality <= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC_COMPLEX;
320                    } else if (KEY_UNLOCK_SET_PASSWORD.equals(key)) {
321                        enabled = quality <= DevicePolicyManager.PASSWORD_QUALITY_COMPLEX;
322                    }
323                    if (!visible || (onlyShowFallback && !allowedForFallback(key))) {
324                        entries.removePreference(pref);
325                    } else if (!enabled) {
326                        pref.setSummary(R.string.unlock_set_unlock_disabled_summary);
327                        pref.setEnabled(false);
328                    }
329                }
330            }
331        }
332
333        private void updatePreferenceSummaryIfNeeded() {
334            if (LockPatternUtils.isDeviceEncrypted()) {
335                return;
336            }
337
338            if (AccessibilityManager.getInstance(getActivity()).getEnabledAccessibilityServiceList(
339                    AccessibilityServiceInfo.FEEDBACK_ALL_MASK).isEmpty()) {
340                return;
341            }
342
343            CharSequence summary = getString(R.string.secure_lock_encryption_warning);
344
345            PreferenceScreen screen = getPreferenceScreen();
346            final int preferenceCount = screen.getPreferenceCount();
347            for (int i = 0; i < preferenceCount; i++) {
348                Preference preference = screen.getPreference(i);
349                switch (preference.getKey()) {
350                    case KEY_UNLOCK_SET_PATTERN:
351                    case KEY_UNLOCK_SET_PIN:
352                    case KEY_UNLOCK_SET_PASSWORD: {
353                        preference.setSummary(summary);
354                    } break;
355                }
356            }
357        }
358
359        /**
360         * Check whether the key is allowed for fallback (e.g. bio sensor). Returns true if it's
361         * supported as a backup.
362         *
363         * @param key
364         * @return true if allowed
365         */
366        private boolean allowedForFallback(String key) {
367            return KEY_UNLOCK_BACKUP_INFO.equals(key)  ||
368                    KEY_UNLOCK_SET_PATTERN.equals(key) || KEY_UNLOCK_SET_PIN.equals(key);
369        }
370
371        private Intent getBiometricSensorIntent() {
372            Intent fallBackIntent = new Intent().setClass(getActivity(),
373                    ChooseLockGeneric.InternalActivity.class);
374            fallBackIntent.putExtra(LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK, true);
375            fallBackIntent.putExtra(CONFIRM_CREDENTIALS, false);
376            fallBackIntent.putExtra(EXTRA_SHOW_FRAGMENT_TITLE,
377                    R.string.backup_lock_settings_picker_title);
378
379            boolean showTutorial = ALWAY_SHOW_TUTORIAL ||
380                    !mChooseLockSettingsHelper.utils().isBiometricWeakEverChosen();
381            Intent intent = new Intent();
382            intent.setClassName("com.android.facelock", "com.android.facelock.SetupIntro");
383            intent.putExtra("showTutorial", showTutorial);
384            PendingIntent pending = PendingIntent.getActivity(getActivity(), 0, fallBackIntent, 0);
385            intent.putExtra("PendingIntent", pending);
386            return intent;
387        }
388
389        /**
390         * Invokes an activity to change the user's pattern, password or PIN based on given quality
391         * and minimum quality specified by DevicePolicyManager. If quality is
392         * {@link DevicePolicyManager#PASSWORD_QUALITY_UNSPECIFIED}, password is cleared.
393         *
394         * @param quality the desired quality. Ignored if DevicePolicyManager requires more security
395         * @param disabled whether or not to show LockScreen at all. Only meaningful when quality is
396         * {@link DevicePolicyManager#PASSWORD_QUALITY_UNSPECIFIED}
397         */
398        void updateUnlockMethodAndFinish(int quality, boolean disabled) {
399            // Sanity check. We should never get here without confirming user's existing password.
400            if (!mPasswordConfirmed) {
401                throw new IllegalStateException("Tried to update password without confirming it");
402            }
403
404            final boolean isFallback = getActivity().getIntent()
405                .getBooleanExtra(LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK, false);
406
407            quality = upgradeQuality(quality, null);
408
409            if (quality >= DevicePolicyManager.PASSWORD_QUALITY_NUMERIC) {
410                int minLength = mDPM.getPasswordMinimumLength(null);
411                if (minLength < MIN_PASSWORD_LENGTH) {
412                    minLength = MIN_PASSWORD_LENGTH;
413                }
414                final int maxLength = mDPM.getPasswordMaximumLength(quality);
415                Intent intent = new Intent().setClass(getActivity(), ChooseLockPassword.class);
416                intent.putExtra(LockPatternUtils.PASSWORD_TYPE_KEY, quality);
417                intent.putExtra(ChooseLockPassword.PASSWORD_MIN_KEY, minLength);
418                intent.putExtra(ChooseLockPassword.PASSWORD_MAX_KEY, maxLength);
419                intent.putExtra(CONFIRM_CREDENTIALS, false);
420                intent.putExtra(LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK,
421                        isFallback);
422                if (isFallback) {
423                    startActivityForResult(intent, FALLBACK_REQUEST);
424                    return;
425                } else {
426                    mFinishPending = true;
427                    intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
428                    startActivity(intent);
429                }
430            } else if (quality == DevicePolicyManager.PASSWORD_QUALITY_SOMETHING) {
431                Intent intent = new Intent(getActivity(), ChooseLockPattern.class);
432                intent.putExtra("key_lock_method", "pattern");
433                intent.putExtra(CONFIRM_CREDENTIALS, false);
434                intent.putExtra(LockPatternUtils.LOCKSCREEN_BIOMETRIC_WEAK_FALLBACK,
435                        isFallback);
436                if (isFallback) {
437                    startActivityForResult(intent, FALLBACK_REQUEST);
438                    return;
439                } else {
440                    mFinishPending = true;
441                    intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
442                    startActivity(intent);
443                }
444            } else if (quality == DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK) {
445                Intent intent = getBiometricSensorIntent();
446                mFinishPending = true;
447                startActivity(intent);
448            } else if (quality == DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED) {
449                mChooseLockSettingsHelper.utils().clearLock(false);
450                mChooseLockSettingsHelper.utils().setLockScreenDisabled(disabled);
451                getActivity().setResult(Activity.RESULT_OK);
452                finish();
453            } else {
454                finish();
455            }
456        }
457
458        @Override
459        protected int getHelpResource() {
460            return R.string.help_url_choose_lockscreen;
461        }
462
463    }
464}
465