Debian Codegraph @

core/java/com/android/internal/widget/LockscreenCredential.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2019 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
17 package com.android.internal.widget;
18
19 import static com.android.internal.widget.LockPatternUtils.CREDENTIAL_TYPE_NONE;
20 import static com.android.internal.widget.LockPatternUtils.CREDENTIAL_TYPE_PASSWORD;
21 import static com.android.internal.widget.LockPatternUtils.CREDENTIAL_TYPE_PASSWORD_OR_PIN;
22 import static com.android.internal.widget.LockPatternUtils.CREDENTIAL_TYPE_PATTERN;
23 import static com.android.internal.widget.LockPatternUtils.CREDENTIAL_TYPE_PIN;
24
25 import android.annotation.NonNull;
26 import android.annotation.Nullable;
27 import android.os.Parcel;
28 import android.os.Parcelable;
29 import android.text.TextUtils;
30
31 import com.android.internal.util.Preconditions;
32
33 import libcore.util.HexEncoding;
34
35 import java.security.MessageDigest;
36 import java.security.NoSuchAlgorithmException;
37 import java.util.Arrays;
38 import java.util.List;
39 import java.util.Objects;
40
41 /**
42 * A class representing a lockscreen credential. It can be either an empty password, a pattern
43 * or a password (or PIN).
44 *
45 * <p> As required by some security certification, the framework tries its best to
46 * remove copies of the lockscreen credential bytes from memory. In this regard, this class
47 * abuses the {@link AutoCloseable} interface for sanitizing memory. This
48 * presents a nice syntax to auto-zeroize memory with the try-with-resource statement:
49 * <pre>
50 * try {LockscreenCredential credential = LockscreenCredential.createPassword(...) {
51 * // Process the credential in some way
52 * }
53 * </pre>
54 * With this construct, we can guarantee that there will be no copies of the password left in
55 * memory when the credential goes out of scope. This should help mitigate certain class of
56 * attacks where the attcker gains read-only access to full device memory (cold boot attack,
57 * unsecured software/hardware memory dumping interfaces such as JTAG).
58 */
59 public class LockscreenCredential implements Parcelable, AutoCloseable {
60
61 private final int mType;
62 // Stores raw credential bytes, or null if credential has been zeroized. An empty password
63 // is represented as a byte array of length 0.
64 private byte[] mCredential;
65
66 /**
67 * Private constructor, use static builder methods instead.
68 *
69 * <p> Builder methods should create a private copy of the credential bytes and pass in here.
70 * LockscreenCredential will only store the reference internally without copying. This is to
71 * minimize the number of extra copies introduced.
72 */
73 private LockscreenCredential(int type, byte[] credential) {
74 Objects.requireNonNull(credential);
75 if (type == CREDENTIAL_TYPE_NONE) {
76 Preconditions.checkArgument(credential.length == 0);
77 } else {
78 // Do not allow constructing a CREDENTIAL_TYPE_PASSWORD_OR_PIN object.
79 Preconditions.checkArgument(type == CREDENTIAL_TYPE_PIN
80 || type == CREDENTIAL_TYPE_PASSWORD
81 || type == CREDENTIAL_TYPE_PATTERN);
82 Preconditions.checkArgument(credential.length > 0);
83 }
84 mType = type;
85 mCredential = credential;
86 }
87
88 /**
89 * Creates a LockscreenCredential object representing empty password.
90 */
91 public static LockscreenCredential createNone() {
92 return new LockscreenCredential(CREDENTIAL_TYPE_NONE, new byte[0]);
93 }
94
95 /**
96 * Creates a LockscreenCredential object representing the given pattern.
97 */
98 public static LockscreenCredential createPattern(@NonNull List<LockPatternView.Cell> pattern) {
99 return new LockscreenCredential(CREDENTIAL_TYPE_PATTERN,
100 LockPatternUtils.patternToByteArray(pattern));
101 }
102
103 /**
104 * Creates a LockscreenCredential object representing the given alphabetic password.
105 */
106 public static LockscreenCredential createPassword(@NonNull CharSequence password) {
107 return new LockscreenCredential(CREDENTIAL_TYPE_PASSWORD,
108 charSequenceToByteArray(password));
109 }
110
111 /**
112 * Creates a LockscreenCredential object representing a managed password for profile with
113 * unified challenge. This credentiall will have type {@code CREDENTIAL_TYPE_PASSWORD} for now.
114 * TODO: consider add a new credential type for this. This can then supersede the
115 * isLockTiedToParent argument in various places in LSS.
116 */
117 public static LockscreenCredential createManagedPassword(@NonNull byte[] password) {
118 return new LockscreenCredential(CREDENTIAL_TYPE_PASSWORD,
119 Arrays.copyOf(password, password.length));
120 }
121
122 /**
123 * Creates a LockscreenCredential object representing the given numeric PIN.
124 */
125 public static LockscreenCredential createPin(@NonNull CharSequence pin) {
126 return new LockscreenCredential(CREDENTIAL_TYPE_PIN,
127 charSequenceToByteArray(pin));
128 }
129
130 /**
131 * Creates a LockscreenCredential object representing the given alphabetic password.
132 * If the supplied password is empty, create an empty credential object.
133 */
134 public static LockscreenCredential createPasswordOrNone(@Nullable CharSequence password) {
135 if (TextUtils.isEmpty(password)) {
136 return createNone();
137 } else {
138 return createPassword(password);
139 }
140 }
141
142 /**
143 * Creates a LockscreenCredential object representing the given numeric PIN.
144 * If the supplied password is empty, create an empty credential object.
145 */
146 public static LockscreenCredential createPinOrNone(@Nullable CharSequence pin) {
147 if (TextUtils.isEmpty(pin)) {
148 return createNone();
149 } else {
150 return createPin(pin);
151 }
152 }
153
154 private void ensureNotZeroized() {
155 Preconditions.checkState(mCredential != null, "Credential is already zeroized");
156 }
157 /**
158 * Returns the type of this credential. Can be one of {@link #CREDENTIAL_TYPE_NONE},
159 * {@link #CREDENTIAL_TYPE_PATTERN}, {@link #CREDENTIAL_TYPE_PIN} or
160 * {@link #CREDENTIAL_TYPE_PASSWORD}.
161 */
162 public int getType() {
163 ensureNotZeroized();
164 return mType;
165 }
166
167 /**
168 * Returns the credential bytes. This is a direct reference of the internal field so
169 * callers should not modify it.
170 *
171 */
172 public byte[] getCredential() {
173 ensureNotZeroized();
174 return mCredential;
175 }
176
177 /** Returns whether this is an empty credential */
178 public boolean isNone() {
179 ensureNotZeroized();
180 return mType == CREDENTIAL_TYPE_NONE;
181 }
182
183 /** Returns whether this is a pattern credential */
184 public boolean isPattern() {
185 ensureNotZeroized();
186 return mType == CREDENTIAL_TYPE_PATTERN;
187 }
188
189 /** Returns whether this is a numeric pin credential */
190 public boolean isPin() {
191 ensureNotZeroized();
192 return mType == CREDENTIAL_TYPE_PIN;
193 }
194
195 /** Returns whether this is an alphabetic password credential */
196 public boolean isPassword() {
197 ensureNotZeroized();
198 return mType == CREDENTIAL_TYPE_PASSWORD;
199 }
200
201 /** Returns the length of the credential */
202 public int size() {
203 ensureNotZeroized();
204 return mCredential.length;
205 }
206
207 /** Create a copy of the credential */
208 public LockscreenCredential duplicate() {
209 return new LockscreenCredential(mType,
210 mCredential != null ? Arrays.copyOf(mCredential, mCredential.length) : null);
211 }
212
213 /**
214 * Zeroize the credential bytes.
215 */
216 public void zeroize() {
217 if (mCredential != null) {
218 Arrays.fill(mCredential, (byte) 0);
219 mCredential = null;
220 }
221 }
222
223 /**
224 * Check if the credential meets minimal length requirement.
225 *
226 * @throws IllegalArgumentException if the credential is too short.
227 */
228 public void checkLength() {
229 if (isNone()) {
230 return;
231 }
232 if (isPattern()) {
233 if (size() < LockPatternUtils.MIN_LOCK_PATTERN_SIZE) {
234 throw new IllegalArgumentException("pattern must not be null and at least "
235 + LockPatternUtils.MIN_LOCK_PATTERN_SIZE + " dots long.");
236 }
237 return;
238 }
239 if (isPassword() || isPin()) {
240 if (size() < LockPatternUtils.MIN_LOCK_PASSWORD_SIZE) {
241 throw new IllegalArgumentException("password must not be null and at least "
242 + "of length " + LockPatternUtils.MIN_LOCK_PASSWORD_SIZE);
243 }
244 return;
245 }
246 }
247
248 /**
249 * Check if this credential's type matches one that's retrieved from disk. The nuance here is
250 * that the framework used to not distinguish between PIN and password, so this method will
251 * allow a PIN/Password LockscreenCredential to match against the legacy
252 * {@link #CREDENTIAL_TYPE_PASSWORD_OR_PIN} stored on disk.
253 */
254 public boolean checkAgainstStoredType(int storedCredentialType) {
255 if (storedCredentialType == CREDENTIAL_TYPE_PASSWORD_OR_PIN) {
256 return getType() == CREDENTIAL_TYPE_PASSWORD || getType() == CREDENTIAL_TYPE_PIN;
257 }
258 return getType() == storedCredentialType;
259 }
260
261 /**
262 * Hash the password for password history check purpose.
263 */
264 public String passwordToHistoryHash(byte[] salt, byte[] hashFactor) {
265 return passwordToHistoryHash(mCredential, salt, hashFactor);
266 }
267
268 /**
269 * Hash the password for password history check purpose.
270 */
271 public static String passwordToHistoryHash(
272 byte[] passwordToHash, byte[] salt, byte[] hashFactor) {
273 if (passwordToHash == null || passwordToHash.length == 0
274 || hashFactor == null || salt == null) {
275 return null;
276 }
277 try {
278 MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
279 sha256.update(hashFactor);
280 byte[] saltedPassword = Arrays.copyOf(passwordToHash, passwordToHash.length
281 + salt.length);
282 System.arraycopy(salt, 0, saltedPassword, passwordToHash.length, salt.length);
283 sha256.update(saltedPassword);
284 Arrays.fill(saltedPassword, (byte) 0);
285 return new String(HexEncoding.encode(sha256.digest()));
286 } catch (NoSuchAlgorithmException e) {
287 throw new AssertionError("Missing digest algorithm: ", e);
288 }
289 }
290
291 /**
292 * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
293 * Not the most secure, but it is at least a second level of protection. First level is that
294 * the file is in a location only readable by the system process.
295 *
296 * @return the hash of the pattern in a byte array.
297 */
298 public String legacyPasswordToHash(byte[] salt) {
299 return legacyPasswordToHash(mCredential, salt);
300 }
301
302 /**
303 * Generate a hash for the given password. To avoid brute force attacks, we use a salted hash.
304 * Not the most secure, but it is at least a second level of protection. First level is that
305 * the file is in a location only readable by the system process.
306 *
307 * @param password the gesture pattern.
308 *
309 * @return the hash of the pattern in a byte array.
310 */
311 public static String legacyPasswordToHash(byte[] password, byte[] salt) {
312 if (password == null || password.length == 0 || salt == null) {
313 return null;
314 }
315
316 try {
317 // Previously the password was passed as a String with the following code:
318 // byte[] saltedPassword = (password + salt).getBytes();
319 // The code below creates the identical digest preimage using byte arrays:
320 byte[] saltedPassword = Arrays.copyOf(password, password.length + salt.length);
321 System.arraycopy(salt, 0, saltedPassword, password.length, salt.length);
322 byte[] sha1 = MessageDigest.getInstance("SHA-1").digest(saltedPassword);
323 byte[] md5 = MessageDigest.getInstance("MD5").digest(saltedPassword);
324
325 byte[] combined = new byte[sha1.length + md5.length];
326 System.arraycopy(sha1, 0, combined, 0, sha1.length);
327 System.arraycopy(md5, 0, combined, sha1.length, md5.length);
328
329 final char[] hexEncoded = HexEncoding.encode(combined);
330 Arrays.fill(saltedPassword, (byte) 0);
331 return new String(hexEncoded);
332 } catch (NoSuchAlgorithmException e) {
333 throw new AssertionError("Missing digest algorithm: ", e);
334 }
335 }
336
337 @Override
338 public void writeToParcel(Parcel dest, int flags) {
339 dest.writeInt(mType);
340 dest.writeByteArray(mCredential);
341 }
342
343 public static final Parcelable.Creator<LockscreenCredential> CREATOR =
344 new Parcelable.Creator<LockscreenCredential>() {
345
346 @Override
347 public LockscreenCredential createFromParcel(Parcel source) {
348 return new LockscreenCredential(source.readInt(), source.createByteArray());
349 }
350
351 @Override
352 public LockscreenCredential[] newArray(int size) {
353 return new LockscreenCredential[size];
354 }
355 };
356
357 @Override
358 public int describeContents() {
359 return 0;
360 }
361
362 @Override
363 public void close() {
364 zeroize();
365 }
366
367 @Override
368 public int hashCode() {
369 // Effective Java — Always override hashCode when you override equals
370 return Objects.hash(mType, Arrays.hashCode(mCredential));
371 }
372
373 @Override
374 public boolean equals(Object o) {
375 if (o == this) return true;
376 if (!(o instanceof LockscreenCredential)) return false;
377 final LockscreenCredential other = (LockscreenCredential) o;
378 return mType == other.mType && Arrays.equals(mCredential, other.mCredential);
379 }
380
381 /**
382 * Converts a CharSequence to a byte array without requiring a toString(), which creates an
383 * additional copy.
384 *
385 * @param chars The CharSequence to convert
386 * @return A byte array representing the input
387 */
388 private static byte[] charSequenceToByteArray(CharSequence chars) {
389 if (chars == null) {
390 return new byte[0];
391 }
392 byte[] bytes = new byte[chars.length()];
393 for (int i = 0; i < chars.length(); i++) {
394 bytes[i] = (byte) chars.charAt(i);
395 }
396 return bytes;
397 }
398 }