1 /*
2  * Copyright (C) 2016 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 android.app.admin;
18 
19 import android.annotation.IntDef;
20 import android.annotation.TestApi;
21 import android.compat.annotation.UnsupportedAppUsage;
22 import android.content.ComponentName;
23 import android.os.Parcel;
24 import android.os.Parcelable;
25 import android.os.SystemProperties;
26 import android.util.EventLog.Event;
27 
28 import java.io.IOException;
29 import java.lang.annotation.Retention;
30 import java.lang.annotation.RetentionPolicy;
31 import java.util.Collection;
32 import java.util.Objects;
33 
34 /**
35  * Definitions for working with security logs.
36  *
37  * <p>Device owner apps can control the logging with
38  * {@link DevicePolicyManager#setSecurityLoggingEnabled}. When security logs are enabled, device
39  * owner apps receive periodic callbacks from {@link DeviceAdminReceiver#onSecurityLogsAvailable},
40  * at which time new batch of logs can be collected via
41  * {@link DevicePolicyManager#retrieveSecurityLogs}. {@link SecurityEvent} describes the type and
42  * format of security logs being collected.
43  */
44 public class SecurityLog {
45 
46     private static final String PROPERTY_LOGGING_ENABLED = "persist.logd.security";
47 
48     /** @hide */
49     @Retention(RetentionPolicy.SOURCE)
50     @IntDef(prefix = { "TAG_" }, value = {
51             TAG_ADB_SHELL_INTERACTIVE,
52             TAG_ADB_SHELL_CMD,
53             TAG_SYNC_RECV_FILE,
54             TAG_SYNC_SEND_FILE,
55             TAG_APP_PROCESS_START,
56             TAG_KEYGUARD_DISMISSED,
57             TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT,
58             TAG_KEYGUARD_SECURED,
59             TAG_OS_STARTUP,
60             TAG_OS_SHUTDOWN,
61             TAG_LOGGING_STARTED,
62             TAG_LOGGING_STOPPED,
63             TAG_MEDIA_MOUNT,
64             TAG_MEDIA_UNMOUNT,
65             TAG_LOG_BUFFER_SIZE_CRITICAL,
66             TAG_PASSWORD_EXPIRATION_SET,
67             TAG_PASSWORD_COMPLEXITY_SET,
68             TAG_PASSWORD_HISTORY_LENGTH_SET,
69             TAG_MAX_SCREEN_LOCK_TIMEOUT_SET,
70             TAG_MAX_PASSWORD_ATTEMPTS_SET,
71             TAG_KEYGUARD_DISABLED_FEATURES_SET,
72             TAG_REMOTE_LOCK,
73             TAG_USER_RESTRICTION_ADDED,
74             TAG_USER_RESTRICTION_REMOVED,
75             TAG_WIPE_FAILURE,
76             TAG_KEY_GENERATED,
77             TAG_KEY_IMPORT,
78             TAG_KEY_DESTRUCTION,
79             TAG_CERT_AUTHORITY_INSTALLED,
80             TAG_CERT_AUTHORITY_REMOVED,
81             TAG_CRYPTO_SELF_TEST_COMPLETED,
82             TAG_KEY_INTEGRITY_VIOLATION,
83             TAG_CERT_VALIDATION_FAILURE,
84     })
85     public @interface SecurityLogTag {}
86 
87     /** @hide */
88     @Retention(RetentionPolicy.SOURCE)
89     @IntDef(prefix = { "LEVEL_" }, value = {
90             LEVEL_INFO,
91             LEVEL_WARNING,
92             LEVEL_ERROR
93     })
94     public @interface SecurityLogLevel {}
95 
96     /**
97      * Indicates that an ADB interactive shell was opened via "adb shell".
98      * There is no extra payload in the log event.
99      */
100     public static final int TAG_ADB_SHELL_INTERACTIVE =
101             SecurityLogTags.SECURITY_ADB_SHELL_INTERACTIVE;
102 
103     /**
104      * Indicates that a shell command was issued over ADB via {@code adb shell <command>}
105      * The log entry contains a {@code String} payload containing the shell command, accessible
106      * via {@link SecurityEvent#getData()}.
107      */
108     public static final int TAG_ADB_SHELL_CMD = SecurityLogTags.SECURITY_ADB_SHELL_COMMAND;
109 
110     /**
111      * Indicates that a file was pulled from the device via the adb daemon, for example via
112      * {@code adb pull}. The log entry contains a {@code String} payload containing the path of the
113      * pulled file on the device, accessible via {@link SecurityEvent#getData()}.
114      */
115     public static final int TAG_SYNC_RECV_FILE = SecurityLogTags.SECURITY_ADB_SYNC_RECV;
116 
117     /**
118      * Indicates that a file was pushed to the device via the adb daemon, for example via
119      * {@code adb push}. The log entry contains a {@code String} payload containing the destination
120      * path of the pushed file, accessible via {@link SecurityEvent#getData()}.
121      */
122     public static final int TAG_SYNC_SEND_FILE = SecurityLogTags.SECURITY_ADB_SYNC_SEND;
123 
124     /**
125      * Indicates that an app process was started. The log entry contains the following
126      * information about the process encapsulated in an {@link Object} array, accessible via
127      * {@link SecurityEvent#getData()}:
128      * <li> [0] process name ({@code String})
129      * <li> [1] exact start time in milliseconds according to {@code System.currentTimeMillis()}
130      *      ({@code Long})
131      * <li> [2] app uid ({@code Integer})
132      * <li> [3] app pid ({@code Integer})
133      * <li> [4] seinfo tag ({@code String})
134      * <li> [5] SHA-256 hash of the base APK in hexadecimal ({@code String})
135      */
136     public static final int TAG_APP_PROCESS_START = SecurityLogTags.SECURITY_APP_PROCESS_START;
137 
138     /**
139      * Indicates that keyguard has been dismissed. This event is only logged if the device
140      * has a secure keyguard. It is logged regardless of how keyguard is dismissed, including
141      * via PIN/pattern/password, biometrics or via a trust agent.
142      * There is no extra payload in the log event.
143      * @see #TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT
144      */
145     public static final int TAG_KEYGUARD_DISMISSED = SecurityLogTags.SECURITY_KEYGUARD_DISMISSED;
146 
147     /**
148      * Indicates that there has been an authentication attempt to dismiss the keyguard. The log
149      * entry contains the following information about the attempt encapsulated in an {@link Object}
150      * array, accessible via {@link SecurityEvent#getData()}:
151      * <li> [0] attempt result ({@code Integer}, 1 for successful, 0 for unsuccessful)
152      * <li> [1] strength of authentication method ({@code Integer}, 1 if strong authentication
153      *      method was used, 0 otherwise)
154      */
155     public static final int TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT =
156             SecurityLogTags.SECURITY_KEYGUARD_DISMISS_AUTH_ATTEMPT;
157 
158     /**
159      * Indicates that the device has been locked, either by the user or by a timeout. There is no
160      * extra payload in the log event.
161      */
162     public static final int TAG_KEYGUARD_SECURED = SecurityLogTags.SECURITY_KEYGUARD_SECURED;
163 
164     /**
165      * Indicates that the Android OS has started. The log entry contains the following information
166      * about the startup time software integrity check encapsulated in an {@link Object} array,
167      * accessible via {@link SecurityEvent#getData()}:
168      * <li> [0] Verified Boot state ({@code String})
169      * <li> [1] dm-verity mode ({@code String}).
170      * <p>Verified Boot state can be one of the following:
171      * <li> {@code green} indicates that there is a full chain of trust extending from the
172      * bootloader to verified partitions including the bootloader, boot partition, and all verified
173      * partitions.
174      * <li> {@code yellow} indicates that the boot partition has been verified using the embedded
175      * certificate and the signature is valid.
176      * <li> {@code orange} indicates that the device may be freely modified. Device integrity is
177      * left to the user to verify out-of-band.
178      * <p>dm-verity mode can be one of the following:
179      * <li> {@code enforcing} indicates that the device will be restarted when corruption is
180      * detected.
181      * <li> {@code eio} indicates that an I/O error will be returned for an attempt to read
182      * corrupted data blocks.
183      * For details see Verified Boot documentation.
184      */
185     public static final int TAG_OS_STARTUP = SecurityLogTags.SECURITY_OS_STARTUP;
186 
187     /**
188      * Indicates that the Android OS has shutdown. There is no extra payload in the log event.
189      */
190     public static final int TAG_OS_SHUTDOWN = SecurityLogTags.SECURITY_OS_SHUTDOWN;
191 
192     /**
193      * Indicates start-up of audit logging. There is no extra payload in the log event.
194      */
195     public static final int TAG_LOGGING_STARTED = SecurityLogTags.SECURITY_LOGGING_STARTED;
196 
197     /**
198      * Indicates shutdown of audit logging. There is no extra payload in the log event.
199      */
200     public static final int TAG_LOGGING_STOPPED = SecurityLogTags.SECURITY_LOGGING_STOPPED;
201 
202     /**
203      * Indicates that removable media has been mounted on the device. The log entry contains the
204      * following information about the event, encapsulated in an {@link Object} array and
205      * accessible via {@link SecurityEvent#getData()}:
206      * <li> [0] mount point ({@code String})
207      * <li> [1] volume label ({@code String}).
208      */
209     public static final int TAG_MEDIA_MOUNT = SecurityLogTags.SECURITY_MEDIA_MOUNTED;
210 
211     /**
212      * Indicates that removable media was unmounted from the device. The log entry contains the
213      * following information about the event, encapsulated in an {@link Object} array and
214      * accessible via {@link SecurityEvent#getData()}:
215      * <li> [0] mount point ({@code String})
216      * <li> [1] volume label ({@code String}).
217      */
218     public static final int TAG_MEDIA_UNMOUNT = SecurityLogTags.SECURITY_MEDIA_UNMOUNTED;
219 
220     /**
221      * Indicates that the audit log buffer has reached 90% of its capacity. There is no extra
222      * payload in the log event.
223      */
224     public static final int TAG_LOG_BUFFER_SIZE_CRITICAL =
225             SecurityLogTags.SECURITY_LOG_BUFFER_SIZE_CRITICAL;
226 
227     /**
228      * Indicates that an admin has set a password expiration timeout. The log entry contains the
229      * following information about the event, encapsulated in an {@link Object} array and accessible
230      * via {@link SecurityEvent#getData()}:
231      * <li> [0] admin package name ({@code String})
232      * <li> [1] admin user ID ({@code Integer})
233      * <li> [2] target user ID ({@code Integer})
234      * <li> [3] new password expiration timeout in milliseconds ({@code Long}).
235      * @see DevicePolicyManager#setPasswordExpirationTimeout(ComponentName, long)
236      */
237     public static final int TAG_PASSWORD_EXPIRATION_SET =
238             SecurityLogTags.SECURITY_PASSWORD_EXPIRATION_SET;
239 
240     /**
241      * Indicates that an admin has set a requirement for password complexity. The log entry contains
242      * the following information about the event, encapsulated in an {@link Object} array and
243      * accessible via {@link SecurityEvent#getData()}:
244      * <li> [0] admin package name ({@code String})
245      * <li> [1] admin user ID ({@code Integer})
246      * <li> [2] target user ID ({@code Integer})
247      * <li> [3] minimum password length ({@code Integer})
248      * <li> [4] password quality constraint ({@code Integer})
249      * <li> [5] minimum number of letters ({@code Integer})
250      * <li> [6] minimum number of non-letters ({@code Integer})
251      * <li> [7] minimum number of digits ({@code Integer})
252      * <li> [8] minimum number of uppercase letters ({@code Integer})
253      * <li> [9] minimum number of lowercase letters ({@code Integer})
254      * <li> [10] minimum number of symbols ({@code Integer})
255      *
256      * @see DevicePolicyManager#setPasswordMinimumLength(ComponentName, int)
257      * @see DevicePolicyManager#setPasswordQuality(ComponentName, int)
258      * @see DevicePolicyManager#setPasswordMinimumLetters(ComponentName, int)
259      * @see DevicePolicyManager#setPasswordMinimumNonLetter(ComponentName, int)
260      * @see DevicePolicyManager#setPasswordMinimumLowerCase(ComponentName, int)
261      * @see DevicePolicyManager#setPasswordMinimumUpperCase(ComponentName, int)
262      * @see DevicePolicyManager#setPasswordMinimumNumeric(ComponentName, int)
263      * @see DevicePolicyManager#setPasswordMinimumSymbols(ComponentName, int)
264      */
265     public static final int TAG_PASSWORD_COMPLEXITY_SET =
266             SecurityLogTags.SECURITY_PASSWORD_COMPLEXITY_SET;
267 
268     /**
269      * Indicates that an admin has set a password history length. The log entry contains the
270      * following information about the event encapsulated in an {@link Object} array, accessible
271      * via {@link SecurityEvent#getData()}:
272      * <li> [0] admin package name ({@code String})
273      * <li> [1] admin user ID ({@code Integer})
274      * <li> [2] target user ID ({@code Integer})
275      * <li> [3] new password history length value ({@code Integer})
276      * @see DevicePolicyManager#setPasswordHistoryLength(ComponentName, int)
277      */
278     public static final int TAG_PASSWORD_HISTORY_LENGTH_SET =
279             SecurityLogTags.SECURITY_PASSWORD_HISTORY_LENGTH_SET;
280 
281     /**
282      * Indicates that an admin has set a maximum screen lock timeout. The log entry contains the
283      * following information about the event encapsulated in an {@link Object} array, accessible
284      * via {@link SecurityEvent#getData()}:
285      * <li> [0] admin package name ({@code String})
286      * <li> [1] admin user ID ({@code Integer})
287      * <li> [2] target user ID ({@code Integer})
288      * <li> [3] new screen lock timeout in milliseconds ({@code Long})
289      * @see DevicePolicyManager#setMaximumTimeToLock(ComponentName, long)
290      */
291     public static final int TAG_MAX_SCREEN_LOCK_TIMEOUT_SET =
292             SecurityLogTags.SECURITY_MAX_SCREEN_LOCK_TIMEOUT_SET;
293 
294     /**
295      * Indicates that an admin has set a maximum number of failed password attempts before wiping
296      * data. The log entry contains the following information about the event encapsulated in an
297      * {@link Object} array, accessible via {@link SecurityEvent#getData()}:
298      * <li> [0] admin package name ({@code String})
299      * <li> [1] admin user ID ({@code Integer})
300      * <li> [2] target user ID ({@code Integer})
301      * <li> [3] new maximum number of failed password attempts ({@code Integer})
302      * @see DevicePolicyManager#setMaximumFailedPasswordsForWipe(ComponentName, int)
303      */
304     public static final int TAG_MAX_PASSWORD_ATTEMPTS_SET =
305             SecurityLogTags.SECURITY_MAX_PASSWORD_ATTEMPTS_SET;
306 
307     /**
308      * Indicates that an admin has set disabled keyguard features. The log entry contains the
309      * following information about the event encapsulated in an {@link Object} array, accessible via
310      * {@link SecurityEvent#getData()}:
311      * <li> [0] admin package name ({@code String})
312      * <li> [1] admin user ID ({@code Integer})
313      * <li> [2] target user ID ({@code Integer})
314      * <li> [3] disabled keyguard feature mask ({@code Integer}).
315      * @see DevicePolicyManager#setKeyguardDisabledFeatures(ComponentName, int)
316      */
317     public static final int TAG_KEYGUARD_DISABLED_FEATURES_SET =
318             SecurityLogTags.SECURITY_KEYGUARD_DISABLED_FEATURES_SET;
319 
320     /**
321      * Indicates that an admin remotely locked the device or profile. The log entry contains the
322      * following information about the event encapsulated in an {@link Object} array, accessible via
323      * {@link SecurityEvent#getData()}:
324      * <li> [0] admin package name ({@code String}),
325      * <li> [1] admin user ID ({@code Integer}).
326      * <li> [2] target user ID ({@code Integer})
327      */
328     public static final int TAG_REMOTE_LOCK = SecurityLogTags.SECURITY_REMOTE_LOCK;
329 
330     /**
331      * Indicates a failure to wipe device or user data. There is no extra payload in the log event.
332      */
333     public static final int TAG_WIPE_FAILURE = SecurityLogTags.SECURITY_WIPE_FAILED;
334 
335     /**
336      * Indicates that an authentication key was generated. The log entry contains the following
337      * information about the event, encapsulated in an {@link Object} array and accessible via
338      * {@link SecurityEvent#getData()}:
339      * <li> [0] result ({@code Integer}, 0 if operation failed, 1 if succeeded)
340      * <li> [1] alias of the key ({@code String})
341      * <li> [2] requesting process uid ({@code Integer}).
342      */
343     public static final int TAG_KEY_GENERATED =
344             SecurityLogTags.SECURITY_KEY_GENERATED;
345 
346     /**
347      * Indicates that a cryptographic key was imported. The log entry contains the following
348      * information about the event, encapsulated in an {@link Object} array and accessible via
349      * {@link SecurityEvent#getData()}:
350      * <li> [0] result ({@code Integer}, 0 if operation failed, 1 if succeeded)
351      * <li> [1] alias of the key ({@code String})
352      * <li> [2] requesting process uid ({@code Integer}).
353      */
354     public static final int TAG_KEY_IMPORT = SecurityLogTags.SECURITY_KEY_IMPORTED;
355 
356     /**
357      * Indicates that a cryptographic key was destroyed. The log entry contains the following
358      * information about the event, encapsulated in an {@link Object} array and accessible via
359      * {@link SecurityEvent#getData()}:
360      * <li> [0] result ({@code Integer}, 0 if operation failed, 1 if succeeded)
361      * <li> [1] alias of the key ({@code String})
362      * <li> [2] requesting process uid ({@code Integer}).
363      */
364     public static final int TAG_KEY_DESTRUCTION = SecurityLogTags.SECURITY_KEY_DESTROYED;
365 
366     /**
367      * Indicates that a new root certificate has been installed into system's trusted credential
368      * storage. The log entry contains the following information about the event, encapsulated in an
369      * {@link Object} array and accessible via {@link SecurityEvent#getData()}:
370      * <li> [0] result ({@code Integer}, 0 if operation failed, 1 if succeeded)
371      * <li> [1] subject of the certificate ({@code String}).
372      */
373     public static final int TAG_CERT_AUTHORITY_INSTALLED =
374             SecurityLogTags.SECURITY_CERT_AUTHORITY_INSTALLED;
375 
376     /**
377      * Indicates that a new root certificate has been removed from system's trusted credential
378      * storage. The log entry contains the following information about the event, encapsulated in an
379      * {@link Object} array and accessible via {@link SecurityEvent#getData()}:
380      * <li> [0] result ({@code Integer}, 0 if operation failed, 1 if succeeded)
381      * <li> [1] subject of the certificate ({@code String}).
382      */
383     public static final int TAG_CERT_AUTHORITY_REMOVED =
384             SecurityLogTags.SECURITY_CERT_AUTHORITY_REMOVED;
385 
386     /**
387      * Indicates that an admin has set a user restriction. The log entry contains the following
388      * information about the event, encapsulated in an {@link Object} array and accessible via
389      * {@link SecurityEvent#getData()}:
390      * <li> [0] admin package name ({@code String})
391      * <li> [1] admin user ID ({@code Integer})
392      * <li> [2] user restriction ({@code String})
393      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
394      */
395     public static final int TAG_USER_RESTRICTION_ADDED =
396             SecurityLogTags.SECURITY_USER_RESTRICTION_ADDED;
397 
398     /**
399      * Indicates that an admin has removed a user restriction. The log entry contains the following
400      * information about the event, encapsulated in an {@link Object} array and accessible via
401      * {@link SecurityEvent#getData()}:
402      * <li> [0] admin package name ({@code String})
403      * <li> [1] admin user ID ({@code Integer})
404      * <li> [2] user restriction ({@code String})
405      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
406      */
407     public static final int TAG_USER_RESTRICTION_REMOVED =
408             SecurityLogTags.SECURITY_USER_RESTRICTION_REMOVED;
409 
410     /**
411      * Indicates that cryptographic functionality self test has completed. The log entry contains an
412      * {@code Integer} payload, indicating the result of the test (0 if the test failed, 1 if
413      * succeeded) and accessible via {@link SecurityEvent#getData()}.
414      */
415     public static final int TAG_CRYPTO_SELF_TEST_COMPLETED =
416             SecurityLogTags.SECURITY_CRYPTO_SELF_TEST_COMPLETED;
417 
418     /**
419      * Indicates a failed cryptographic key integrity check. The log entry contains the following
420      * information about the event, encapsulated in an {@link Object} array and accessible via
421      * {@link SecurityEvent#getData()}:
422      * <li> [0] alias of the key ({@code String})
423      * <li> [1] owner application uid ({@code Integer}).
424      */
425     public static final int TAG_KEY_INTEGRITY_VIOLATION =
426             SecurityLogTags.SECURITY_KEY_INTEGRITY_VIOLATION;
427 
428     /**
429      * Indicates a failure to validate X.509v3 certificate. The log entry contains a {@code String}
430      * payload indicating the failure reason, accessible via {@link SecurityEvent#getData()}.
431      */
432     public static final int TAG_CERT_VALIDATION_FAILURE =
433             SecurityLogTags.SECURITY_CERT_VALIDATION_FAILURE;
434 
435     /**
436      * Event severity level indicating that the event corresponds to normal workflow.
437      */
438     public static final int LEVEL_INFO = 1;
439 
440     /**
441      * Event severity level indicating that the event may require admin attention.
442      */
443     public static final int LEVEL_WARNING = 2;
444 
445     /**
446      * Event severity level indicating that the event requires urgent admin action.
447      */
448     public static final int LEVEL_ERROR = 3;
449 
450     /**
451      * Returns if security logging is enabled. Log producers should only write new logs if this is
452      * true. Under the hood this is the logical AND of whether device owner exists and whether
453      * it enables logging by setting the system property {@link #PROPERTY_LOGGING_ENABLED}.
454      * @hide
455      */
isLoggingEnabled()456     public static native boolean isLoggingEnabled();
457 
458     /**
459      * @hide
460      */
setLoggingEnabledProperty(boolean enabled)461     public static void setLoggingEnabledProperty(boolean enabled) {
462         SystemProperties.set(PROPERTY_LOGGING_ENABLED, enabled ? "true" : "false");
463     }
464 
465     /**
466      * @hide
467      */
getLoggingEnabledProperty()468     public static boolean getLoggingEnabledProperty() {
469         return SystemProperties.getBoolean(PROPERTY_LOGGING_ENABLED, false);
470     }
471 
472     /**
473      * A class representing a security event log entry.
474      */
475     public static final class SecurityEvent implements Parcelable {
476         private Event mEvent;
477         private long mId;
478 
479         /**
480          * Constructor used by native classes to generate SecurityEvent instances.
481          * @hide
482          */
483         @UnsupportedAppUsage
SecurityEvent(byte[] data)484         /* package */ SecurityEvent(byte[] data) {
485             this(0, data);
486         }
487 
488         /**
489          * Constructor used by Parcelable.Creator to generate SecurityEvent instances.
490          * @hide
491          */
SecurityEvent(Parcel source)492         /* package */ SecurityEvent(Parcel source) {
493             this(source.readLong(), source.createByteArray());
494         }
495 
496         /** @hide */
497         @TestApi
SecurityEvent(long id, byte[] data)498         public SecurityEvent(long id, byte[] data) {
499             mId = id;
500             mEvent = Event.fromBytes(data);
501         }
502 
503         /**
504          * Returns the timestamp in nano seconds when this event was logged.
505          */
getTimeNanos()506         public long getTimeNanos() {
507             return mEvent.getTimeNanos();
508         }
509 
510         /**
511          * Returns the tag of this log entry, which specifies entry's semantics.
512          */
getTag()513         public @SecurityLogTag int getTag() {
514             return mEvent.getTag();
515         }
516 
517         /**
518          * Returns the payload contained in this log entry or {@code null} if there is no payload.
519          */
getData()520         public Object getData() {
521             return mEvent.getData();
522         }
523 
524         /**
525          * @hide
526          */
setId(long id)527         public void setId(long id) {
528             this.mId = id;
529         }
530 
531         /**
532          * Returns the id of the event, where the id monotonically increases for each event. The id
533          * is reset when the device reboots, and when security logging is enabled.
534          */
getId()535         public long getId() {
536             return mId;
537         }
538 
539         /**
540          * Returns severity level for the event.
541          */
getLogLevel()542         public @SecurityLogLevel int getLogLevel() {
543             switch (mEvent.getTag()) {
544                 case TAG_ADB_SHELL_INTERACTIVE:
545                 case TAG_ADB_SHELL_CMD:
546                 case TAG_SYNC_RECV_FILE:
547                 case TAG_SYNC_SEND_FILE:
548                 case TAG_APP_PROCESS_START:
549                 case TAG_KEYGUARD_DISMISSED:
550                 case TAG_KEYGUARD_SECURED:
551                 case TAG_OS_STARTUP:
552                 case TAG_OS_SHUTDOWN:
553                 case TAG_LOGGING_STARTED:
554                 case TAG_LOGGING_STOPPED:
555                 case TAG_MEDIA_MOUNT:
556                 case TAG_MEDIA_UNMOUNT:
557                 case TAG_PASSWORD_EXPIRATION_SET:
558                 case TAG_PASSWORD_COMPLEXITY_SET:
559                 case TAG_PASSWORD_HISTORY_LENGTH_SET:
560                 case TAG_MAX_SCREEN_LOCK_TIMEOUT_SET:
561                 case TAG_MAX_PASSWORD_ATTEMPTS_SET:
562                 case TAG_USER_RESTRICTION_ADDED:
563                 case TAG_USER_RESTRICTION_REMOVED:
564                     return LEVEL_INFO;
565                 case TAG_CERT_AUTHORITY_REMOVED:
566                 case TAG_CRYPTO_SELF_TEST_COMPLETED:
567                     return getSuccess() ? LEVEL_INFO : LEVEL_ERROR;
568                 case TAG_CERT_AUTHORITY_INSTALLED:
569                 case TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT:
570                 case TAG_KEY_IMPORT:
571                 case TAG_KEY_DESTRUCTION:
572                 case TAG_KEY_GENERATED:
573                     return getSuccess() ? LEVEL_INFO : LEVEL_WARNING;
574                 case TAG_LOG_BUFFER_SIZE_CRITICAL:
575                 case TAG_WIPE_FAILURE:
576                 case TAG_KEY_INTEGRITY_VIOLATION:
577                     return LEVEL_ERROR;
578                 case TAG_CERT_VALIDATION_FAILURE:
579                     return LEVEL_WARNING;
580                 default:
581                     return LEVEL_INFO;
582             }
583         }
584 
585         // Success/failure if present is encoded as an integer in the first (0th) element of data.
getSuccess()586         private boolean getSuccess() {
587             final Object data = getData();
588             if (data == null || !(data instanceof Object[])) {
589                 return false;
590             }
591 
592             final Object[] array = (Object[]) data;
593             return array.length >= 1 && array[0] instanceof Integer && (Integer) array[0] != 0;
594         }
595 
596 
597         @Override
describeContents()598         public int describeContents() {
599             return 0;
600         }
601 
602         @Override
writeToParcel(Parcel dest, int flags)603         public void writeToParcel(Parcel dest, int flags) {
604             dest.writeLong(mId);
605             dest.writeByteArray(mEvent.getBytes());
606         }
607 
608         public static final @android.annotation.NonNull Parcelable.Creator<SecurityEvent> CREATOR =
609                 new Parcelable.Creator<SecurityEvent>() {
610             @Override
611             public SecurityEvent createFromParcel(Parcel source) {
612                 return new SecurityEvent(source);
613             }
614 
615             @Override
616             public SecurityEvent[] newArray(int size) {
617                 return new SecurityEvent[size];
618             }
619         };
620 
621         /**
622          * @hide
623          */
624         @Override
equals(Object o)625         public boolean equals(Object o) {
626             if (this == o) return true;
627             if (o == null || getClass() != o.getClass()) return false;
628             SecurityEvent other = (SecurityEvent) o;
629             return mEvent.equals(other.mEvent) && mId == other.mId;
630         }
631 
632         /**
633          * @hide
634          */
635         @Override
hashCode()636         public int hashCode() {
637             return Objects.hash(mEvent, mId);
638         }
639 
640         /** @hide */
eventEquals(SecurityEvent other)641         public boolean eventEquals(SecurityEvent other) {
642             return other != null && mEvent.equals(other.mEvent);
643         }
644     }
645     /**
646      * Retrieve all security logs and return immediately.
647      * @hide
648      */
readEvents(Collection<SecurityEvent> output)649     public static native void readEvents(Collection<SecurityEvent> output) throws IOException;
650 
651     /**
652      * Retrieve all security logs since the given timestamp in nanoseconds and return immediately.
653      * @hide
654      */
readEventsSince(long timestamp, Collection<SecurityEvent> output)655     public static native void readEventsSince(long timestamp, Collection<SecurityEvent> output)
656             throws IOException;
657 
658     /**
659      * Retrieve all security logs before the last reboot. May return corrupted data due to
660      * unreliable pstore.
661      * @hide
662      */
readPreviousEvents(Collection<SecurityEvent> output)663     public static native void readPreviousEvents(Collection<SecurityEvent> output)
664             throws IOException;
665 
666     /**
667      * Retrieve all security logs whose timestamp is equal to or greater than the given timestamp in
668      * nanoseconds. This method will block until either the last log earlier than the given
669      * timestamp is about to be pruned, or after a 2-hour timeout has passed.
670      * @hide
671      */
readEventsOnWrapping(long timestamp, Collection<SecurityEvent> output)672     public static native void readEventsOnWrapping(long timestamp, Collection<SecurityEvent> output)
673             throws IOException;
674 
675     /**
676      * Write a log entry to the underlying storage, with a string payload.
677      * @hide
678      */
writeEvent(int tag, String str)679     public static native int writeEvent(int tag, String str);
680 
681     /**
682      * Write a log entry to the underlying storage, with several payloads.
683      * Supported types of payload are: integer, long, float, string plus array of supported types.
684      * @hide
685      */
writeEvent(int tag, Object... payloads)686     public static native int writeEvent(int tag, Object... payloads);
687 }
688