Repository navigation
Expand file tree
/
Copy pathShellCommand.java
More file actions
1716 lines (1532 loc) · 70.1 KB
/
Copy pathShellCommand.java
File metadata and controls
1716 lines (1532 loc) · 70.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.afwsamples.testdpc;
import static com.afwsamples.testdpc.util.flags.Flags.command;
import static com.afwsamples.testdpc.util.flags.Flags.namedParam;
import static com.afwsamples.testdpc.util.flags.Flags.optional;
import static com.afwsamples.testdpc.util.flags.Flags.ordinalParam;
import static com.afwsamples.testdpc.util.flags.Flags.repeated;
import android.annotation.TargetApi;
import android.app.admin.ConnectEvent;
import android.app.admin.DevicePolicyManager;
import android.app.admin.DnsEvent;
import android.app.admin.NetworkEvent;
import android.app.admin.SecurityLog.SecurityEvent;
import android.content.ComponentName;
import android.content.Context;
import android.content.IntentFilter;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Process;
import android.os.UserHandle;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.afwsamples.testdpc.common.Util;
import com.afwsamples.testdpc.policy.SecurityLogsFragment;
import com.afwsamples.testdpc.policy.resetpassword.ResetPasswordWithTokenFragment;
import com.afwsamples.testdpc.util.flags.Flags;
import java.io.File;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
* Provides a CLI (command-line interface) to TestDPC through {@code dumpsys}.
*
* <p>Usage: {@code adb shell dumpsys activity --user USER_ID service com.afwsamples.testdpc CMD}.
*/
final class ShellCommand {
private static final String TAG = "TestDPCShellCommand";
private final Context mContext;
private final PrintWriter mWriter;
private final String[] mArgs;
private final DevicePolicyManagerGateway mDevicePolicyManagerGateway;
@Nullable // dynamically created on post() method
private Handler mHandler;
public ShellCommand(
@NonNull Context context, @NonNull PrintWriter writer, @Nullable String[] args) {
mContext = context;
mWriter = writer;
mArgs = args;
mDevicePolicyManagerGateway = new DevicePolicyManagerGatewayImpl(context);
Log.d(
TAG,
"constructor: pid="
+ Process.myPid()
+ ", process name="
+ Util.myProcessName()
+ ", args="
+ Arrays.toString(args));
}
private static String suspendedToString(boolean suspended) {
return suspended ? "SUSPENDED" : "NOT SUSPENDED";
}
private static String hiddenToString(boolean hidden) {
return hidden ? "HIDDEN" : "VISIBLE";
}
private static String permittedToString(boolean permitted) {
return permitted ? "PERMITTED" : "NOT PERMITTED";
}
public void run() {
Flags flags = new Flags(mWriter);
flags.registerCustomParser(
UserHandle.class,
(string, validator) -> {
long serialNumber;
try {
serialNumber = Long.parseLong(string);
} catch (NumberFormatException e) {
return validator.invalid("UserHandle must be a long integer.");
}
UserHandle userHandle = mDevicePolicyManagerGateway.getUserHandle(serialNumber);
if (userHandle == null) {
return validator.invalid(
String.format(Locale.getDefault(), "User %d does not exist.", serialNumber));
}
return validator.valid(userHandle);
});
flags.registerCustomParser(
File.class,
(string, validator) -> {
File file = UserIconContentProvider.getFile(mContext, string);
if (!file.isFile()) {
return validator.invalid(
String.format(Locale.getDefault(), "Could not open file %s.", string));
}
return validator.valid(file);
});
flags.registerCustomParser(
KeyValue.class,
(string, validator) -> {
if (string.contains("=")) {
String[] parts = string.split("=", 2);
return validator.valid(
new KeyValue(parts.length > 0 ? parts[0] : "", parts.length > 1 ? parts[1] : ""));
}
return validator.invalid(
String.format(
"Key-value type must contain '=' separator, found only: '%s'.", string));
});
flags.addCommand(command("dump", this::dumpState).setDescription("Dump internal state."));
flags.addCommand(
command(
"create-user",
this::createUser,
ordinalParam(String.class, "name"),
optional(namedParam(int.class, "flags")))
.setDescription("Create a user with the optional flags and name."));
flags.addCommand(
command("set-user-icon", this::setUserIcon, ordinalParam(File.class, "file"))
.setDescription(
"Set the user icon using the bitmap located at the given file, which must be"
+ " located in the user's `UserIcons` directory. For user 0, you can use `adb"
+ " push` to push a local file to that directory"
+ " (/storage/emulated/0/Android/data/com.afwsamples.testdpc/files/Pictures/UserIcons),"
+ " but for other users you need to switch to that user and use its content"
+ " provider (for example, `adb shell content write --user 10 --uri"
+ " content://com.afwsamples.testdpc.usericoncontentprovider/icon.png <"
+ " /tmp/icon.png`)."));
flags.addCommand(
command(
"set-start-user-session-message",
this::setStartUserSessionMessage,
ordinalParam(String.class, "message"))
.setDescription("Set the message shown when a user is switched to"));
flags.addCommand(
command("get-start-user-session-message", this::getStartUserSessionMessage)
.setDescription("Get the message shown when a user is switched to"));
flags.addCommand(
command(
"set-end-user-session-message",
this::setEndUserSessionMessage,
ordinalParam(String.class, "message"))
.setDescription("Set the message shown when a user is switched of"));
flags.addCommand(
command("get-end-user-session-message", this::getEndUserSessionMessage)
.setDescription("Get the message shown when a user is switched of"));
flags.addCommand(
command(
"remove-user",
this::removeUser,
ordinalParam(UserHandle.class, "user-serial-number"))
.setDescription("Remove the given user."));
flags.addCommand(
command(
"switch-user",
this::switchUser,
ordinalParam(UserHandle.class, "user-serial-number"))
.setDescription("Switch the given user to foreground."));
flags.addCommand(
command(
"start-user-in-background",
this::startUserInBackground,
ordinalParam(UserHandle.class, "user-serial-number"))
.setDescription("Switch the given user to foreground."));
flags.addCommand(
command(
"is-logout-enabled",
this::isLogoutEnabled)
.setDescription("Whether logout is enabled."));
flags.addCommand(
command(
"set-logout-enabled",
this::setLogoutEnabled,
ordinalParam(boolean.class, "enabled"))
.setDescription("Set whether logout is enabled."));
flags.addCommand(
command(
"logout-user",
this::logoutUser)
.setDescription("Logout the current user."));
flags.addCommand(
command("is-user-affiliated", this::isUserAffiliated)
.setDescription("Check if the user is affiliated with the device."));
flags.addCommand(
command(
"set-affiliation-ids",
this::setAffiliationIds,
repeated(ordinalParam(String.class, "ids")))
.setDescription("Set the user affiliation ids (or clear them if no ids are passed)."));
flags.addCommand(
command("get-affiliation-ids", this::getAffiliationIds)
.setDescription("Get the user affiliation ids."));
flags.addCommand(
command("list-user-restrictions", this::listUserRestrictions)
.setDescription("List the user restrictions."));
flags.addCommand(
command(
"set-user-restriction",
this::setUserRestriction,
ordinalParam(String.class, "restriction"),
ordinalParam(boolean.class, "enabled"))
.setDescription("Set the given user restriction."));
flags.addCommand(
command(
"set-user-restriction-on-parent",
this::setUserRestrictionOnParent,
ordinalParam(String.class, "restriction"),
ordinalParam(boolean.class, "enabled"))
.setDescription("Set the given user restriction on the parent user."));
flags.addCommand(
command("lock-now", this::lockNow, optional(namedParam(int.class, "flags")))
.setDescription("Lock the device (now! :-)."));
flags.addCommand(command("reboot", this::reboot).setDescription("Reboot the device."));
flags.addCommand(
command("wipe-data", this::wipeData, optional(namedParam(int.class, "flags")))
.setDescription("Factory reset the device."));
flags.addCommand(
command("request-bugreport", this::requestBugreport)
.setDescription("Request a bug report."));
flags.addCommand(
command("get-last-bugreport-request-time", this::getLastBugReportRequestTime)
.setDescription("Prints the last time the device owner request a bugreport."));
flags.addCommand(
command(
"set-network-logging-enabled",
this::setNetworkLoggingEnabled,
ordinalParam(boolean.class, "enabled"))
.setDescription("Enable / disable network logging."));
flags.addCommand(
command("is-network-logging-enabled", this::isNetworkLoggingEnabled)
.setDescription("Checks whether network logging is enabled."));
flags.addCommand(
command("get-last-network-log-retrieval-time", this::getLastNetworkLogRetrievalTime)
.setDescription("Prints the last time the device owner retrieved the network log."));
flags.addCommand(
command("retrieve-network-logs", this::retrieveNetworkLogs,
ordinalParam(Long.class, "batch-token"))
.setDescription("Retrieves the network logs."));
flags.addCommand(
command(
"set-security-logging-enabled",
this::setSecurityLoggingEnabled,
ordinalParam(boolean.class, "enabled"))
.setDescription("Enable / disable security logging."));
flags.addCommand(
command("is-security-logging-enabled", this::isSecurityLoggingEnabled)
.setDescription("Checks whether security logging is enabled."));
flags.addCommand(
command("get-last-security-log-retrieval-time", this::getLastSecurityLogRetrievalTime)
.setDescription("Prints the last time the device owner retrieved the security log."));
flags.addCommand(
command("retrieve-security-logs", this::retrieveSecurityLogs)
.setDescription("Retrieves the security logs."));
flags.addCommand(
command("retrieve-pre-reboot-security-logs", this::retrievePreRebootSecurityLogs)
.setDescription("Retrieves the pre-reboot security logs."));
flags.addCommand(
command("clear-organization-name", this::clearOrganizationName)
.setDescription("Clear the organisation name."));
flags.addCommand(
command(
"set-organization-name",
this::setOrganizationName,
ordinalParam(String.class, "name"))
.setDescription("Set the organisation name."));
flags.addCommand(
command("get-organization-name", this::getOrganizationName)
.setDescription("Get the organization name."));
flags.addCommand(
command(
"set-user-control-disabled-packages",
this::setUserControlDisabledPackages,
repeated(ordinalParam(String.class, "packages")))
.setDescription(
"Set the packages that the user cannot force stop or clear data for. Provide an"
+ " empty list to reset."));
flags.addCommand(
command("get-user-control-disabled-packages", this::getUserControlDisabledPackages)
.setDescription("Get the packages that the user cannot force stop or clear data for."));
flags.addCommand(
command(
"set-cross-profile-packages",
this::setCrossProfilePackages,
repeated(ordinalParam(String.class, "packages")))
.setDescription(
"Set the allow-listed packages that are allowed to request user consent for"
+ " cross-profile communication. Provide an empty list to reset."));
flags.addCommand(
command("get-cross-profile-packages", this::getCrossProfilePackages)
.setDescription(
"Get the allow-listed packages that are allowed to request user consent"
+ " for cross-profile communication."));
flags.addCommand(
command("remove-active-admin", this::removeActiveAdmin)
.setDescription("Remove TestDPC as an active admin."));
flags.addCommand(
command("clear-device-owner", this::clearDeviceOwner)
.setDescription("Clear TestDPC as device owner."));
flags.addCommand(
command("clear-profile-owner", this::clearProfileOwner)
.setDescription("Clear TestDPC as profile owner."));
flags.addCommand(
command(
"set-password-quality",
this::setPasswordQuality,
ordinalParam(int.class, "quality"))
.setDescription("Set the password quality."));
flags.addCommand(
command("get-password-quality", this::getPasswordQuality)
.setDescription("Get the password quality."));
flags.addCommand(
command("is-active-password-sufficient", this::isActivePasswordSufficient)
.setDescription("Checks if user's password is sufficient."));
flags.addCommand(
command(
"is-active-password-sufficient-for-device-requirement",
this::isActivePasswordSufficientForDeviceRequirement)
.setDescription("Checks if user's password is sufficient for device requirement."));
flags.addCommand(
command(
"set-required-password-complexity",
this::setRequiredPasswordComplexity,
ordinalParam(int.class, "complexity"))
.setDescription("Set the required password complexity."));
flags.addCommand(
command("get-required-password-complexity", this::getRequiredPasswordComplexity)
.setDescription("Get required the password complexity."));
flags.addCommand(
command("transfer-ownership", this::transferOwnership, ordinalParam(String.class, "admin"))
.setDescription("Transfer ownership to the given admin."));
flags.addCommand(
command(
"set-suspended-packages",
this::setSuspendedPackages,
ordinalParam(boolean.class, "suspended"),
repeated(ordinalParam(String.class, "packageNames")))
.setDescription("Suspend / unsuspend the given packages."));
flags.addCommand(
command(
"is-suspended-packages",
this::isSuspendedPackage,
repeated(ordinalParam(String.class, "packageNames")))
.setDescription("Check if the given packages are suspended."));
flags.addCommand(
command(
"set-personal-apps-suspended",
this::setPersonalAppsSuspended,
ordinalParam(boolean.class, "suspended"))
.setDescription("Suspend / unsuspend personal apps."));
flags.addCommand(
command(
"enable-system-app",
this::enableSystemApp,
ordinalParam(String.class, "packageName"))
.setDescription("Enable the given system app."));
flags.addCommand(
command("list-disabled-system-apps", this::listDisabledSystemApps)
.setDescription("List the disabled system apps."));
flags.addCommand(
command("get-personal-apps-suspended-reasons", this::getPersonalAppsSuspendedReasons)
.setDescription("Get the reasons for suspending personal apps."));
flags.addCommand(
command(
"set-hidden-package",
this::setHiddenPackage,
ordinalParam(String.class, "package"),
ordinalParam(boolean.class, "hidden"))
.setDescription("Hide / unhide the given package."));
flags.addCommand(
command("is-hidden-package", this::isHiddenPackage, ordinalParam(String.class, "package"))
.setDescription("Check if the given package is hidden."));
flags.addCommand(
command(
"set-lock-task-packages",
this::setLockTaskPackages,
repeated(ordinalParam(String.class, "packages")))
.setDescription("Set the packages allowed to have tasks locked."));
flags.addCommand(
command("get-lock-task-packages", this::getLockTaskPackages)
.setDescription("Get the packages allowed to have tasks locked."));
flags.addCommand(
command(
"is-lock-task-permitted",
this::isLockTaskPermitted,
repeated(ordinalParam(String.class, "packages")))
.setDescription("Check if the given packages are allowed to have tasks locked."));
flags.addCommand(
command(
"set-lock-task-features",
this::setLockTaskFeatures,
ordinalParam(int.class, "flags"))
.setDescription("Set the lock task features."));
flags.addCommand(
command("get-lock-task-features", this::getLockTaskFeatures)
.setDescription("Get the lock task features."));
flags.addCommand(
command(
"set-app-restrictions",
this::setAppRestrictions,
ordinalParam(String.class, "package"),
repeated(ordinalParam(KeyValue.class, "restrictions")))
.setDescription(
"Set the application restrictions (provided as key=value strings) for the given app"
+ " (or clear if no values provided)."));
flags.addCommand(
command(
"get-app-restrictions",
this::getAppRestrictions,
repeated(ordinalParam(String.class, "packages")))
.setDescription(
"Get the application restrictions for the given apps (or for TestDPC when empty,"
+ " using UserManager)."));
flags.addCommand(
command(
"set-permission-grant-state",
this::setPermissionGrantState,
ordinalParam(String.class, "package"),
ordinalParam(String.class, "permission"),
ordinalParam(int.class, "state"))
.setDescription("Set the grant state for the given package and permission."));
flags.addCommand(
command(
"get-permission-grant-state",
this::getPermissionGrantState,
ordinalParam(String.class, "package"),
ordinalParam(String.class, "permission"))
.setDescription("Get the grant state for the given package and persmission."));
flags.addCommand(
command("can-admin-grant-sensors-permissions", this::canAdminGrantSensorsPermissions)
.setDescription("Checks whether the admin can grant sensor permissions."));
flags.addCommand(
command(
"set-location-enabled",
this::setLocationEnabled,
ordinalParam(boolean.class, "enabled"))
.setDescription("Set location enabled for the user."));
flags.addCommand(
command("is-location-enabled", this::isLocationEnabled)
.setDescription("Get whether location is enabled for the user."));
flags.addCommand(
command("clear-device-owner-lockscreen-info", this::clearDeviceOwnerLockScreenInfo)
.setDescription("Clear the device owner lock screen info."));
flags.addCommand(
command(
"set-device-owner-lockscreen-info",
this::setDeviceOwnerLockScreenInfo,
ordinalParam(String.class, "info"))
.setDescription("Set the device owner lock screen info."));
flags.addCommand(
command("get-device-owner-lockscreen-info", this::getDeviceOwnerLockScreenInfo)
.setDescription("Get the device owner lock screen info."));
flags.addCommand(
command(
"set-keyguard-disabled",
this::setKeyguardDisabled,
ordinalParam(boolean.class, "disabled"))
.setDescription("Set keyguard disabled."));
flags.addCommand(
command(
"set-keyguard-disabled-features",
this::setKeyguardDisabledFeatures,
ordinalParam(int.class, "flags"))
.setDescription("Set the keyguard disabled features."));
flags.addCommand(
command("get-keyguard-disabled-features", this::getKeyguardDisabledFeatures)
.setDescription("Get the keyguard disabled features."));
flags.addCommand(
command(
"set-camera-disabled",
this::setCameraDisabled,
ordinalParam(boolean.class, "disabled"))
.setDescription("Set camera disabled."));
flags.addCommand(
command("get-camera-disabled", this::getCameraDisabled)
.setDescription("Get camera disabled."));
flags.addCommand(
command(
"set-status-bar-disabled",
this::setStatusBarDisabled,
ordinalParam(boolean.class, "disabled"))
.setDescription("Set status bar disabled."));
flags.addCommand(
command(
"set-max-failed-passwords",
this::setMaximumFailedPasswordsForWipe,
ordinalParam(int.class, "max"))
.setDescription("Set maximum number of failed passwords before user is wiped."));
flags.addCommand(
command("get-max-failed-passwords", this::getMaximumFailedPasswordsForWipe)
.setDescription("Get maximum number of failed passwords before user is wiped."));
flags.addCommand(
command("install-existing-package", this::installExistingPackage,
ordinalParam(String.class, "package"))
.setDescription("Installs the existing package for this user."));
flags.addCommand(
command("set-uninstall-blocked", this::setUninstallBlocked,
ordinalParam(String.class, "package"),
ordinalParam(boolean.class, "blocked"))
.setDescription("Sets whether the given package can be uninstalled."));
flags.addCommand(
command("is-uninstall-blocked", this::isUninstallBlocked,
ordinalParam(String.class, "package"))
.setDescription("Checks whether the given package can be uninstalled."));
flags.addCommand(
command("set-secure-setting", this::setSecureSetting,
ordinalParam(String.class, "setting"),
ordinalParam(String.class, "value"))
.setDescription("Sets the given Settings.SECURE setting for this user."));
flags.addCommand(
command("set-global-setting", this::setGlobalSetting,
ordinalParam(String.class, "setting"),
ordinalParam(String.class, "value"))
.setDescription("Sets the given Settings.GLOBAL setting for this user."));
flags.addCommand(
command("has-key-pair", this::hasKeyPair,
ordinalParam(String.class, "alias"))
.setDescription("Checks if a certificate key with the given alias is installed."));
flags.addCommand(
command("generate-device-attestation-key-pair", this::generateDeviceAttestationKeyPair,
ordinalParam(String.class, "alias"),
optional(namedParam(int.class, "flags")))
.setDescription("Generates a device attestation key."));
flags.addCommand(
command("remove-key-pair", this::removeKeyPair,
ordinalParam(String.class, "alias"))
.setDescription("Removes the certificate key with the given alias."));
flags.addCommand(
command("grant-key-pair-to-app", this::grantKeyPairToApp,
ordinalParam(String.class, "alias"),
ordinalParam(String.class, "packageName"))
.setDescription("Grants a certificate key to an app."));
flags.addCommand(
command("get-key-pair-grants", this::getKeyPairGrants,
ordinalParam(String.class, "alias"))
.setDescription("Lists the apps that were granted the given certificate key."));
flags.addCommand(
command("revoke-key-pair-from-app", this::revokeKeyPairFromApp,
ordinalParam(String.class, "alias"),
ordinalParam(String.class, "packageName"))
.setDescription("Revokes a certificate key from an app."));
flags.addCommand(
command("set-delegated-scopes", this::setDelegatedScopes,
ordinalParam(String.class, "packageName"),
repeated(ordinalParam(String.class, "scopes")))
.setDescription("Delegates the given scopes to an app."));
flags.addCommand(
command("get-delegated-scopes", this::getDelegatedScopes,
ordinalParam(String.class, "packageName"))
.setDescription("Gets the scopes delgated to an app."));
flags.addCommand(
command("get-delegate-packages", this::getDelegatePackages,
ordinalParam(String.class, "scope"))
.setDescription("Gets the apps that were delegate a given scope."));
flags.addCommand(
command("set-password", this::setPassword, ordinalParam(String.class, "newPassword"))
.setDescription("Resets password to a given one. Requires an active token"));
flags.addCommand(
command("clear-password", this::clearPassword)
.setDescription("Resets password to an empty one. Requires an active token"));
flags.addCommand(
command(
"set-screencapture-disabled",
this::setScreenCaptureDisabled,
ordinalParam(boolean.class, "disabled"))
.setDescription("Set whether screen capture is disabled."));
flags.addCommand(
command("add-persistent-preferred-activity",
this::addPersistentPreferredActivity,
ordinalParam(String.class, "activityName"),
ordinalParam(String.class, "action"),
repeated(ordinalParam(String.class, "categories")))
.setDescription("Adds a preferred activity for the given intent filter."));
flags.addCommand(
command("clear-package-persistent-preferred-activities",
this::clearPackagePersistentPreferredActivities,
ordinalParam(String.class, "packageName"))
.setDescription("Clears preferred activities assigned to an app."));
// Separator for S / pre-S commands - do NOT remove line to avoid cherry-pick conflicts
if (Util.isAtLeastS()) {
flags.addCommand(
command(
"set-usb-data-signaling-enabled",
this::setUsbDataSignalingEnabled,
ordinalParam(boolean.class, "enabled"))
.setDescription("Enable / disable USB data signaling."));
flags.addCommand(
command(
"can-usb-data-signaling-be-disabled",
this::canUsbDataSignalingBeDisabled)
.setDescription("Check if USB data signaling can be disabled."));
flags.addCommand(
command(
"set-permitted-input-methods-parent",
this::setPermittedInputMethodsOnParent,
repeated(ordinalParam(String.class, "methods")))
.setDescription("Set the permitted input methods in the parent's device admin."));
flags.addCommand(
command("list-foreground-users", this::listForegroundUsers)
.setDescription("List the users running in the foreground."));
flags.addCommand(
command("is-foreground-user", this::isForegroundUser)
.setDescription("Checks if the calling user is running in the foreground."));
flags.addCommand(
command(
"set-metered-data-disabled-packages",
this::setMeteredDataDisabledPackages,
repeated(ordinalParam(String.class, "disabled-packages")))
.setDescription("Restricts packages from using metered data."));
flags.addCommand(
command("get-metered-data-disabled-packages", this::getMeteredDataDisabledPackages)
.setDescription("List the packages restricted from using metered data."));
flags.addCommand(
command("get-secondary-users", this::getSecondaryUsers)
.setDescription("List all UserHandles of secondary users on the device."));
}
try {
flags.run(mArgs);
} catch (Exception e) {
// Must explicitly catch and show generic exceptions (like NumberFormatException parsing
// args), otherwise they'dbe logcat'ed on AndroidRuntime and not surfaced to caller
onError(e, "error executing %s", Arrays.toString(mArgs));
}
}
private void dumpState() {
mWriter.printf("isDeviceOwner: %b\n", mDevicePolicyManagerGateway.isDeviceOwnerApp());
mWriter.printf("isProfileOwner: %b\n", mDevicePolicyManagerGateway.isProfileOwnerApp());
mWriter.printf(
"isOrganizationOwnedDeviceWithManagedProfile: %b\n",
mDevicePolicyManagerGateway.isOrganizationOwnedDeviceWithManagedProfile());
if (Util.isAtLeastS()) {
mWriter.printf(
"isHeadlessSystemUserMode: %b\n", mDevicePolicyManagerGateway.isHeadlessSystemUserMode());
mWriter.printf("isUserForeground: %b\n", mDevicePolicyManagerGateway.isUserForeground());
}
mWriter.printf("isDeviceIdAttestationSupported: %b\n",
mDevicePolicyManagerGateway.isDeviceIdAttestationSupported());
mWriter.printf("isUniqueDeviceAttestationSupported: %b\n",
mDevicePolicyManagerGateway.isUniqueDeviceAttestationSupported());
}
private void createUser(String name, int flags) {
Log.i(TAG, "createUser(): name=" + name + ", flags=" + flags);
mDevicePolicyManagerGateway.createAndManageUser(
name,
flags,
(u) -> onSuccess("User created: %s", toString(u)),
(e) -> onError(e, "Error creating user %s", name));
}
private void setUserIcon(File file) {
String absolutePath = file.getAbsolutePath();
Log.i(TAG, "setUserIcon(): path=" + absolutePath);
Bitmap icon = BitmapFactory.decodeFile(absolutePath, /* bmOptions= */ null);
if (icon == null) {
mWriter.printf("Could not create bitmap from file %s\n", absolutePath);
return;
}
mDevicePolicyManagerGateway.setUserIcon(
icon,
(v) -> onSuccess("User icon created from file %s", absolutePath),
(e) -> onError(e, "Error creating user icon from file %s", absolutePath));
}
private void setStartUserSessionMessage(String message) {
Log.i(TAG, "setStartUserSessionMessage(): " + message);
mDevicePolicyManagerGateway.setStartUserSessionMessage(
message,
(v) -> onSuccess("Set start user session message to '%s'", message),
(e) -> onError(e, "Error setting start user session message to '%s'", message));
}
private void getStartUserSessionMessage() {
CharSequence message = mDevicePolicyManagerGateway.getStartUserSessionMessage();
mWriter.printf("%s\n", message);
}
private void setEndUserSessionMessage(String message) {
Log.i(TAG, "setEndUserSessionMessage(): " + message);
mDevicePolicyManagerGateway.setEndUserSessionMessage(
message,
(v) -> onSuccess("Set end user session message to '%s'", message),
(e) -> onError(e, "Error setting end user session message to '%s'", message));
}
private void getEndUserSessionMessage() {
CharSequence message = mDevicePolicyManagerGateway.getEndUserSessionMessage();
mWriter.printf("%s\n", message);
}
private void removeUser(UserHandle userHandle) {
mDevicePolicyManagerGateway.removeUser(
userHandle,
(v) -> onSuccess("User %s removed", userHandle),
(e) -> onError(e, "Error removing user %s", userHandle));
}
private void switchUser(UserHandle userHandle) {
mDevicePolicyManagerGateway.switchUser(
userHandle,
(v) -> onSuccess("User %s switched", userHandle),
(e) -> onError(e, "Error switching user %s", userHandle));
}
private void startUserInBackground(UserHandle userHandle) {
mDevicePolicyManagerGateway.startUserInBackground(
userHandle,
(v) -> onSuccess("User %s started in background", userHandle),
(e) -> onError(e, "Error starting user %s in background", userHandle));
}
private void stopUser(UserHandle userHandle) {
mDevicePolicyManagerGateway.stopUser(
userHandle,
(v) -> onSuccess("User %s stopped", userHandle),
(e) -> onError(e, "Error stopping user %s", userHandle));
}
private void isLogoutEnabled() {
mWriter.println(mDevicePolicyManagerGateway.isLogoutEnabled());
}
private void setLogoutEnabled(boolean enabled) {
mDevicePolicyManagerGateway.setLogoutEnabled(enabled,
(v) -> onSuccess("Logout enabled set to %b", enabled),
(e) -> onError(e, "Error setting logout enabled to %b", enabled));
}
private void logoutUser() {
UserHandle userHandle = Process.myUserHandle();
mDevicePolicyManagerGateway.logoutUser(
(v) -> onSuccess("User %s logged out", userHandle),
(e) -> onError(e, "Error logging out user %s", userHandle));
}
private void getAffiliationIds() {
Set<String> ids = mDevicePolicyManagerGateway.getAffiliationIds();
if (ids.isEmpty()) {
mWriter.println("no affiliation ids");
return;
}
mWriter.printf("%d affiliation ids: %s\n", ids.size(), ids);
}
private void setAffiliationIds(String[] ids) {
Set<String> idSet = getOrderedSortedSet(ids);
Log.i(TAG, "setAffiliationIds(): ids=" + idSet);
mDevicePolicyManagerGateway.setAffiliationIds(idSet);
getAffiliationIds();
}
private void isUserAffiliated() {
mWriter.println(mDevicePolicyManagerGateway.isAffiliatedUser());
}
private void listUserRestrictions() {
Log.i(TAG, "listUserRestrictions()");
printCollection("user restriction", mDevicePolicyManagerGateway.getUserRestrictions());
}
private void setUserRestriction(String userRestriction, boolean enabled) {
Log.i(TAG, "setUserRestriction(" + userRestriction + ", " + enabled + ")");
mDevicePolicyManagerGateway.setUserRestriction(
userRestriction,
enabled,
(v) -> onSuccess("User restriction '%s' set to %b", userRestriction, enabled),
(e) -> onError(e, "Error setting user restriction '%s' to %b", userRestriction, enabled));
}
private void setUserRestrictionOnParent(String userRestriction, boolean enabled) {
Log.i(TAG, "setUserRestrictionOnParent(" + userRestriction + ", " + enabled + ")");
DevicePolicyManagerGateway parentDpmGateway =
DevicePolicyManagerGatewayImpl.forParentProfile(mContext);
parentDpmGateway.setUserRestriction(
userRestriction,
enabled,
(v) -> onSuccess("User restriction '%s' set to %b", userRestriction, enabled),
(e) ->
onError(
e, "Error setting parent user restriction '%s' to %b", userRestriction, enabled));
}
private void lockNow(Integer flags) {
if (flags == null) {
Log.i(TAG, "lockNow()");
mDevicePolicyManagerGateway.lockNow(
(v) -> onSuccess("Device locked"), (e) -> onError(e, "Error locking device"));
} else {
Log.i(TAG, "lockNow(" + flags + ")");
mDevicePolicyManagerGateway.lockNow(
flags, (v) -> onSuccess("Device locked"), (e) -> onError(e, "Error locking device"));
}
}
private void reboot() {
Log.i(TAG, "reboot()");
mDevicePolicyManagerGateway.reboot(
(v) -> onSuccess("Device rebooted"), (e) -> onError(e, "Error rebooting device"));
}
private void wipeData(int flags) {
Log.i(TAG, "wipeData()");
mDevicePolicyManagerGateway.wipeData(
flags, (v) -> onSuccess("Data wiped"), (e) -> onError(e, "Error wiping data"));
}
private void requestBugreport() {
Log.i(TAG, "requestBugreport()");
mDevicePolicyManagerGateway.requestBugreport(
(v) -> onSuccess("Bugreport requested"), (e) -> onError(e, "Error requesting bugreport"));
}
private void getLastBugReportRequestTime() {
printTime(mDevicePolicyManagerGateway.getLastBugReportRequestTime());
}
private void setNetworkLoggingEnabled(boolean enabled) {
Log.i(TAG, "setNetworkLoggingEnabled(" + enabled + ")");
mDevicePolicyManagerGateway.setNetworkLoggingEnabled(
enabled,
(v) -> onSuccess("Network logging enabled set to %b", enabled),
(e) -> onError(e, "Error setting network logging enabled to %b", enabled));
}
private void isNetworkLoggingEnabled() {
mWriter.println(mDevicePolicyManagerGateway.isNetworkLoggingEnabled());
}
private void getLastNetworkLogRetrievalTime() {
printTime(mDevicePolicyManagerGateway.getLastNetworkLogRetrievalTime());
}
private void retrieveNetworkLogs(long batchToken) {
List<NetworkEvent> events = mDevicePolicyManagerGateway.retrieveNetworkLogs(batchToken);
if (events == null || events.isEmpty()) {
mWriter.println("N/A");
return;
}
mWriter.printf("%d events:\n", events.size());
for (int i = 0; i < events.size(); i++) {
NetworkEvent event = events.get(i);
if (event instanceof DnsEvent) {
DnsEvent de = (DnsEvent) event;
String addresses = de.getInetAddresses().stream()
.map(InetAddress::toString).collect(Collectors.joining(","));
mWriter.printf("\t%d:DnsEvent id=%d pkg=%s hostname=%s addresses=%s\n",
i, event.getId(), event.getPackageName(), de.getHostname(), addresses);
} else if (event instanceof ConnectEvent) {
ConnectEvent ce = (ConnectEvent) event;
mWriter.printf("\t%d:ConnectEvent id=%d pkg=%s address=%s port=%d\n",
i, ce.getId(), ce.getPackageName(), ce.getInetAddress(), ce.getPort());
} else {
mWriter.printf("\t%d:Unknown id=%d pkg=%s\n", i, event.getId(), event.getPackageName());
}
}
}
private void setSecurityLoggingEnabled(boolean enabled) {
Log.i(TAG, "setSecurityLoggingEnabled(" + enabled + ")");
mDevicePolicyManagerGateway.setSecurityLoggingEnabled(
enabled,
(v) -> onSuccess("Security logging enabled set to %b", enabled),
(e) -> onError(e, "Error setting security logging enabled to %b", enabled));
}
private void isSecurityLoggingEnabled() {
mWriter.println(mDevicePolicyManagerGateway.isSecurityLoggingEnabled());
}
private void getLastSecurityLogRetrievalTime() {
printTime(mDevicePolicyManagerGateway.getLastSecurityLogRetrievalTime());
}
private void retrieveSecurityLogs() {
printSecurityLogs(mDevicePolicyManagerGateway.retrieveSecurityLogs());
}
private void retrievePreRebootSecurityLogs() {
printSecurityLogs(mDevicePolicyManagerGateway.retrievePreRebootSecurityLogs());
}
private void clearOrganizationName() {
setOrganizationName("");
}
private void setOrganizationName(String name) {
Log.i(TAG, "setOrganizationName(" + name + ")");
mDevicePolicyManagerGateway.setOrganizationName(
name,
(v) -> onSuccess("Organization name set to %s", name),
(e) -> onError(e, "Error setting Organization name to %s", name));
}
private void getOrganizationName() {
CharSequence title = mDevicePolicyManagerGateway.getOrganizationName();
if (title == null) {
mWriter.println("Not set");
return;
}
mWriter.println(title);
}
private void setUserControlDisabledPackages(String[] packages) {
List<String> packagesList = Arrays.asList(packages);
Log.i(TAG, "setUserControlDisabledPackages(" + packagesList + ")");
mDevicePolicyManagerGateway.setUserControlDisabledPackages(
packagesList,
(v) -> onSuccess("User-control disabled packages set to %s", packagesList),
(e) -> onError(e, "Error setting User-control disabled packages to %s", packagesList));
}
private void getUserControlDisabledPackages() {
List<String> pkgs = mDevicePolicyManagerGateway.getUserControlDisabledPackages();
pkgs.forEach(mWriter::println);
}
private void setCrossProfilePackages(String[] packages) {
Set<String> packagesList = getOrderedSortedSet(packages);
Log.i(TAG, "setCrossProfilePackages(" + packagesList + ")");
mDevicePolicyManagerGateway.setCrossProfilePackages(
packagesList,
(v) ->
onSuccess(
"Allow-listed packages for cross-profile communication set to %s", packagesList),
(e) ->
onError(
e,
"Error setting allow-listed packages for cross-profile communication to" + " %s",
packagesList));
}
private void getCrossProfilePackages() {
Set<String> pkgs = mDevicePolicyManagerGateway.getCrossProfilePackages();
pkgs.forEach(mWriter::println);
}
private void removeActiveAdmin() {
Log.i(TAG, "removeActiveAdmin()");
ComponentName admin = mDevicePolicyManagerGateway.getAdmin();
mDevicePolicyManagerGateway.removeActiveAdmin(
(v) -> onSuccess("Removed %s as an active admin", admin),
(e) -> onError(e, "Error removing %s as admin", admin));
}