AndroidQ SystemUI之Keyguard强认证机制StrongAuth

本文深入解析Android系统中强认证超时机制的工作原理,包括密码、PIN码、图案解锁与指纹、面部解锁的关系,以及如何在超时后强制用户进行强认证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本篇文章分析一下Android系统的强认证机制,Google官方术语中,password/pin/pattern这三种类型的屏幕锁称为strong method authentication,强方法认证,而像指纹/面部解锁的方式则称作辅助的认证方式(weak auth)。

Google认为指纹/面部解锁的安全性不如password/pin/pattern,在某些情况下无法使用指纹//面部解锁,例如设备重启,失败次数过多,强认证超时StrongAuthTimeOut,我们就来分析一下强认证超时引起的无法使用指纹//面部解锁流程

以password解锁为例,我们输入password之后点击确认进去密码匹配调用链为:

KeyguardAbsKeyInputView.verifyPasswordAndUnlock
->LockPatternChecker.checkPassword
->LockPatternUtils.checkPassword
->LockPatternUtils.checkCredential
->LockSettingsService.checkCredential
->LockSettingsService.doVerifyCredential
->LockSettingsService.spBasedDoVerifyCredential
->SyntheticPasswordManager.unwrapPasswordBasedSyntheticPassword
->native层GateKeeper
->tee GateKeeper(tee中进行密码匹配返回到FW中的respose)
public static final int RESPONSE_ERROR = -1;
public static final int RESPONSE_OK = 0;
public static final int RESPONSE_RETRY = 1;

StrongAuthTracker

了解了解锁大致流程之后我们来看下StrongAuthTracker这个类,此类定义在LockPatternUtils中,它里面定义了很多重要的flag常量

public static class StrongAuthTracker {

        /**
         * Strong authentication is not required.
         */
        public static final int STRONG_AUTH_NOT_REQUIRED = 0x0;

        /**
         * Strong authentication is required because the user has not authenticated since boot.
         */
        public static final int STRONG_AUTH_REQUIRED_AFTER_BOOT = 0x1;

        /**
         * Strong authentication is required because a device admin has requested it.
         */
        public static final int STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW = 0x2;

        /**
         * Some authentication is required because the user has temporarily disabled trust.
         */
        public static final int SOME_AUTH_REQUIRED_AFTER_USER_REQUEST = 0x4;

        /**
         * Strong authentication is required because the user has been locked out after too many
         * attempts.
         */
        public static final int STRONG_AUTH_REQUIRED_AFTER_LOCKOUT = 0x8;

        /**
         * Strong authentication is required because it hasn't been used for a time required by
         * a device admin.
         */
        public static final int STRONG_AUTH_REQUIRED_AFTER_TIMEOUT = 0x10;

        /**
         * Strong authentication is required because the user has triggered lockdown.
         */
        public static final int STRONG_AUTH_REQUIRED_AFTER_USER_LOCKDOWN = 0x20;

不需要强认证解锁:STRONG_AUTH_NOT_REQUIRED

重启之后需要强认证:STRONG_AUTH_REQUIRED_AFTER_BOOT

设备管理者要求强认证:STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW

强认证超时:STRONG_AUTH_REQUIRED_AFTER_TIMEOUT

设置Alarm强认证解锁timeout

当底层密码匹配成功返回RESPONSE_OK后会更新Alarm超时强认证解锁timeout
LockSettingsService.doVerifyCredential

private VerifyCredentialResponse doVerifyCredential(byte[] credential, int credentialType,
            boolean hasChallenge, long challenge, int userId,
            ICheckCredentialProgressCallback progressCallback) throws RemoteException {
			.....
         if (response.getResponseCode() == VerifyCredentialResponse.RESPONSE_OK) {
            mStrongAuth.reportSuccessfulStrongAuthUnlock(userId);
            ...
        }
        ......
}

mStrongAuth类型为LockSettingsStrongAuth,这个类主要作为追踪强认证的请求变化

reportSuccessfulStrongAuthUnlock

public void reportSuccessfulStrongAuthUnlock(int userId) {
        final int argNotUsed = 0;
        mHandler.obtainMessage(MSG_SCHEDULE_STRONG_AUTH_TIMEOUT, userId, argNotUsed).sendToTarget();
    }

发送handler消息

MSG_SCHEDULE_STRONG_AUTH_TIMEOUT

 private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                ....
                case MSG_SCHEDULE_STRONG_AUTH_TIMEOUT:
                    handleScheduleStrongAuthTimeout(msg.arg1);
                    break;
            }
        }
    };
    

handleScheduleStrongAuthTimeout

private void handleScheduleStrongAuthTimeout(int userId) {
        final DevicePolicyManager dpm =
                (DevicePolicyManager) mContext.getSystemService(Context.DEVICE_POLICY_SERVICE);
        long when = SystemClock.elapsedRealtime() + dpm.getRequiredStrongAuthTimeout(null, userId);
        // cancel current alarm listener for the user (if there was one)
        StrongAuthTimeoutAlarmListener alarm = mStrongAuthTimeoutAlarmListenerForUser.get(userId);
        if (alarm != null) {
            mAlarmManager.cancel(alarm);
        } else {
            alarm = new StrongAuthTimeoutAlarmListener(userId);
            mStrongAuthTimeoutAlarmListenerForUser.put(userId, alarm);
        }
       
        // schedule a new alarm listener for the user
        mAlarmManager.set(AlarmManager.ELAPSED_REALTIME, when, STRONG_AUTH_TIMEOUT_ALARM_TAG,
                alarm, mHandler);
    }

此方法中会设置Alarm,timeout为when:(设备开机以来的时间加上一个dpm.getRequiredStrongAuthTimeout)

getRequiredStrongAuthTimeout这个时间是多少呢?

getRequiredStrongAuthTimeout

@Override
    public long getRequiredStrongAuthTimeout(ComponentName who, int userId, boolean parent) {
        ......
        synchronized (getLockObject()) {
            if (who != null) {
                ActiveAdmin admin = getActiveAdminUncheckedLocked(who, userId, parent);
                return admin != null ? admin.strongAuthUnlockTimeout : 0;
            }

            // Return the strictest policy across all participating admins.
            List<ActiveAdmin> admins = getActiveAdminsForLockscreenPoliciesLocked(userId, parent);

            long strongAuthUnlockTimeout = DevicePolicyManager.DEFAULT_STRONG_AUTH_TIMEOUT_MS;
            for (int i = 0; i < admins.size(); i++) {
                final long timeout = admins.get(i).strongAuthUnlockTimeout;
                if (timeout != 0) { // take only participating admins into account
                    strongAuthUnlockTimeout = Math.min(timeout, strongAuthUnlockTimeout);
                }
            }
            return Math.max(strongAuthUnlockTimeout, getMinimumStrongAuthTimeoutMs());
        }
    }

getRequiredStrongAuthTimeout这个方法可以根据传递的ComponentName定向获取某个设备管理者设置的timeout,我们分析的流程中传递的ComponentName为null,所以进行下一步获取当前手机的全部设备管理者List,将所有设备管理者设置的timeout和默认值DEFAULT_STRONG_AUTH_TIMEOUT_MS进行比较,去其中小的值,也就是说最大值只能是DEFAULT_STRONG_AUTH_TIMEOUT_MS,也就是三天,最后再和getMinimumStrongAuthTimeoutMs最小值进行比较,
getMinimumStrongAuthTimeoutMs返回MINIMUM_STRONG_AUTH_TIMEOUT_MS

/**
     * Default and maximum timeout in milliseconds after which unlocking with weak auth times out,
     * i.e. the user has to use a strong authentication method like password, PIN or pattern.
     *
     * @hide
     */
    public static final long DEFAULT_STRONG_AUTH_TIMEOUT_MS = 72 * 60 * 60 * 1000; // 72h
    /**
     * Minimum timeout in milliseconds after which unlocking with weak auth times out,
     * i.e. the user has to use a strong authentication method like password, PIN or pattern.
     */
    private static final long MINIMUM_STRONG_AUTH_TIMEOUT_MS = TimeUnit.HOURS.toMillis(1);

也就是说强认证超时最大时间为三天,最小时间为1小时,中间可以通过设备管理者进行修改,获取到timeout之后就会设置一个alarm

// schedule a new alarm listener for the user
        mAlarmManager.set(AlarmManager.ELAPSED_REALTIME, when, STRONG_AUTH_TIMEOUT_ALARM_TAG,
                alarm, mHandler);

这个alarm是一个StrongAuthTimeoutAlarmListener,在timeout之后回调onAlarm方法

private class StrongAuthTimeoutAlarmListener implements OnAlarmListener {

        private final int mUserId;

        public StrongAuthTimeoutAlarmListener(int userId) {
            mUserId = userId;
        }

        @Override
        public void onAlarm() {
            requireStrongAuth(STRONG_AUTH_REQUIRED_AFTER_TIMEOUT, mUserId);
        }
    }

到这里我们就知道了每一次使用pin/password/pattern都会重置这个timeout,设置给alarm,所以当我们使用指纹/面部解锁达到一定时间(最大值三天,最小值一个小时)则必须要求进行强认证,即强制使用pin/password/pattern

requireStrongAuth

调用此方法传递了一个strongAuthReason,为STRONG_AUTH_REQUIRED_AFTER_TIMEOUT,这个flag常量我们前面说过,定义在StrongAuthTracker中,代表超时强认证

public void requireStrongAuth(int strongAuthReason, int userId) {
        if (userId == UserHandle.USER_ALL || userId >= UserHandle.USER_SYSTEM) {
            mHandler.obtainMessage(MSG_REQUIRE_STRONG_AUTH, strongAuthReason,
                    userId).sendToTarget();
        } else {
            throw new IllegalArgumentException(
                    "userId must be an explicit user id or USER_ALL");
        }
    }

发送handler消息

MSG_REQUIRE_STRONG_AUTH

private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                ...
                case MSG_REQUIRE_STRONG_AUTH:
                    handleRequireStrongAuth(msg.arg1, msg.arg2);
                    break;
               ...
            }
        }
    };

handleRequireStrongAuth

private void handleRequireStrongAuth(int strongAuthReason, int userId) {
        if (userId == UserHandle.USER_ALL) {
            for (int i = 0; i < mStrongAuthForUser.size(); i++) {
                int key = mStrongAuthForUser.keyAt(i);
                handleRequireStrongAuthOneUser(strongAuthReason, key);
            }
        } else {
            handleRequireStrongAuthOneUser(strongAuthReason, userId);
        }
    }

mStrongAuthForUser是一个map结构,以userId为key,strongAuthReason为value,接着看下handleRequireStrongAuthOneUser方法

handleRequireStrongAuthOneUser

private void handleRequireStrongAuthOneUser(int strongAuthReason, int userId) {
        int oldValue = mStrongAuthForUser.get(userId, mDefaultStrongAuthFlags);
        int newValue = strongAuthReason == STRONG_AUTH_NOT_REQUIRED
                ? STRONG_AUTH_NOT_REQUIRED
                : (oldValue | strongAuthReason);
        if (oldValue != newValue) {
            mStrongAuthForUser.put(userId, newValue);
            notifyStrongAuthTrackers(newValue, userId);
        }
    }

如果strongAuthReason发生了变化,即oldValue不等于newValue,则通过mStrongAuthForUser.put覆盖旧的strongAuthReason,接着调用notifyStrongAuthTrackers方法

notifyStrongAuthTrackers

private void notifyStrongAuthTrackers(int strongAuthReason, int userId) {
        int i = mTrackers.beginBroadcast();
        try {
            while (i > 0) {
                i--;
                try {
                    mTrackers.getBroadcastItem(i).onStrongAuthRequiredChanged(
                            strongAuthReason, userId);
                } catch (RemoteException e) {
                    Slog.e(TAG, "Exception while notifying StrongAuthTracker.", e);
                }
            }
        } finally {
            mTrackers.finishBroadcast();
        }
    }

这里会遍历mTrackers,mTrackers里面是IStrongAuthTracker,并调用其onStrongAuthRequiredChanged回调方法,IStrongAuthTracker是一个AIDL接口,其mStub通过SystemUI的KeyguardUpdateMonitor注册的,最终到framework层就将mStub添加到了mTrackers中,而mStub是定义在StrongAuthTracker类中,我们看看mStub中的onStrongAuthRequiredChanged方法做了什么?

    /**
     * Tracks the global strong authentication state.
     */
public static class StrongAuthTracker {
	.....
	protected final IStrongAuthTracker.Stub mStub = new IStrongAuthTracker.Stub() {
            @Override
            public void onStrongAuthRequiredChanged(@StrongAuthFlags int strongAuthFlags,
                    int userId) {
                mHandler.obtainMessage(H.MSG_ON_STRONG_AUTH_REQUIRED_CHANGED,
                        strongAuthFlags, userId).sendToTarget();
            }
        };
    private class H extends Handler {
           ......
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case MSG_ON_STRONG_AUTH_REQUIRED_CHANGED:
                        handleStrongAuthRequiredChanged(msg.arg1, msg.arg2);
                        break;
                }
            }
        }
    }

通过handler调用了handleStrongAuthRequiredChanged方法,

protected void handleStrongAuthRequiredChanged(@StrongAuthFlags int strongAuthFlags,
                int userId) {
            int oldValue = getStrongAuthForUser(userId);
            if (strongAuthFlags != oldValue) {
                if (strongAuthFlags == mDefaultStrongAuthFlags) {
                    mStrongAuthRequiredForUser.delete(userId);
                } else {
                    mStrongAuthRequiredForUser.put(userId, strongAuthFlags);
                }
                onStrongAuthRequiredChanged(userId);
            }
        }

如果当前传递的strongAuthReason和之前的strongAuthReason不一致,则调用onStrongAuthRequiredChanged方法通知到SystemUI中,onStrongAuthRequiredChanged这个方法被定义在StrongAuthTracker中是个空方法,需要子类实现,而SystemUI中KeyguardUpdateMonitor的StrongAuthTracker继承了LockPatternUtils.StrongAuthTracker类,最终实现了onStrongAuthRequiredChanged方法

KeyguardUpdateMonitor

public static class StrongAuthTracker extends LockPatternUtils.StrongAuthTracker {
	......
		@Override
        public void onStrongAuthRequiredChanged(int userId) {
            mStrongAuthRequiredChangedCallback.accept(userId);
        }
	......

}

mStrongAuthRequiredChangedCallback是构造StrongAuthTracker时创建的一个函数式接口Consumer,

mStrongAuthTracker = new StrongAuthTracker(context, this::notifyStrongAuthStateChanged);

调用mStrongAuthRequiredChangedCallback.accept等价于调用this.notifyStrongAuthStateChanged

notifyStrongAuthStateChanged

private void notifyStrongAuthStateChanged(int userId) {
        checkIsHandlerThread();
        for (int i = 0; i < mCallbacks.size(); i++) {
            KeyguardUpdateMonitorCallback cb = mCallbacks.get(i).get();
            if (cb != null) {
                cb.onStrongAuthStateChanged(userId);
            }
        }
    }

这里调用onStrongAuthStateChanged回调方法,来到KeyguardBouncer中

KeyguardBouncer

public class KeyguardBouncer {
	 private final KeyguardUpdateMonitorCallback mUpdateMonitorCallback =
            new KeyguardUpdateMonitorCallback() {
                @Override
                public void onStrongAuthStateChanged(int userId) {
                    mBouncerPromptReason = mCallback.getBouncerPromptReason();
                }
            };

}

在此方法中再通过回调getBouncerPromptReason获取Bouncer弹出的reason,来到KeyguardViewMediator中

KeyguardViewMediator

    ViewMediatorCallback mViewMediatorCallback = new ViewMediatorCallback() {
		@Override
        public int getBouncerPromptReason() {
            int currentUser = ActivityManager.getCurrentUser();
            boolean trust = mTrustManager.isTrustUsuallyManaged(currentUser);
            boolean biometrics = mUpdateMonitor.isUnlockingWithBiometricsPossible(currentUser);
            boolean any = trust || biometrics;
            KeyguardUpdateMonitor.StrongAuthTracker strongAuthTracker =
                    mUpdateMonitor.getStrongAuthTracker();
            int strongAuth = strongAuthTracker.getStrongAuthForUser(currentUser);

            if (any && !strongAuthTracker.hasUserAuthenticatedSinceBoot()) {
                return KeyguardSecurityView.PROMPT_REASON_RESTART;
            } else if (any && (strongAuth & STRONG_AUTH_REQUIRED_AFTER_TIMEOUT) != 0) {
                return KeyguardSecurityView.PROMPT_REASON_TIMEOUT;
            } else if (any && (strongAuth & STRONG_AUTH_REQUIRED_AFTER_DPM_LOCK_NOW) != 0) {
                return KeyguardSecurityView.PROMPT_REASON_DEVICE_ADMIN;
            } else if (trust && (strongAuth & SOME_AUTH_REQUIRED_AFTER_USER_REQUEST) != 0) {
                return KeyguardSecurityView.PROMPT_REASON_USER_REQUEST;
            } else if (any && (strongAuth & STRONG_AUTH_REQUIRED_AFTER_LOCKOUT) != 0) {
                return KeyguardSecurityView.PROMPT_REASON_AFTER_LOCKOUT;
            }
            return KeyguardSecurityView.PROMPT_REASON_NONE;
        }
}

这里根据不同的reason获取不同的显示字符串,显示在bouncer上,以提醒用户为何需要强制输入pin/password/pattern,我们从frameworks层传递的reason为STRONG_AUTH_REQUIRED_AFTER_TIMEOUT,强认证超时,所以返回的flag为PROMPT_REASON_TIMEOUT

有了此flag,然后根据不同的bouncer调用不用的showPromptReason(mBouncerPromptReason)实现,我们以password为例,showPromptReason会调用getPromptReasonStringRes方法:

 @Override
    protected int getPromptReasonStringRes(int reason) {
        switch (reason) {
            case PROMPT_REASON_RESTART:
                return R.string.kg_prompt_reason_restart_pin;
            case PROMPT_REASON_TIMEOUT:
                return R.string.kg_prompt_reason_timeout_pin;
            case PROMPT_REASON_DEVICE_ADMIN:
                return R.string.kg_prompt_reason_device_admin;
            case PROMPT_REASON_USER_REQUEST:
                return R.string.kg_prompt_reason_user_request;
            case PROMPT_REASON_NONE:
                return 0;
            default:
                return R.string.kg_prompt_reason_timeout_pin;
        }
    }

我们得到的reason为PROMPT_REASON_TIMEOUT,所以返回的字符串为kg_prompt_reason_timeout_pin

  <!-- An explanation text that the pin needs to be entered since
   the user hasn't used strong authentication since quite some time. [CHAR LIMIT=80] -->
    <string name="kg_prompt_reason_timeout_pin">PIN required for additional security</string>

所以当你不能使用指纹或者面部解锁时看看bouncer界面的字符串,如果出现了这条字串就说明你已经长时间没有强认证设备了,

我们同时也看到其他的强认证方式同样会返回不同的字串,原理都是和强认证超时一样的

总结一下:

  1. 当我们成功使用pin/password/pattern解锁时,会重置强认证timeout时间,这个时间最大值是三天,最小值是1小时,设备管理者应用可以修改此时间,这个timeout是指从设备开机开始算起,到下一次使用pin/password/pattern解锁
  2. 当timeout到达时,alarm会执行StrongAuthTimeoutAlarmListener的回调方法onAlarm,最终传递一个strongAuthReason到SystemUI中,KeyguardBouncer根据此strongAuthReason向用户展示kg_prompt_reason_timeout_pin的字串,提示用户强认证超时
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值