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.Manifest;
20 import android.annotation.IntDef;
21 import android.annotation.NonNull;
22 import android.annotation.Nullable;
23 import android.annotation.RequiresPermission;
24 import android.annotation.SystemApi;
25 import android.annotation.TestApi;
26 import android.compat.annotation.UnsupportedAppUsage;
27 import android.content.ComponentName;
28 import android.os.Build;
29 import android.os.Parcel;
30 import android.os.Parcelable;
31 import android.os.SystemProperties;
32 import android.os.UserHandle;
33 import android.util.EventLog.Event;
34 
35 import java.io.IOException;
36 import java.lang.annotation.Retention;
37 import java.lang.annotation.RetentionPolicy;
38 import java.util.ArrayList;
39 import java.util.Collection;
40 import java.util.Objects;
41 
42 /**
43  * Definitions for working with security logs.
44  *
45  * <p>Device owner apps can control the logging with
46  * {@link DevicePolicyManager#setSecurityLoggingEnabled}. When security logs are enabled, device
47  * owner apps receive periodic callbacks from {@link DeviceAdminReceiver#onSecurityLogsAvailable},
48  * at which time new batch of logs can be collected via
49  * {@link DevicePolicyManager#retrieveSecurityLogs}. {@link SecurityEvent} describes the type and
50  * format of security logs being collected.
51  */
52 public class SecurityLog {
53 
54     private static final String PROPERTY_LOGGING_ENABLED = "persist.logd.security";
55 
56     /** @hide */
57     @Retention(RetentionPolicy.SOURCE)
58     @IntDef(prefix = { "TAG_" }, value = {
59             TAG_ADB_SHELL_INTERACTIVE,
60             TAG_ADB_SHELL_CMD,
61             TAG_SYNC_RECV_FILE,
62             TAG_SYNC_SEND_FILE,
63             TAG_APP_PROCESS_START,
64             TAG_KEYGUARD_DISMISSED,
65             TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT,
66             TAG_KEYGUARD_SECURED,
67             TAG_OS_STARTUP,
68             TAG_OS_SHUTDOWN,
69             TAG_LOGGING_STARTED,
70             TAG_LOGGING_STOPPED,
71             TAG_MEDIA_MOUNT,
72             TAG_MEDIA_UNMOUNT,
73             TAG_LOG_BUFFER_SIZE_CRITICAL,
74             TAG_PASSWORD_EXPIRATION_SET,
75             TAG_PASSWORD_COMPLEXITY_SET,
76             TAG_PASSWORD_HISTORY_LENGTH_SET,
77             TAG_MAX_SCREEN_LOCK_TIMEOUT_SET,
78             TAG_MAX_PASSWORD_ATTEMPTS_SET,
79             TAG_KEYGUARD_DISABLED_FEATURES_SET,
80             TAG_REMOTE_LOCK,
81             TAG_USER_RESTRICTION_ADDED,
82             TAG_USER_RESTRICTION_REMOVED,
83             TAG_WIPE_FAILURE,
84             TAG_KEY_GENERATED,
85             TAG_KEY_IMPORT,
86             TAG_KEY_DESTRUCTION,
87             TAG_CERT_AUTHORITY_INSTALLED,
88             TAG_CERT_AUTHORITY_REMOVED,
89             TAG_CRYPTO_SELF_TEST_COMPLETED,
90             TAG_KEY_INTEGRITY_VIOLATION,
91             TAG_CERT_VALIDATION_FAILURE,
92             TAG_CAMERA_POLICY_SET,
93             TAG_PASSWORD_COMPLEXITY_REQUIRED,
94             TAG_PASSWORD_CHANGED,
95             TAG_WIFI_CONNECTION,
96             TAG_WIFI_DISCONNECTION,
97             TAG_BLUETOOTH_CONNECTION,
98             TAG_BLUETOOTH_DISCONNECTION,
99             TAG_PACKAGE_INSTALLED,
100             TAG_PACKAGE_UPDATED,
101             TAG_PACKAGE_UNINSTALLED,
102     })
103     public @interface SecurityLogTag {}
104 
105     /** @hide */
106     @Retention(RetentionPolicy.SOURCE)
107     @IntDef(prefix = { "LEVEL_" }, value = {
108             LEVEL_INFO,
109             LEVEL_WARNING,
110             LEVEL_ERROR
111     })
112     public @interface SecurityLogLevel {}
113 
114     /**
115      * Indicates that an ADB interactive shell was opened via "adb shell".
116      * There is no extra payload in the log event.
117      */
118     public static final int TAG_ADB_SHELL_INTERACTIVE =
119             SecurityLogTags.SECURITY_ADB_SHELL_INTERACTIVE;
120 
121     /**
122      * Indicates that a shell command was issued over ADB via {@code adb shell <command>}
123      * The log entry contains a {@code String} payload containing the shell command, accessible
124      * via {@link SecurityEvent#getData()}. If security logging is enabled on organization-owned
125      * managed profile devices, the shell command will be redacted to an empty string.
126      */
127     public static final int TAG_ADB_SHELL_CMD = SecurityLogTags.SECURITY_ADB_SHELL_COMMAND;
128 
129     /**
130      * Indicates that a file was pulled from the device via the adb daemon, for example via
131      * {@code adb pull}. The log entry contains a {@code String} payload containing the path of the
132      * pulled file on the device, accessible via {@link SecurityEvent#getData()}.
133      */
134     public static final int TAG_SYNC_RECV_FILE = SecurityLogTags.SECURITY_ADB_SYNC_RECV;
135 
136     /**
137      * Indicates that a file was pushed to the device via the adb daemon, for example via
138      * {@code adb push}. The log entry contains a {@code String} payload containing the destination
139      * path of the pushed file, accessible via {@link SecurityEvent#getData()}.
140      */
141     public static final int TAG_SYNC_SEND_FILE = SecurityLogTags.SECURITY_ADB_SYNC_SEND;
142 
143     /**
144      * Indicates that an app process was started. The log entry contains the following
145      * information about the process encapsulated in an {@link Object} array, accessible via
146      * {@link SecurityEvent#getData()}:
147      * <li> [0] process name ({@code String})
148      * <li> [1] exact start time in milliseconds according to {@code System.currentTimeMillis()}
149      *      ({@code Long})
150      * <li> [2] app uid ({@code Integer})
151      * <li> [3] app pid ({@code Integer})
152      * <li> [4] seinfo tag ({@code String})
153      * <li> [5] SHA-256 hash of the base APK in hexadecimal ({@code String})
154      * If security logging is enabled on organization-owned managed profile devices, only events
155      * happening inside the managed profile will be visible.
156      */
157     public static final int TAG_APP_PROCESS_START = SecurityLogTags.SECURITY_APP_PROCESS_START;
158 
159     /**
160      * Indicates that keyguard has been dismissed. This event is only logged if the device
161      * has a secure keyguard. It is logged regardless of how keyguard is dismissed, including
162      * via PIN/pattern/password, biometrics or via a trust agent.
163      * There is no extra payload in the log event.
164      * @see #TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT
165      */
166     public static final int TAG_KEYGUARD_DISMISSED = SecurityLogTags.SECURITY_KEYGUARD_DISMISSED;
167 
168     /**
169      * Indicates that there has been an authentication attempt to dismiss the keyguard. The log
170      * entry contains the following information about the attempt encapsulated in an {@link Object}
171      * array, accessible via {@link SecurityEvent#getData()}:
172      * <li> [0] attempt result ({@code Integer}, 1 for successful, 0 for unsuccessful)
173      * <li> [1] strength of authentication method ({@code Integer}, 1 if strong authentication
174      *      method was used, 0 otherwise)
175      */
176     public static final int TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT =
177             SecurityLogTags.SECURITY_KEYGUARD_DISMISS_AUTH_ATTEMPT;
178 
179     /**
180      * Indicates that the device has been locked, either by the user or by a timeout. There is no
181      * extra payload in the log event.
182      */
183     public static final int TAG_KEYGUARD_SECURED = SecurityLogTags.SECURITY_KEYGUARD_SECURED;
184 
185     /**
186      * Indicates that the Android OS has started. The log entry contains the following information
187      * about the startup time software integrity check encapsulated in an {@link Object} array,
188      * accessible via {@link SecurityEvent#getData()}:
189      * <li> [0] Verified Boot state ({@code String})
190      * <li> [1] dm-verity mode ({@code String}).
191      * <p>Verified Boot state can be one of the following:
192      * <li> {@code green} indicates that there is a full chain of trust extending from the
193      * bootloader to verified partitions including the bootloader, boot partition, and all verified
194      * partitions.
195      * <li> {@code yellow} indicates that the boot partition has been verified using the embedded
196      * certificate and the signature is valid.
197      * <li> {@code orange} indicates that the device may be freely modified. Device integrity is
198      * left to the user to verify out-of-band.
199      * <p>dm-verity mode can be one of the following:
200      * <li> {@code enforcing} indicates that the device will be restarted when corruption is
201      * detected.
202      * <li> {@code eio} indicates that an I/O error will be returned for an attempt to read
203      * corrupted data blocks.
204      * <li> {@code disabled} indicates that integrity check is disabled.
205      * For details see Verified Boot documentation.
206      */
207     public static final int TAG_OS_STARTUP = SecurityLogTags.SECURITY_OS_STARTUP;
208 
209     /**
210      * Indicates that the Android OS has shutdown. There is no extra payload in the log event.
211      */
212     public static final int TAG_OS_SHUTDOWN = SecurityLogTags.SECURITY_OS_SHUTDOWN;
213 
214     /**
215      * Indicates start-up of audit logging. There is no extra payload in the log event.
216      */
217     public static final int TAG_LOGGING_STARTED = SecurityLogTags.SECURITY_LOGGING_STARTED;
218 
219     /**
220      * Indicates shutdown of audit logging. There is no extra payload in the log event.
221      */
222     public static final int TAG_LOGGING_STOPPED = SecurityLogTags.SECURITY_LOGGING_STOPPED;
223 
224     /**
225      * Indicates that removable media has been mounted on the device. The log entry contains the
226      * following information about the event, encapsulated in an {@link Object} array and
227      * accessible via {@link SecurityEvent#getData()}:
228      * <li> [0] mount point ({@code String})
229      * <li> [1] volume label ({@code String}). Redacted to empty string on organization-owned
230      *     managed profile devices.
231      */
232     public static final int TAG_MEDIA_MOUNT = SecurityLogTags.SECURITY_MEDIA_MOUNTED;
233 
234     /**
235      * Indicates that removable media was unmounted from the device. The log entry contains the
236      * following information about the event, encapsulated in an {@link Object} array and
237      * accessible via {@link SecurityEvent#getData()}:
238      * <li> [0] mount point ({@code String})
239      * <li> [1] volume label ({@code String}). Redacted to empty string on organization-owned
240      *     managed profile devices.
241      */
242     public static final int TAG_MEDIA_UNMOUNT = SecurityLogTags.SECURITY_MEDIA_UNMOUNTED;
243 
244     /**
245      * Indicates that the audit log buffer has reached 90% of its capacity. There is no extra
246      * payload in the log event.
247      */
248     public static final int TAG_LOG_BUFFER_SIZE_CRITICAL =
249             SecurityLogTags.SECURITY_LOG_BUFFER_SIZE_CRITICAL;
250 
251     /**
252      * Indicates that an admin has set a password expiration timeout. The log entry contains the
253      * following information about the event, encapsulated in an {@link Object} array and accessible
254      * via {@link SecurityEvent#getData()}:
255      * <li> [0] admin package name ({@code String})
256      * <li> [1] admin user ID ({@code Integer})
257      * <li> [2] target user ID ({@code Integer})
258      * <li> [3] new password expiration timeout in milliseconds ({@code Long}).
259      * @see DevicePolicyManager#setPasswordExpirationTimeout(ComponentName, long)
260      */
261     public static final int TAG_PASSWORD_EXPIRATION_SET =
262             SecurityLogTags.SECURITY_PASSWORD_EXPIRATION_SET;
263 
264     /**
265      * Indicates that an admin has set a requirement for password complexity. The log entry contains
266      * the following information about the event, encapsulated in an {@link Object} array and
267      * accessible via {@link SecurityEvent#getData()}:
268      * <li> [0] admin package name ({@code String})
269      * <li> [1] admin user ID ({@code Integer})
270      * <li> [2] target user ID ({@code Integer})
271      * <li> [3] minimum password length ({@code Integer})
272      * <li> [4] password quality constraint ({@code Integer})
273      * <li> [5] minimum number of letters ({@code Integer})
274      * <li> [6] minimum number of non-letters ({@code Integer})
275      * <li> [7] minimum number of digits ({@code Integer})
276      * <li> [8] minimum number of uppercase letters ({@code Integer})
277      * <li> [9] minimum number of lowercase letters ({@code Integer})
278      * <li> [10] minimum number of symbols ({@code Integer})
279      *
280      * @see DevicePolicyManager#setPasswordMinimumLength(ComponentName, int)
281      * @see DevicePolicyManager#setPasswordQuality(ComponentName, int)
282      * @see DevicePolicyManager#setPasswordMinimumLetters(ComponentName, int)
283      * @see DevicePolicyManager#setPasswordMinimumNonLetter(ComponentName, int)
284      * @see DevicePolicyManager#setPasswordMinimumLowerCase(ComponentName, int)
285      * @see DevicePolicyManager#setPasswordMinimumUpperCase(ComponentName, int)
286      * @see DevicePolicyManager#setPasswordMinimumNumeric(ComponentName, int)
287      * @see DevicePolicyManager#setPasswordMinimumSymbols(ComponentName, int)
288      */
289     public static final int TAG_PASSWORD_COMPLEXITY_SET =
290             SecurityLogTags.SECURITY_PASSWORD_COMPLEXITY_SET;
291 
292     /**
293      * Indicates that an admin has set a password history length. The log entry contains the
294      * following information about the event encapsulated in an {@link Object} array, accessible
295      * via {@link SecurityEvent#getData()}:
296      * <li> [0] admin package name ({@code String})
297      * <li> [1] admin user ID ({@code Integer})
298      * <li> [2] target user ID ({@code Integer})
299      * <li> [3] new password history length value ({@code Integer})
300      * @see DevicePolicyManager#setPasswordHistoryLength(ComponentName, int)
301      */
302     public static final int TAG_PASSWORD_HISTORY_LENGTH_SET =
303             SecurityLogTags.SECURITY_PASSWORD_HISTORY_LENGTH_SET;
304 
305     /**
306      * Indicates that an admin has set a maximum screen lock timeout. The log entry contains the
307      * following information about the event encapsulated in an {@link Object} array, accessible
308      * via {@link SecurityEvent#getData()}:
309      * <li> [0] admin package name ({@code String})
310      * <li> [1] admin user ID ({@code Integer})
311      * <li> [2] target user ID ({@code Integer})
312      * <li> [3] new screen lock timeout in milliseconds ({@code Long})
313      * @see DevicePolicyManager#setMaximumTimeToLock(ComponentName, long)
314      */
315     public static final int TAG_MAX_SCREEN_LOCK_TIMEOUT_SET =
316             SecurityLogTags.SECURITY_MAX_SCREEN_LOCK_TIMEOUT_SET;
317 
318     /**
319      * Indicates that an admin has set a maximum number of failed password attempts before wiping
320      * data. The log entry contains the following information about the event encapsulated in an
321      * {@link Object} array, accessible via {@link SecurityEvent#getData()}:
322      * <li> [0] admin package name ({@code String})
323      * <li> [1] admin user ID ({@code Integer})
324      * <li> [2] target user ID ({@code Integer})
325      * <li> [3] new maximum number of failed password attempts ({@code Integer})
326      * @see DevicePolicyManager#setMaximumFailedPasswordsForWipe(ComponentName, int)
327      */
328     public static final int TAG_MAX_PASSWORD_ATTEMPTS_SET =
329             SecurityLogTags.SECURITY_MAX_PASSWORD_ATTEMPTS_SET;
330 
331     /**
332      * Indicates that an admin has set disabled keyguard features. The log entry contains the
333      * following information about the event encapsulated in an {@link Object} array, accessible via
334      * {@link SecurityEvent#getData()}:
335      * <li> [0] admin package name ({@code String})
336      * <li> [1] admin user ID ({@code Integer})
337      * <li> [2] target user ID ({@code Integer})
338      * <li> [3] disabled keyguard feature mask ({@code Integer}).
339      * @see DevicePolicyManager#setKeyguardDisabledFeatures(ComponentName, int)
340      */
341     public static final int TAG_KEYGUARD_DISABLED_FEATURES_SET =
342             SecurityLogTags.SECURITY_KEYGUARD_DISABLED_FEATURES_SET;
343 
344     /**
345      * Indicates that an admin remotely locked the device or profile. The log entry contains the
346      * following information about the event encapsulated in an {@link Object} array, accessible via
347      * {@link SecurityEvent#getData()}:
348      * <li> [0] admin package name ({@code String}),
349      * <li> [1] admin user ID ({@code Integer}).
350      * <li> [2] target user ID ({@code Integer})
351      */
352     public static final int TAG_REMOTE_LOCK = SecurityLogTags.SECURITY_REMOTE_LOCK;
353 
354     /**
355      * Indicates a failure to wipe device or user data. There is no extra payload in the log event.
356      */
357     public static final int TAG_WIPE_FAILURE = SecurityLogTags.SECURITY_WIPE_FAILED;
358 
359     /**
360      * Indicates that a cryptographic key was generated. The log entry contains the following
361      * information about the event, encapsulated in an {@link Object} array and accessible via
362      * {@link SecurityEvent#getData()}:
363      * <li> [0] result ({@code Integer}, 0 if operation failed, 1 if succeeded)
364      * <li> [1] alias of the key ({@code String})
365      * <li> [2] requesting process uid ({@code Integer}).
366      *
367      * If security logging is enabled on organization-owned managed profile devices, only events
368      * happening inside the managed profile will be visible.
369      */
370     public static final int TAG_KEY_GENERATED =
371             SecurityLogTags.SECURITY_KEY_GENERATED;
372 
373     /**
374      * Indicates that a cryptographic key was imported. The log entry contains the following
375      * information about the event, encapsulated in an {@link Object} array and accessible via
376      * {@link SecurityEvent#getData()}:
377      * <li> [0] result ({@code Integer}, 0 if operation failed, 1 if succeeded)
378      * <li> [1] alias of the key ({@code String})
379      * <li> [2] requesting process uid ({@code Integer}).
380      *
381      * If security logging is enabled on organization-owned managed profile devices, only events
382      * happening inside the managed profile will be visible.
383      */
384     public static final int TAG_KEY_IMPORT = SecurityLogTags.SECURITY_KEY_IMPORTED;
385 
386     /**
387      * Indicates that a cryptographic key was destroyed. 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] result ({@code Integer}, 0 if operation failed, 1 if succeeded)
391      * <li> [1] alias of the key ({@code String})
392      * <li> [2] requesting process uid ({@code Integer}).
393      *
394      * If security logging is enabled on organization-owned managed profile devices, only events
395      * happening inside the managed profile will be visible.
396      */
397     public static final int TAG_KEY_DESTRUCTION = SecurityLogTags.SECURITY_KEY_DESTROYED;
398 
399     /**
400      * Indicates that a new root certificate has been installed into system's trusted credential
401      * storage. The log entry contains the following information about the event, encapsulated in an
402      * {@link Object} array and accessible via {@link SecurityEvent#getData()}:
403      * <li> [0] result ({@code Integer}, 0 if operation failed, 1 if succeeded)
404      * <li> [1] subject of the certificate ({@code String}).
405      * <li> [2] which user the certificate is installed for ({@code Integer}), only available from
406      *   version {@link android.os.Build.VERSION_CODES#R}.
407      *
408      * If security logging is enabled on organization-owned managed profile devices, only events
409      * happening inside the managed profile will be visible.
410      */
411     public static final int TAG_CERT_AUTHORITY_INSTALLED =
412             SecurityLogTags.SECURITY_CERT_AUTHORITY_INSTALLED;
413 
414     /**
415      * Indicates that a new root certificate has been removed from system's trusted credential
416      * storage. The log entry contains the following information about the event, encapsulated in an
417      * {@link Object} array and accessible via {@link SecurityEvent#getData()}:
418      * <li> [0] result ({@code Integer}, 0 if operation failed, 1 if succeeded)
419      * <li> [1] subject of the certificate ({@code String}).
420      * <li> [2] which user the certificate is removed from ({@code Integer}), only available from
421      *   version {@link android.os.Build.VERSION_CODES#R}.
422      *
423      * If security logging is enabled on organization-owned managed profile devices, only events
424      * happening inside the managed profile will be visible.
425      */
426     public static final int TAG_CERT_AUTHORITY_REMOVED =
427             SecurityLogTags.SECURITY_CERT_AUTHORITY_REMOVED;
428 
429     /**
430      * Indicates that an admin has set a user restriction. The log entry contains the following
431      * information about the event, encapsulated in an {@link Object} array and accessible via
432      * {@link SecurityEvent#getData()}:
433      * <li> [0] admin package name ({@code String})
434      * <li> [1] admin user ID ({@code Integer})
435      * <li> [2] user restriction ({@code String})
436      * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
437      */
438     public static final int TAG_USER_RESTRICTION_ADDED =
439             SecurityLogTags.SECURITY_USER_RESTRICTION_ADDED;
440 
441     /**
442      * Indicates that an admin has removed a user restriction. The log entry contains the following
443      * information about the event, encapsulated in an {@link Object} array and accessible via
444      * {@link SecurityEvent#getData()}:
445      * <li> [0] admin package name ({@code String})
446      * <li> [1] admin user ID ({@code Integer})
447      * <li> [2] user restriction ({@code String})
448      * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
449      */
450     public static final int TAG_USER_RESTRICTION_REMOVED =
451             SecurityLogTags.SECURITY_USER_RESTRICTION_REMOVED;
452 
453     /**
454      * Indicates that cryptographic functionality self test has completed. The log entry contains an
455      * {@code Integer} payload, indicating the result of the test (0 if the test failed, 1 if
456      * succeeded) and accessible via {@link SecurityEvent#getData()}.
457      */
458     public static final int TAG_CRYPTO_SELF_TEST_COMPLETED =
459             SecurityLogTags.SECURITY_CRYPTO_SELF_TEST_COMPLETED;
460 
461     /**
462      * Indicates a failed cryptographic key integrity check. The log entry contains the following
463      * information about the event, encapsulated in an {@link Object} array and accessible via
464      * {@link SecurityEvent#getData()}:
465      * <li> [0] alias of the key ({@code String})
466      * <li> [1] owner application uid ({@code Integer}).
467      *
468      * If security logging is enabled on organization-owned managed profile devices, only events
469      * happening inside the managed profile will be visible.
470      */
471     public static final int TAG_KEY_INTEGRITY_VIOLATION =
472             SecurityLogTags.SECURITY_KEY_INTEGRITY_VIOLATION;
473 
474     /**
475      * Indicates a failure to validate X.509v3 certificate. The log entry contains a {@code String}
476      * payload indicating the failure reason, accessible via {@link SecurityEvent#getData()}.
477      */
478     public static final int TAG_CERT_VALIDATION_FAILURE =
479             SecurityLogTags.SECURITY_CERT_VALIDATION_FAILURE;
480 
481     /**
482      * Indicates that the admin has set policy to disable camera.
483      * The log entry contains the following information about the event, encapsulated in an
484      * {@link Object} array and accessible via {@link SecurityEvent#getData()}:
485      * <li> [0] admin package name ({@code String})
486      * <li> [1] admin user ID ({@code Integer})
487      * <li> [2] target user ID ({@code Integer})
488      * <li> [3] whether the camera is disabled or not ({@code Integer}, 1 if it's disabled,
489      *      0 if enabled)
490      */
491     public static final int TAG_CAMERA_POLICY_SET =
492             SecurityLogTags.SECURITY_CAMERA_POLICY_SET;
493 
494     /**
495      * Indicates that an admin has set a password complexity requirement, using the platform's
496      * pre-defined complexity levels. The log entry contains the following information about the
497      * event, encapsulated in an {@link Object} array and accessible via
498      * {@link SecurityEvent#getData()}:
499      * <li> [0] admin package name ({@code String})
500      * <li> [1] admin user ID ({@code Integer})
501      * <li> [2] target user ID ({@code Integer})
502      * <li> [3] Password complexity ({@code Integer})
503      *
504      * @see DevicePolicyManager#setRequiredPasswordComplexity(int)
505      */
506     public static final int TAG_PASSWORD_COMPLEXITY_REQUIRED =
507             SecurityLogTags.SECURITY_PASSWORD_COMPLEXITY_REQUIRED;
508 
509     /**
510      * Indicates that a user has just changed their lockscreen password.
511      * The log entry contains the following information about the
512      * event, encapsulated in an {@link Object} array and accessible via
513      * {@link SecurityEvent#getData()}:
514      * <li> [0] complexity for the new password ({@code Integer})
515      * <li> [1] target user ID ({@code Integer})
516      *
517      * <p>Password complexity levels are defined as in
518      * {@link DevicePolicyManager#getPasswordComplexity()}
519      */
520     public static final int TAG_PASSWORD_CHANGED = SecurityLogTags.SECURITY_PASSWORD_CHANGED;
521 
522     /**
523      * Indicates that an event occurred as the device attempted to connect to
524      * a managed WiFi network. The log entry contains the following information about the
525      * event, encapsulated in an {@link Object} array and accessible via
526      * {@link SecurityEvent#getData()}:
527      * <li> [0] Last 2 octets of the network BSSID ({@code String}, in the form "xx:xx:xx:xx:AA:BB")
528      * <li> [1] Type of event that occurred ({@code String}). Event types are CONNECTED,
529      *      DISCONNECTED, ASSOCIATING, ASSOCIATED, EAP_METHOD_SELECTED, EAP_FAILURE,
530      *      SSID_TEMP_DISABLED, and OPEN_SSL_FAILURE.
531      * <li> [2] Optional human-readable failure reason, empty string if none ({@code String})
532      */
533     public static final int TAG_WIFI_CONNECTION = SecurityLogTags.SECURITY_WIFI_CONNECTION;
534 
535     /**
536      * Indicates that the device disconnects from a managed WiFi network.
537      * The log entry contains the following information about the
538      * event, encapsulated in an {@link Object} array and accessible via
539      * {@link SecurityEvent#getData()}:
540      * <li> [0] Last 2 octets of the network BSSID ({@code String}, in the form "xx:xx:xx:xx:AA:BB")
541      * <li> [1] Optional human-readable disconnection reason, empty string if none ({@code String})
542      */
543     public static final int TAG_WIFI_DISCONNECTION = SecurityLogTags.SECURITY_WIFI_DISCONNECTION;
544 
545     /**
546      * Indicates that the device attempts to connect to a Bluetooth device.
547      * The log entry contains the following information about the
548      * event, encapsulated in an {@link Object} array and accessible via
549      * {@link SecurityEvent#getData()}:
550      * <li> [0] The MAC address of the Bluetooth device ({@code String})
551      * <li> [1] Whether the connection is successful ({@code Integer}, 1 if successful, 0 otherwise)
552      * <li> [2] Optional human-readable failure reason, empty string if none ({@code String})
553      */
554     public static final int TAG_BLUETOOTH_CONNECTION =
555             SecurityLogTags.SECURITY_BLUETOOTH_CONNECTION;
556 
557     /**
558      * Indicates that the device disconnects from a connected Bluetooth device.
559      * The log entry contains the following information about the
560      * event, encapsulated in an {@link Object} array and accessible via
561      * {@link SecurityEvent#getData()}:
562      * <li> [0] The MAC address of the connected Bluetooth device ({@code String})
563      * <li> [1] Optional human-readable disconnection reason, empty string if none ({@code String})
564      */
565     public static final int TAG_BLUETOOTH_DISCONNECTION =
566             SecurityLogTags.SECURITY_BLUETOOTH_DISCONNECTION;
567 
568     /**
569      * Indicates that a package is installed.
570      * The log entry contains the following information about the
571      * event, encapsulated in an {@link Object} array and accessible via
572      * {@link SecurityEvent#getData()}:
573      * <li> [0] Name of the package being installed ({@code String})
574      * <li> [1] Package version code ({@code Long})
575      * <li> [2] UserId of the user that installed this package ({@code Integer})
576      */
577     public static final int TAG_PACKAGE_INSTALLED = SecurityLogTags.SECURITY_PACKAGE_INSTALLED;
578 
579     /**
580      * Indicates that a package is updated.
581      * The log entry contains the following information about the
582      * event, encapsulated in an {@link Object} array and accessible via
583      * {@link SecurityEvent#getData()}:
584      * <li> [0] Name of the package being updated ({@code String})
585      * <li> [1] Package version code ({@code Long})
586      * <li> [2] UserId of the user that updated this package ({@code Integer})
587      */
588     public static final int TAG_PACKAGE_UPDATED = SecurityLogTags.SECURITY_PACKAGE_UPDATED;
589 
590     /**
591      * Indicates that a package is uninstalled.
592      * The log entry contains the following information about the
593      * event, encapsulated in an {@link Object} array and accessible via
594      * {@link SecurityEvent#getData()}:
595      * <li> [0] Name of the package being uninstalled ({@code String})
596      * <li> [1] Package version code ({@code Long})
597      * <li> [2] UserId of the user that uninstalled this package ({@code Integer})
598      */
599     public static final int TAG_PACKAGE_UNINSTALLED = SecurityLogTags.SECURITY_PACKAGE_UNINSTALLED;
600 
601     /**
602      * Event severity level indicating that the event corresponds to normal workflow.
603      */
604     public static final int LEVEL_INFO = 1;
605 
606     /**
607      * Event severity level indicating that the event may require admin attention.
608      */
609     public static final int LEVEL_WARNING = 2;
610 
611     /**
612      * Event severity level indicating that the event requires urgent admin action.
613      */
614     public static final int LEVEL_ERROR = 3;
615 
616     /**
617      * Returns if security logging is enabled. Log producers should only write new logs if this is
618      * true. Under the hood this is the logical AND of whether device owner exists and whether
619      * it enables logging by setting the system property {@link #PROPERTY_LOGGING_ENABLED}.
620      * @hide
621      */
isLoggingEnabled()622     public static native boolean isLoggingEnabled();
623 
624     /**
625      * @hide
626      */
setLoggingEnabledProperty(boolean enabled)627     public static void setLoggingEnabledProperty(boolean enabled) {
628         SystemProperties.set(PROPERTY_LOGGING_ENABLED, enabled ? "true" : "false");
629     }
630 
631     /**
632      * @hide
633      */
getLoggingEnabledProperty()634     public static boolean getLoggingEnabledProperty() {
635         return SystemProperties.getBoolean(PROPERTY_LOGGING_ENABLED, false);
636     }
637 
638     /**
639      * A class representing a security event log entry.
640      */
641     public static final class SecurityEvent implements Parcelable {
642         private Event mEvent;
643         private long mId;
644 
645         /**
646          * Constructor used by native classes to generate SecurityEvent instances.
647          * @hide
648          */
649         @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
SecurityEvent(byte[] data)650         /* package */ SecurityEvent(byte[] data) {
651             this(0, data);
652         }
653 
654         /**
655          * Constructor used by Parcelable.Creator to generate SecurityEvent instances.
656          * @hide
657          */
SecurityEvent(Parcel source)658         /* package */ SecurityEvent(Parcel source) {
659             this(source.readLong(), source.createByteArray());
660         }
661 
662         /** @hide */
663         @TestApi
SecurityEvent(long id, byte[] data)664         public SecurityEvent(long id, byte[] data) {
665             mId = id;
666             mEvent = Event.fromBytes(data);
667         }
668 
669         /**
670          * Returns the timestamp in nano seconds when this event was logged.
671          */
getTimeNanos()672         public long getTimeNanos() {
673             return mEvent.getTimeNanos();
674         }
675 
676         /**
677          * Returns the tag of this log entry, which specifies entry's semantics.
678          */
getTag()679         public @SecurityLogTag int getTag() {
680             return mEvent.getTag();
681         }
682 
683         /**
684          * Returns the payload contained in this log entry or {@code null} if there is no payload.
685          */
getData()686         public Object getData() {
687             return mEvent.getData();
688         }
689 
690         /** @hide */
getIntegerData(int index)691         public int getIntegerData(int index) {
692             return (Integer) ((Object[]) mEvent.getData())[index];
693         }
694 
695         /** @hide */
getStringData(int index)696         public String getStringData(int index) {
697             return (String) ((Object[]) mEvent.getData())[index];
698         }
699 
700         /**
701          * @hide
702          */
setId(long id)703         public void setId(long id) {
704             this.mId = id;
705         }
706 
707         /**
708          * Returns the id of the event, where the id monotonically increases for each event. The id
709          * is reset when the device reboots, and when security logging is enabled.
710          */
getId()711         public long getId() {
712             return mId;
713         }
714 
715         /**
716          * Returns severity level for the event.
717          */
getLogLevel()718         public @SecurityLogLevel int getLogLevel() {
719             switch (getTag()) {
720                 case TAG_ADB_SHELL_INTERACTIVE:
721                 case TAG_ADB_SHELL_CMD:
722                 case TAG_SYNC_RECV_FILE:
723                 case TAG_SYNC_SEND_FILE:
724                 case TAG_APP_PROCESS_START:
725                 case TAG_KEYGUARD_DISMISSED:
726                 case TAG_KEYGUARD_SECURED:
727                 case TAG_OS_STARTUP:
728                 case TAG_OS_SHUTDOWN:
729                 case TAG_LOGGING_STARTED:
730                 case TAG_LOGGING_STOPPED:
731                 case TAG_MEDIA_MOUNT:
732                 case TAG_MEDIA_UNMOUNT:
733                 case TAG_PASSWORD_EXPIRATION_SET:
734                 case TAG_PASSWORD_COMPLEXITY_SET:
735                 case TAG_PASSWORD_HISTORY_LENGTH_SET:
736                 case TAG_MAX_SCREEN_LOCK_TIMEOUT_SET:
737                 case TAG_MAX_PASSWORD_ATTEMPTS_SET:
738                 case TAG_USER_RESTRICTION_ADDED:
739                 case TAG_USER_RESTRICTION_REMOVED:
740                 case TAG_CAMERA_POLICY_SET:
741                 case TAG_PASSWORD_COMPLEXITY_REQUIRED:
742                 case TAG_PASSWORD_CHANGED:
743                     return LEVEL_INFO;
744                 case TAG_CERT_AUTHORITY_REMOVED:
745                 case TAG_CRYPTO_SELF_TEST_COMPLETED:
746                     return getSuccess() ? LEVEL_INFO : LEVEL_ERROR;
747                 case TAG_CERT_AUTHORITY_INSTALLED:
748                 case TAG_KEYGUARD_DISMISS_AUTH_ATTEMPT:
749                 case TAG_KEY_IMPORT:
750                 case TAG_KEY_DESTRUCTION:
751                 case TAG_KEY_GENERATED:
752                     return getSuccess() ? LEVEL_INFO : LEVEL_WARNING;
753                 case TAG_LOG_BUFFER_SIZE_CRITICAL:
754                 case TAG_WIPE_FAILURE:
755                 case TAG_KEY_INTEGRITY_VIOLATION:
756                     return LEVEL_ERROR;
757                 case TAG_CERT_VALIDATION_FAILURE:
758                     return LEVEL_WARNING;
759                 default:
760                     return LEVEL_INFO;
761             }
762         }
763 
764         // Success/failure if present is encoded as an integer in the first (0th) element of data.
getSuccess()765         private boolean getSuccess() {
766             final Object data = getData();
767             if (data == null || !(data instanceof Object[])) {
768                 return false;
769             }
770 
771             final Object[] array = (Object[]) data;
772             return array.length >= 1 && array[0] instanceof Integer && (Integer) array[0] != 0;
773         }
774 
775         /**
776          * Returns a copy of the security event suitable to be consumed by the provided user.
777          * This method will either return the original event itself if the event does not contain
778          * any sensitive data; or a copy of itself but with sensitive information redacted; or
779          * {@code null} if the entire event should not be accessed by the given user.
780          *
781          * @param accessingUser which user this security event is to be accessed, must be a
782          *     concrete user id.
783          * @hide
784          */
redact(int accessingUser)785         public SecurityEvent redact(int accessingUser) {
786             // Which user the event is associated with, for the purpose of log redaction.
787             final int userId;
788             switch (getTag()) {
789                 case SecurityLog.TAG_ADB_SHELL_CMD:
790                     return new SecurityEvent(getId(), mEvent.withNewData("").getBytes());
791                 case SecurityLog.TAG_MEDIA_MOUNT:
792                 case SecurityLog.TAG_MEDIA_UNMOUNT:
793                     // Partial redaction
794                     String mountPoint;
795                     try {
796                         mountPoint = getStringData(0);
797                     } catch (Exception e) {
798                         return null;
799                     }
800                     return new SecurityEvent(getId(),
801                             mEvent.withNewData(new Object[] {mountPoint, ""}).getBytes());
802                 case SecurityLog.TAG_APP_PROCESS_START:
803                     try {
804                         userId = UserHandle.getUserId(getIntegerData(2));
805                     } catch (Exception e) {
806                         return null;
807                     }
808                     break;
809                 case SecurityLog.TAG_CERT_AUTHORITY_INSTALLED:
810                 case SecurityLog.TAG_CERT_AUTHORITY_REMOVED:
811                 case SecurityLog.TAG_PACKAGE_INSTALLED:
812                 case SecurityLog.TAG_PACKAGE_UPDATED:
813                 case SecurityLog.TAG_PACKAGE_UNINSTALLED:
814                     try {
815                         userId = getIntegerData(2);
816                     } catch (Exception e) {
817                         return null;
818                     }
819                     break;
820                 case SecurityLog.TAG_KEY_GENERATED:
821                 case SecurityLog.TAG_KEY_IMPORT:
822                 case SecurityLog.TAG_KEY_DESTRUCTION:
823                     try {
824                         userId = UserHandle.getUserId(getIntegerData(2));
825                     } catch (Exception e) {
826                         return null;
827                     }
828                     break;
829                 case SecurityLog.TAG_KEY_INTEGRITY_VIOLATION:
830                     try {
831                         userId = UserHandle.getUserId(getIntegerData(1));
832                     } catch (Exception e) {
833                         return null;
834                     }
835                     break;
836                 case SecurityLog.TAG_PASSWORD_CHANGED:
837                     try {
838                         userId = getIntegerData(1);
839                     } catch (Exception e) {
840                         return null;
841                     }
842                     break;
843                 default:
844                     userId = UserHandle.USER_NULL;
845             }
846             // If the event is not user-specific, or matches the accessing user, return it
847             // unmodified, else redact by returning null
848             if (userId == UserHandle.USER_NULL || accessingUser == userId) {
849                 return this;
850             } else {
851                 return null;
852             }
853         }
854 
855         @Override
describeContents()856         public int describeContents() {
857             return 0;
858         }
859 
860         @Override
writeToParcel(Parcel dest, int flags)861         public void writeToParcel(Parcel dest, int flags) {
862             dest.writeLong(mId);
863             dest.writeByteArray(mEvent.getBytes());
864         }
865 
866         public static final @android.annotation.NonNull Parcelable.Creator<SecurityEvent> CREATOR =
867                 new Parcelable.Creator<SecurityEvent>() {
868             @Override
869             public SecurityEvent createFromParcel(Parcel source) {
870                 return new SecurityEvent(source);
871             }
872 
873             @Override
874             public SecurityEvent[] newArray(int size) {
875                 return new SecurityEvent[size];
876             }
877         };
878 
879         /**
880          * @hide
881          */
882         @Override
equals(@ullable Object o)883         public boolean equals(@Nullable Object o) {
884             if (this == o) return true;
885             if (o == null || getClass() != o.getClass()) return false;
886             SecurityEvent other = (SecurityEvent) o;
887             return mEvent.equals(other.mEvent) && mId == other.mId;
888         }
889 
890         /**
891          * @hide
892          */
893         @Override
hashCode()894         public int hashCode() {
895             return Objects.hash(mEvent, mId);
896         }
897 
898         /** @hide */
eventEquals(SecurityEvent other)899         public boolean eventEquals(SecurityEvent other) {
900             return other != null && mEvent.equals(other.mEvent);
901         }
902     }
903 
904     /**
905      * Redacts events in-place according to which user will consume the events.
906      *
907      * @param accessingUser which user will consume the redacted events, or UserHandle.USER_ALL if
908      *     redaction should be skipped.
909      * @hide
910      */
redactEvents(ArrayList<SecurityEvent> logList, int accessingUser)911     public static void redactEvents(ArrayList<SecurityEvent> logList, int accessingUser) {
912         if (accessingUser == UserHandle.USER_ALL) return;
913         int end = 0;
914         for (int i = 0; i < logList.size(); i++) {
915             SecurityEvent event = logList.get(i);
916             event = event.redact(accessingUser);
917             if (event != null) {
918                 logList.set(end, event);
919                 end++;
920             }
921         }
922         for (int i = logList.size() - 1; i >= end; i--) {
923             logList.remove(i);
924         }
925     }
926 
927     /**
928      * Retrieve all security logs and return immediately.
929      * @hide
930      */
readEvents(Collection<SecurityEvent> output)931     public static native void readEvents(Collection<SecurityEvent> output) throws IOException;
932 
933     /**
934      * Retrieve all security logs since the given timestamp in nanoseconds and return immediately.
935      * @hide
936      */
readEventsSince(long timestamp, Collection<SecurityEvent> output)937     public static native void readEventsSince(long timestamp, Collection<SecurityEvent> output)
938             throws IOException;
939 
940     /**
941      * Retrieve all security logs before the last reboot. May return corrupted data due to
942      * unreliable pstore.
943      * @hide
944      */
readPreviousEvents(Collection<SecurityEvent> output)945     public static native void readPreviousEvents(Collection<SecurityEvent> output)
946             throws IOException;
947 
948     /**
949      * Retrieve all security logs whose timestamp is equal to or greater than the given timestamp in
950      * nanoseconds. This method will block until either the last log earlier than the given
951      * timestamp is about to be pruned, or after a 2-hour timeout has passed.
952      * @hide
953      */
readEventsOnWrapping(long timestamp, Collection<SecurityEvent> output)954     public static native void readEventsOnWrapping(long timestamp, Collection<SecurityEvent> output)
955             throws IOException;
956 
957     /**
958      * Write a log entry to the underlying storage, with several payloads.
959      * Supported types of payload are: integer, long, float, string plus array of supported types.
960      *
961      * <p>Security log is part of Android's device management capability that tracks
962      * security-sensitive events for auditing purposes.
963      *
964      * @param tag the tag ID of the security event
965      * @param payloads a list of payload values. Each tag dictates the expected payload types
966      *                 and their meanings
967      * @see DevicePolicyManager#setSecurityLoggingEnabled(ComponentName, boolean)
968      *
969      * @hide
970      */
971     // TODO(b/218658622): enforce WRITE_SECURITY_LOG in logd.
972     @SystemApi
973     @RequiresPermission(Manifest.permission.WRITE_SECURITY_LOG)
writeEvent(@ecurityLogTag int tag, @NonNull Object... payloads)974     public static native int writeEvent(@SecurityLogTag int tag, @NonNull Object... payloads);
975 }
976