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 com.android.cts.verifier.managedprovisioning;
18 
19 import android.Manifest;
20 import android.app.Activity;
21 import android.app.PendingIntent;
22 import android.app.admin.DevicePolicyManager;
23 import android.content.ComponentName;
24 import android.content.Context;
25 import android.content.Intent;
26 import android.content.IntentFilter;
27 import android.content.pm.PackageInstaller;
28 import android.content.pm.PackageManager;
29 import android.graphics.BitmapFactory;
30 import android.net.ProxyInfo;
31 import android.os.Bundle;
32 import android.os.UserHandle;
33 import android.os.UserManager;
34 import android.provider.ContactsContract;
35 import android.provider.MediaStore;
36 import android.provider.Settings;
37 import android.util.Log;
38 
39 import com.android.cts.verifier.R;
40 import com.android.cts.verifier.managedprovisioning.Utils;
41 
42 import java.io.File;
43 import java.io.FileInputStream;
44 import java.io.InputStream;
45 import java.io.OutputStream;
46 import java.util.ArrayList;
47 import java.util.List;
48 import java.util.concurrent.TimeUnit;
49 
50 public class CommandReceiverActivity extends Activity {
51     private static final String TAG = "CommandReceiverActivity";
52 
53     public static final String ACTION_EXECUTE_COMMAND =
54             "com.android.cts.verifier.managedprovisioning.action.EXECUTE_COMMAND";
55     public static final String EXTRA_COMMAND =
56             "com.android.cts.verifier.managedprovisioning.extra.COMMAND";
57 
58     public static final String COMMAND_SET_USER_RESTRICTION = "set-user_restriction";
59     public static final String COMMAND_DISALLOW_KEYGUARD_UNREDACTED_NOTIFICATIONS =
60             "disallow-keyguard-unredacted-notifications";
61     public static final String COMMAND_SET_AUTO_TIME_REQUIRED = "set-auto-time-required";
62     public static final String COMMAND_SET_GLOBAL_SETTING =
63             "set-global-setting";
64     public static final String COMMAND_SET_MAXIMUM_TO_LOCK = "set-maximum-time-to-lock";
65     public static final String COMMAND_SET_PASSWORD_QUALITY = "set-password-quality";
66     public static final String COMMAND_SET_KEYGUARD_DISABLED = "set-keyguard-disabled";
67     public static final String COMMAND_SET_LOCK_SCREEN_INFO = "set-lock-screen-info";
68     public static final String COMMAND_SET_STATUSBAR_DISABLED = "set-statusbar-disabled";
69     public static final String COMMAND_ALLOW_ONLY_SYSTEM_INPUT_METHODS =
70             "allow-only-system-input-methods";
71     public static final String COMMAND_ALLOW_ONLY_SYSTEM_ACCESSIBILITY_SERVICES =
72             "allow-only-system-accessibility-services";
73     public static final String COMMAND_CLEAR_POLICIES = "clear-policies";
74     public static final String COMMAND_REMOVE_DEVICE_OWNER = "remove-device-owner";
75     public static final String COMMAND_REQUEST_BUGREPORT = "request-bugreport";
76     public static final String COMMAND_SET_USER_ICON = "set-user-icon";
77     public static final String COMMAND_RETRIEVE_NETWORK_LOGS = "retrieve-network-logs";
78     public static final String COMMAND_RETRIEVE_SECURITY_LOGS = "retrieve-security-logs";
79     public static final String COMMAND_SET_ORGANIZATION_NAME = "set-organization-name";
80     public static final String COMMAND_ENABLE_NETWORK_LOGGING = "enable-network-logging";
81     public static final String COMMAND_DISABLE_NETWORK_LOGGING = "disable-network-logging";
82     public static final String COMMAND_INSTALL_HELPER_PACKAGE = "install-helper-package";
83     public static final String COMMAND_UNINSTALL_HELPER_PACKAGE = "uninstall-helper-package";
84     public static final String COMMAND_SET_PERMISSION_GRANT_STATE = "set-permission-grant-state";
85     public static final String COMMAND_ADD_PERSISTENT_PREFERRED_ACTIVITIES =
86             "add-persistent-preferred-activities";
87     public static final String COMMAND_CLEAR_PERSISTENT_PREFERRED_ACTIVITIES =
88             "clear-persistent-preferred-activities";
89     public static final String COMMAND_CREATE_MANAGED_PROFILE = "create-managed-profile";
90     public static final String COMMAND_REMOVE_MANAGED_PROFILE = "remove-managed-profile";
91     public static final String COMMAND_SET_ALWAYS_ON_VPN = "set-always-on-vpn";
92     public static final String COMMAND_CLEAR_ALWAYS_ON_VPN = "clear-always-on-vpn";
93     public static final String COMMAND_SET_GLOBAL_HTTP_PROXY = "set-global-http-proxy";
94     public static final String COMMAND_CLEAR_GLOBAL_HTTP_PROXY = "clear-global-http-proxy";
95     public static final String COMMAND_INSTALL_CA_CERT = "install-ca-cert";
96     public static final String COMMAND_CLEAR_CA_CERT = "clear-ca-cert";
97     public static final String COMMAND_SET_MAXIMUM_PASSWORD_ATTEMPTS =
98             "set-maximum-password-attempts";
99     public static final String COMMAND_CLEAR_MAXIMUM_PASSWORD_ATTEMPTS =
100             "clear-maximum-password-attempts";
101     public static final String COMMAND_SET_DEFAULT_IME = "set-default-ime";
102     public static final String COMMAND_CLEAR_DEFAULT_IME = "clear-default-ime";
103 
104     public static final String EXTRA_USER_RESTRICTION =
105             "com.android.cts.verifier.managedprovisioning.extra.USER_RESTRICTION";
106     public static final String EXTRA_SETTING =
107             "com.android.cts.verifier.managedprovisioning.extra.SETTING";
108     // This extra can be used along with a command extra to set policy to
109     // specify if that policy is enforced or not.
110     public static final String EXTRA_ENFORCED =
111             "com.android.cts.verifier.managedprovisioning.extra.ENFORCED";
112     public static final String EXTRA_VALUE =
113             "com.android.cts.verifier.managedprovisioning.extra.VALUE";
114     public static final String EXTRA_ORGANIZATION_NAME =
115             "com.android.cts.verifier.managedprovisioning.extra.ORGANIZATION_NAME";
116     public static final String EXTRA_PERMISSION =
117             "com.android.cts.verifier.managedprovisioning.extra.PERMISSION";
118     public static final String EXTRA_GRANT_STATE =
119             "com.android.cts.verifier.managedprovisioning.extra.GRANT_STATE";
120 
121     // We care about installing and uninstalling only. It does not matter what apk is used.
122     // NotificationBot.apk is a good choice because it comes bundled with the CTS verifier.
123     protected static final String HELPER_APP_LOCATION = "/sdcard/NotificationBot.apk";
124     protected static final String HELPER_APP_PKG = "com.android.cts.robot";
125 
126     public static final String ACTION_INSTALL_COMPLETE =
127             "com.android.cts.verifier.managedprovisioning.action.ACTION_INSTALL_COMPLETE";
128     public static final String ACTION_UNINSTALL_COMPLETE =
129             "com.android.cts.verifier.managedprovisioning.action.ACTION_UNINSTALL_COMPLETE";
130 
131     /*
132      * The CA cert below is the content of cacert.pem as generated by:
133      *
134      * openssl req -new -x509 -days 3650 -extensions v3_ca -keyout cakey.pem -out cacert.pem
135      */
136     private static final String TEST_CA =
137             "-----BEGIN CERTIFICATE-----\n" +
138             "MIIDXTCCAkWgAwIBAgIJAK9Tl/F9V8kSMA0GCSqGSIb3DQEBCwUAMEUxCzAJBgNV\n" +
139             "BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX\n" +
140             "aWRnaXRzIFB0eSBMdGQwHhcNMTUwMzA2MTczMjExWhcNMjUwMzAzMTczMjExWjBF\n" +
141             "MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50\n" +
142             "ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n" +
143             "CgKCAQEAvItOutsE75WBTgTyNAHt4JXQ3JoseaGqcC3WQij6vhrleWi5KJ0jh1/M\n" +
144             "Rpry7Fajtwwb4t8VZa0NuM2h2YALv52w1xivql88zce/HU1y7XzbXhxis9o6SCI+\n" +
145             "oVQSbPeXRgBPppFzBEh3ZqYTVhAqw451XhwdA4Aqs3wts7ddjwlUzyMdU44osCUg\n" +
146             "kVg7lfPf9sTm5IoHVcfLSCWH5n6Nr9sH3o2ksyTwxuOAvsN11F/a0mmUoPciYPp+\n" +
147             "q7DzQzdi7akRG601DZ4YVOwo6UITGvDyuAAdxl5isovUXqe6Jmz2/myTSpAKxGFs\n" +
148             "jk9oRoG6WXWB1kni490GIPjJ1OceyQIDAQABo1AwTjAdBgNVHQ4EFgQUH1QIlPKL\n" +
149             "p2OQ/AoLOjKvBW4zK3AwHwYDVR0jBBgwFoAUH1QIlPKLp2OQ/AoLOjKvBW4zK3Aw\n" +
150             "DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAcMi4voMMJHeQLjtq8Oky\n" +
151             "Azpyk8moDwgCd4llcGj7izOkIIFqq/lyqKdtykVKUWz2bSHO5cLrtaOCiBWVlaCV\n" +
152             "DYAnnVLM8aqaA6hJDIfaGs4zmwz0dY8hVMFCuCBiLWuPfiYtbEmjHGSmpQTG6Qxn\n" +
153             "ZJlaK5CZyt5pgh5EdNdvQmDEbKGmu0wpCq9qjZImwdyAul1t/B0DrsWApZMgZpeI\n" +
154             "d2od0VBrCICB1K4p+C51D93xyQiva7xQcCne+TAnGNy9+gjQ/MyR8MRpwRLv5ikD\n" +
155             "u0anJCN8pXo6IMglfMAsoton1J6o5/ae5uhC6caQU8bNUsCK570gpNfjkzo6rbP0\n" +
156             "wQ==\n" +
157             "-----END CERTIFICATE-----";
158 
159     private ComponentName mAdmin;
160     private DevicePolicyManager mDpm;
161     private UserManager mUm;
162 
163     @Override
onCreate(Bundle savedInstanceState)164     public void onCreate(Bundle savedInstanceState) {
165         super.onCreate(savedInstanceState);
166         final Intent intent = getIntent();
167         try {
168             mDpm = (DevicePolicyManager) getSystemService(
169                     Context.DEVICE_POLICY_SERVICE);
170             mUm = (UserManager) getSystemService(Context.USER_SERVICE);
171             mAdmin = DeviceAdminTestReceiver.getReceiverComponentName();
172             Log.i(TAG, "Command: " + intent);
173 
174             final String command = getIntent().getStringExtra(EXTRA_COMMAND);
175             switch (command) {
176                 case COMMAND_SET_USER_RESTRICTION: {
177                     String restrictionKey = intent.getStringExtra(EXTRA_USER_RESTRICTION);
178                     boolean enforced = intent.getBooleanExtra(EXTRA_ENFORCED, false);
179                     if (enforced) {
180                         mDpm.addUserRestriction(mAdmin, restrictionKey);
181                     } else {
182                         mDpm.clearUserRestriction(mAdmin, restrictionKey);
183                     }
184                 } break;
185                 case COMMAND_DISALLOW_KEYGUARD_UNREDACTED_NOTIFICATIONS: {
186                     boolean enforced = intent.getBooleanExtra(EXTRA_ENFORCED, false);
187                     mDpm.setKeyguardDisabledFeatures(mAdmin, enforced
188                             ? DevicePolicyManager.KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS
189                             : 0);
190                 } break;
191                 case COMMAND_SET_AUTO_TIME_REQUIRED: {
192                     mDpm.setAutoTimeRequired(mAdmin,
193                             intent.getBooleanExtra(EXTRA_ENFORCED, false));
194                 }
195                 case COMMAND_SET_LOCK_SCREEN_INFO: {
196                     mDpm.setDeviceOwnerLockScreenInfo(mAdmin, intent.getStringExtra(EXTRA_VALUE));
197                 }
198                 case COMMAND_SET_MAXIMUM_TO_LOCK: {
199                     final long timeInSeconds = Long.parseLong(intent.getStringExtra(EXTRA_VALUE));
200                     mDpm.setMaximumTimeToLock(mAdmin,
201                             TimeUnit.SECONDS.toMillis(timeInSeconds) /* in milliseconds */);
202                 } break;
203                 case COMMAND_SET_PASSWORD_QUALITY: {
204                     int quality = intent.getIntExtra(EXTRA_VALUE, 0);
205                     mDpm.setPasswordQuality(mAdmin, quality);
206                 } break;
207                 case COMMAND_SET_KEYGUARD_DISABLED: {
208                     boolean enforced = intent.getBooleanExtra(EXTRA_ENFORCED, false);
209                     if (enforced) {
210                         mDpm.resetPassword(null, 0);
211                     }
212                     mDpm.setKeyguardDisabled(mAdmin, enforced);
213                 } break;
214                 case COMMAND_SET_STATUSBAR_DISABLED: {
215                     boolean enforced = intent.getBooleanExtra(EXTRA_ENFORCED, false);
216                     mDpm.setStatusBarDisabled(mAdmin, enforced);
217                 } break;
218                 case COMMAND_ALLOW_ONLY_SYSTEM_INPUT_METHODS: {
219                     boolean enforced = intent.getBooleanExtra(EXTRA_ENFORCED, false);
220                     mDpm.setPermittedInputMethods(mAdmin, enforced ? new ArrayList() : null);
221                 } break;
222                 case COMMAND_ALLOW_ONLY_SYSTEM_ACCESSIBILITY_SERVICES: {
223                     boolean enforced = intent.getBooleanExtra(EXTRA_ENFORCED, false);
224                     mDpm.setPermittedAccessibilityServices(mAdmin,
225                             enforced ? new ArrayList() : null);
226                 } break;
227                 case COMMAND_SET_GLOBAL_SETTING: {
228                     final String setting = intent.getStringExtra(EXTRA_SETTING);
229                     final String value = intent.getStringExtra(EXTRA_VALUE);
230                     mDpm.setGlobalSetting(mAdmin, setting, value);
231                 } break;
232                 case COMMAND_REMOVE_DEVICE_OWNER: {
233                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
234                         return;
235                     }
236                     clearAllPoliciesAndRestrictions();
237                     mDpm.clearDeviceOwnerApp(getPackageName());
238                 } break;
239                 case COMMAND_REQUEST_BUGREPORT: {
240                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
241                         return;
242                     }
243                     final boolean bugreportStarted = mDpm.requestBugreport(mAdmin);
244                     if (!bugreportStarted) {
245                         Utils.showBugreportNotification(this, getString(
246                                 R.string.bugreport_already_in_progress),
247                                 Utils.BUGREPORT_NOTIFICATION_ID);
248                     }
249                 } break;
250                 case COMMAND_CLEAR_POLICIES: {
251                     int mode = intent.getIntExtra(PolicyTransparencyTestListActivity.EXTRA_MODE,
252                             PolicyTransparencyTestListActivity.MODE_DEVICE_OWNER);
253                     if (mode == PolicyTransparencyTestListActivity.MODE_DEVICE_OWNER) {
254                         if (!mDpm.isDeviceOwnerApp(getPackageName())) {
255                             return;
256                         }
257                         clearAllPoliciesAndRestrictions();
258                     } else if(mode == PolicyTransparencyTestListActivity.MODE_PROFILE_OWNER) {
259                         if (!mDpm.isProfileOwnerApp(getPackageName())) {
260                             return;
261                         }
262                         clearProfileOwnerRelatedPoliciesAndRestrictions();
263                     }
264                     // No policies need to be cleared for COMP at the moment.
265                 } break;
266                 case COMMAND_SET_USER_ICON: {
267                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
268                         return;
269                     }
270                     mDpm.setUserIcon(mAdmin, BitmapFactory.decodeResource(getResources(),
271                             com.android.cts.verifier.R.drawable.icon));
272                 } break;
273                 case COMMAND_RETRIEVE_NETWORK_LOGS: {
274                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
275                         return;
276                     }
277                     mDpm.setNetworkLoggingEnabled(mAdmin, true);
278                     mDpm.retrieveNetworkLogs(mAdmin, 0 /* batchToken */);
279                     mDpm.setNetworkLoggingEnabled(mAdmin, false);
280                 } break;
281                 case COMMAND_RETRIEVE_SECURITY_LOGS: {
282                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
283                         return;
284                     }
285                     mDpm.setSecurityLoggingEnabled(mAdmin, true);
286                     mDpm.retrieveSecurityLogs(mAdmin);
287                     mDpm.setSecurityLoggingEnabled(mAdmin, false);
288                 } break;
289                 case COMMAND_SET_ORGANIZATION_NAME: {
290                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
291                         return;
292                     }
293                     mDpm.setOrganizationName(mAdmin,
294                             intent.getStringExtra(EXTRA_ORGANIZATION_NAME));
295                 } break;
296                 case COMMAND_ENABLE_NETWORK_LOGGING: {
297                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
298                         return;
299                     }
300                     mDpm.setNetworkLoggingEnabled(mAdmin, true);
301                 } break;
302                 case COMMAND_DISABLE_NETWORK_LOGGING: {
303                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
304                         return;
305                     }
306                     mDpm.setNetworkLoggingEnabled(mAdmin, false);
307                 } break;
308                 case COMMAND_INSTALL_HELPER_PACKAGE: {
309                     installHelperPackage();
310                 } break;
311                 case COMMAND_UNINSTALL_HELPER_PACKAGE: {
312                     uninstallHelperPackage();
313                 } break;
314                 case COMMAND_SET_PERMISSION_GRANT_STATE: {
315                     mDpm.setPermissionGrantState(mAdmin, getPackageName(),
316                             intent.getStringExtra(EXTRA_PERMISSION),
317                             intent.getIntExtra(EXTRA_GRANT_STATE,
318                                     DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT));
319                 } break;
320                 case COMMAND_ADD_PERSISTENT_PREFERRED_ACTIVITIES: {
321                     final ComponentName componentName =
322                             EnterprisePrivacyTestDefaultAppActivity.COMPONENT_NAME;
323                     // Browser
324                     IntentFilter filter = new IntentFilter();
325                     filter.addAction(Intent.ACTION_VIEW);
326                     filter.addCategory(Intent.CATEGORY_BROWSABLE);
327                     filter.addDataScheme("http");
328                     mDpm.addPersistentPreferredActivity(mAdmin, filter, componentName);
329                     // Camera
330                     filter = new IntentFilter();
331                     filter.addAction(MediaStore.ACTION_IMAGE_CAPTURE);
332                     filter.addAction(MediaStore.ACTION_VIDEO_CAPTURE);
333                     mDpm.addPersistentPreferredActivity(mAdmin, filter, componentName);
334                     // Map
335                     filter = new IntentFilter();
336                     filter.addAction(Intent.ACTION_VIEW);
337                     filter.addDataScheme("geo");
338                     mDpm.addPersistentPreferredActivity(mAdmin, filter, componentName);
339                     // E-mail
340                     filter = new IntentFilter();
341                     filter.addAction(Intent.ACTION_SENDTO);
342                     filter.addAction(Intent.ACTION_SEND);
343                     filter.addAction(Intent.ACTION_SEND_MULTIPLE);
344                     mDpm.addPersistentPreferredActivity(mAdmin, filter, componentName);
345                     // Calendar
346                     filter = new IntentFilter();
347                     filter.addAction(Intent.ACTION_INSERT);
348                     filter.addDataType("vnd.android.cursor.dir/event");
349                     mDpm.addPersistentPreferredActivity(mAdmin, filter, componentName);
350                     // Contacts
351                     filter = new IntentFilter();
352                     filter.addAction(Intent.ACTION_PICK);
353                     filter.addDataType(ContactsContract.Contacts.CONTENT_TYPE);
354                     mDpm.addPersistentPreferredActivity(mAdmin, filter, componentName);
355                     // Dialer
356                     filter = new IntentFilter();
357                     filter.addAction(Intent.ACTION_DIAL);
358                     filter.addAction(Intent.ACTION_CALL);
359                     mDpm.addPersistentPreferredActivity(mAdmin, filter, componentName);
360                     getPackageManager().setComponentEnabledSetting(componentName,
361                             PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
362                             PackageManager.DONT_KILL_APP);
363                 } break;
364                 case COMMAND_CLEAR_PERSISTENT_PREFERRED_ACTIVITIES: {
365                     mDpm.clearPackagePersistentPreferredActivities(mAdmin, getPackageName());
366                     getPackageManager().setComponentEnabledSetting(
367                             EnterprisePrivacyTestDefaultAppActivity.COMPONENT_NAME,
368                             PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
369                             PackageManager.DONT_KILL_APP);
370                 } break;
371                 case COMMAND_CREATE_MANAGED_PROFILE: {
372                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
373                         return;
374                     }
375                     if (mUm.getUserProfiles().size() > 1) {
376                         return;
377                     }
378                     startActivityForResult(new Intent(
379                             DevicePolicyManager.ACTION_PROVISION_MANAGED_PROFILE)
380                             .putExtra(DevicePolicyManager
381                                     .EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME,
382                                     CompDeviceAdminTestReceiver.getReceiverComponentName())
383                             .putExtra(DevicePolicyManager.EXTRA_PROVISIONING_SKIP_ENCRYPTION, true)
384                             .putExtra(DevicePolicyManager.EXTRA_PROVISIONING_SKIP_USER_CONSENT,
385                                 true), 0);
386                 } break;
387                 case COMMAND_REMOVE_MANAGED_PROFILE: {
388                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
389                         return;
390                     }
391                     removeManagedProfile();
392                 } break;
393                 case COMMAND_SET_ALWAYS_ON_VPN: {
394                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
395                         return;
396                     }
397                     mDpm.setAlwaysOnVpnPackage(mAdmin, getPackageName(),
398                             false /* lockdownEnabled */);
399                 } break;
400                 case COMMAND_CLEAR_ALWAYS_ON_VPN: {
401                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
402                         return;
403                     }
404                     mDpm.setAlwaysOnVpnPackage(mAdmin, null /* vpnPackage */,
405                             false /* lockdownEnabled */);
406                 } break;
407                 case COMMAND_SET_GLOBAL_HTTP_PROXY: {
408                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
409                         return;
410                     }
411                     mDpm.setRecommendedGlobalProxy(mAdmin,
412                             ProxyInfo.buildDirectProxy("example.com", 123));
413                 } break;
414                 case COMMAND_CLEAR_GLOBAL_HTTP_PROXY: {
415                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
416                         return;
417                     }
418                     mDpm.setRecommendedGlobalProxy(mAdmin, null);
419                 }
420                 case COMMAND_INSTALL_CA_CERT: {
421                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
422                         return;
423                     }
424                     mDpm.installCaCert(mAdmin, TEST_CA.getBytes());
425                 } break;
426                 case COMMAND_CLEAR_CA_CERT: {
427                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
428                         return;
429                     }
430                     mDpm.uninstallCaCert(mAdmin, TEST_CA.getBytes());
431                 } break;
432                 case COMMAND_SET_MAXIMUM_PASSWORD_ATTEMPTS: {
433                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
434                         return;
435                     }
436                     mDpm.setMaximumFailedPasswordsForWipe(mAdmin, 100);
437                 } break;
438                 case COMMAND_CLEAR_MAXIMUM_PASSWORD_ATTEMPTS: {
439                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
440                         return;
441                     }
442                     mDpm.setMaximumFailedPasswordsForWipe(mAdmin, 0);
443                 } break;
444                 case COMMAND_SET_DEFAULT_IME: {
445                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
446                         return;
447                     }
448                     mDpm.setSecureSetting(mAdmin, Settings.Secure.DEFAULT_INPUT_METHOD,
449                             getPackageName());
450                 } break;
451                 case COMMAND_CLEAR_DEFAULT_IME: {
452                     if (!mDpm.isDeviceOwnerApp(getPackageName())) {
453                         return;
454                     }
455                     mDpm.setSecureSetting(mAdmin, Settings.Secure.DEFAULT_INPUT_METHOD, null);
456                 }
457             }
458         } catch (Exception e) {
459             Log.e(TAG, "Failed to execute command: " + intent, e);
460         } finally {
461             finish();
462         }
463     }
464 
installHelperPackage()465     private void installHelperPackage() throws Exception {
466         final PackageInstaller packageInstaller = getPackageManager().getPackageInstaller();
467         final PackageInstaller.Session session = packageInstaller.openSession(
468                 packageInstaller.createSession(new PackageInstaller.SessionParams(
469                         PackageInstaller.SessionParams.MODE_FULL_INSTALL)));
470         final File file = new File(HELPER_APP_LOCATION);
471         final InputStream in = new FileInputStream(file);
472         final OutputStream out = session.openWrite("CommandReceiverActivity", 0, file.length());
473         final byte[] buffer = new byte[65536];
474         int count;
475         while ((count = in.read(buffer)) != -1) {
476             out.write(buffer, 0, count);
477         }
478         session.fsync(out);
479         in.close();
480         out.close();
481         session.commit(PendingIntent.getBroadcast(this, 0, new Intent(ACTION_INSTALL_COMPLETE), 0)
482                 .getIntentSender());
483     }
484 
uninstallHelperPackage()485     private void uninstallHelperPackage() {
486         try {
487             getPackageManager().getPackageInstaller().uninstall(HELPER_APP_PKG,
488                     PendingIntent.getBroadcast(this, 0, new Intent(ACTION_UNINSTALL_COMPLETE), 0)
489                             .getIntentSender());
490         } catch (IllegalArgumentException e) {
491             // The package is not installed: that's fine
492         }
493     }
494 
clearAllPoliciesAndRestrictions()495     private void clearAllPoliciesAndRestrictions() throws Exception {
496         clearProfileOwnerRelatedPolicies();
497         clearPolicyTransparencyUserRestriction(
498                 PolicyTransparencyTestListActivity.MODE_DEVICE_OWNER);
499 
500         // There are a few user restrictions that are used, but not for policy transparency
501         mDpm.clearUserRestriction(mAdmin, UserManager.DISALLOW_CONFIG_BLUETOOTH);
502         mDpm.clearUserRestriction(mAdmin, UserManager.DISALLOW_CONFIG_VPN);
503         mDpm.clearUserRestriction(mAdmin, UserManager.DISALLOW_DATA_ROAMING);
504 
505         mDpm.setDeviceOwnerLockScreenInfo(mAdmin, null);
506         mDpm.setKeyguardDisabled(mAdmin, false);
507         mDpm.setAutoTimeRequired(mAdmin, false);
508         mDpm.setStatusBarDisabled(mAdmin, false);
509         mDpm.setOrganizationName(mAdmin, null);
510         mDpm.setNetworkLoggingEnabled(mAdmin, false);
511         mDpm.setSecurityLoggingEnabled(mAdmin, false);
512         mDpm.setPermissionGrantState(mAdmin, getPackageName(),
513                 Manifest.permission.ACCESS_FINE_LOCATION,
514                 DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT);
515         mDpm.setPermissionGrantState(mAdmin, getPackageName(), Manifest.permission.RECORD_AUDIO,
516                 DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT);
517         mDpm.setPermissionGrantState(mAdmin, getPackageName(), Manifest.permission.CAMERA,
518                 DevicePolicyManager.PERMISSION_GRANT_STATE_DEFAULT);
519         mDpm.clearPackagePersistentPreferredActivities(mAdmin, getPackageName());
520         mDpm.setAlwaysOnVpnPackage(mAdmin, null, false);
521         mDpm.setRecommendedGlobalProxy(mAdmin, null);
522         mDpm.uninstallCaCert(mAdmin, TEST_CA.getBytes());
523         mDpm.setMaximumFailedPasswordsForWipe(mAdmin, 0);
524         mDpm.setSecureSetting(mAdmin, Settings.Secure.DEFAULT_INPUT_METHOD, null);
525 
526         uninstallHelperPackage();
527         removeManagedProfile();
528         getPackageManager().setComponentEnabledSetting(
529                 EnterprisePrivacyTestDefaultAppActivity.COMPONENT_NAME,
530                 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
531                 PackageManager.DONT_KILL_APP);
532     }
533 
clearProfileOwnerRelatedPoliciesAndRestrictions()534     private void clearProfileOwnerRelatedPoliciesAndRestrictions() {
535         clearPolicyTransparencyUserRestriction(
536                 PolicyTransparencyTestListActivity.MODE_PROFILE_OWNER);
537         clearProfileOwnerRelatedPolicies();
538     }
539 
clearProfileOwnerRelatedPolicies()540     private void clearProfileOwnerRelatedPolicies() {
541         mDpm.setKeyguardDisabledFeatures(mAdmin, 0);
542         mDpm.setPasswordQuality(mAdmin, 0);
543         mDpm.setMaximumTimeToLock(mAdmin, 0);
544         mDpm.setPermittedAccessibilityServices(mAdmin, null);
545         mDpm.setPermittedInputMethods(mAdmin, null);
546     }
547 
clearPolicyTransparencyUserRestriction(int mode)548     private void clearPolicyTransparencyUserRestriction(int mode) {
549         for (String userRestriction : UserRestrictions.getUserRestrictionsForPolicyTransparency(
550                 mode)) {
551             mDpm.clearUserRestriction(mAdmin, userRestriction);
552         }
553     }
554 
removeManagedProfile()555     private void removeManagedProfile() {
556         for (final UserHandle userHandle : mUm.getUserProfiles()) {
557             mDpm.removeUser(mAdmin, userHandle);
558         }
559     }
560 }
561