-
Notifications
You must be signed in to change notification settings - Fork 3
/
aldroid
executable file
·983 lines (826 loc) · 33.4 KB
/
aldroid
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
#!/bin/sh
#
# aldroid.sh
#
# Created by Max Buck on 1/1/21.
# Copyright © 2021 AppLovin Corporation. All rights reserved.
#
# This script is used to make APKs debuggable locally or pull an app, make it debuggable and push it pack to the device or pull/push files to an Android device
#
# Example Usage: ./aldroid.sh d com.applovin.enterprise.apps.demoapp
#
VERSION=0.4.2
usage() {
cat <<EOF
usage: aldroid
-h Prints this information.
-v Prints version information.
usage: aldroid d[ebuggable] [options] <package_name>
Pulls the app, makes it debuggable and charlesable and reinstalls it. Will also handle obbs.
--use-aapt2 Rebuild with aapt2.
usage: aldroid d[ebuggable] [options] --apk <apk_file> [splits]
Make an apk or a split apk debuggable and charlesable. Saves all inputs as <input>_debuggable.apk
-o <output_directory> The directory to save the apks to.
--use-aapt2 Rebuild with aapt2.
--split Indicates that this is a split apk and a list of splits follow the options.
-i|--install Install the apks after making them debuggable.
--pm-install Install the apk on the device using a pm install session instead of using 'adb install'.
usage: aldroid pull [options] <package_name>
Pull files for given package name.
-o <output_directory> Directory in which to store the files. Defaults to /tmp/<package_name>
--apk Pull apk(s).
--obb Pull obb(s).
usage: aldroid b[uild] [options] <path_to_decoded_folder>
Rebuilds a decoded APK using apktool. The final apk will be named "[name of decoded apk]_rebuilt.apk"
-o <output_directory> Directory in which to store the files. Defaults to current working directory.
usage: aldroid start <package_name>
Starts the app with the given package name on the connected device.
usage: aldroid kill <package_name>
Stops the app with the given package name on the connected device.
usage: aldroid sign <apk_file>
Signs the given (unsigned) APK in case of manual adjustment.
required tools:
adb - Android Platform Tools, usually located under ~/Library/Android/sdk/platform-tools/adb
apktool - Apktool, install via 'brew install apktool'
apksigner - Android Build Tools, usually located under ~/Library/Android/sdk/build-tools/<version>/apksigner
EOF
}
# Checks if debug keystore exists, otherwise create one
check_keystore() {
if [ ! -f ~/.android/debug.keystore ]; then
# Create ~/.android directory if it does not exist
if [ ! -d ~/.android ]; then
mkdir ~/.android
fi
# Generate a keystore and self-signed certificate:
echo "No debug keystore found, creating a new one..."
# -v: verbose mode enabled
# -keystore: storage path
# -storepass: keystore password
# -alias: unique alias
# -keypass: key password
# -keyalg: algorithm
# -keysize: key size
# -validity: validity in days
keytool -genkey \
-v \
-keystore ~/.android/debug.keystore \
-storepass android \
-alias androiddebugkey \
-keypass android \
-keyalg RSA \
-keysize 2048 \
-validity 10000
fi
}
# Check if apktool exists in path
check_apktool() {
command -v apktool >/dev/null 2>&1 || {
echo >&2 "ERROR: Apktool is not installed!"
exit 1
}
}
# Decompiles an apk with apktool
# First argument is the APK to decompile
# Second argument is optional and defines the path to the output folder (content will be overwritten if it exists) - defaults to /tmp/<apk_name_without_extensions>
decompile_apk() {
local APK_IN=$1
if [ -z "$APK_IN" ]; then
echo >&2 "ERROR: No APK file specified to decompile!"
exit 1
fi
# Strip APK file name of any extension
local -r APK_NAME_WITH_EXT=$(basename "$APK_IN")
local -r APK_NAME="${APK_NAME_WITH_EXT%.*}"
local -r OUTPUT_DIRECTORY=${2:-/tmp/$APK_NAME}
echo "Decompiling into $OUTPUT_DIRECTORY..."
# Check that apktool is installed
check_apktool
# Decompiles the apk
# -f: overwrite output directory
# -s: skips source decompilation which is faster and source access is not required in 99% of cases
# -o: explicitly set output directory
apktool d -f -s -o "$OUTPUT_DIRECTORY" "$APK_IN"
echo "Finished decompiling into ${OUTPUT_DIRECTORY}."
return 0
}
# Rebuilds an apk with apktool
# First argument is the folder to rebuild
compile_apk() {
local APK_IN=$1
# TODO: check that input path exists
# Check that apktool is installed
check_apktool
# Empty out internal frameworks in the output directory by force deleting the output directory
apktool empty-framework-dir --force "$APK_IN"
# Rebuild the apk. Reads $USE_AAPT2 which is set when this script is run with the --use-aapt2 flag
# -f: overwrite output APK if it already exists
# --use-aapt2: Use the newer aapt2 to recompile resources which is sometimes required for a successful build
# Will always output to APK_IN/dist/base.apk
apktool b -f $USE_AAPT2 "$APK_IN"
return 0
}
# Aligns and signs an APK
# First argument is the APK to resign
# Second argument is the output path for the resigned APK
sign_apk() {
local APK_IN=$1
# TODO: provide default for APK_OUT
local APK_OUT=$2
# Make sure the keystore exists
check_keystore
local debug_keystore=~/.android/debug.keystore
# Optionally realign APK
if [[ $ALIGN_OPT_SET == true ]]; then
echo "Aligning $APK_IN to $APK_OUT..."
# -f: overwrite output path if it exists
# 4: defines byte-alignment boundaries; must be 4
zipalign -f 4 "$APK_IN" "$APK_OUT"
else
cp "$APK_IN" "$APK_OUT"
fi
# Signs the APK
echo "Signing $APK_OUT..."
apksigner sign \
--ks "$debug_keystore" \
--ks-key-alias androiddebugkey \
--ks-pass pass:android \
--key-pass pass:android \
"$APK_OUT"
}
# Pulls all APKs for a package name and saves an array with all pulled APK names to PULLED_APKS
# First argument is the package name for which to pull the APKs
# Second optional argument is the folder to save the APKs in - defaults to /tmp/<package_name>
pull_apks() {
PULLED_APKS=()
local PACKAGE_NAME=$1
local OUTPUT_DIRECTORY=${2:-/tmp/$PACKAGE_NAME}
echo "Pulling APK(s) for $PACKAGE_NAME into ${OUTPUT_DIRECTORY}..."
# Ignore errors since our command is not guaranteed to succeed
set +e
# Gets a list of associated paths with the package name from pm (package manager). Packages are separated by newlines
local apks;
apks=$(adb shell pm path $PACKAGE_NAME)
# Exit on any errors
set -e
# No APK found for package name
if [[ -z $apks ]]; then
echo "No APKs found for package name $PACKAGE_NAME. Aborting..."
return 1
fi
# Create output directory if it does not exist
if [ ! -d "$OUTPUT_DIRECTORY" ]; then
mkdir "$OUTPUT_DIRECTORY"
fi
# Iterate over the list
while IFS= read -r line; do
# Each line is 'package:' followed by the absolute path to an APK
# Remove first 8 characters (package:) from start of line
local APK_REMOTE_PATH="${line:8}"
APK_REMOTE_PATH=${APK_REMOTE_PATH//[$'\t\r\n']}
# Pull APK from device and save it in the output directory
echo "adb pull $APK_REMOTE_PATH $OUTPUT_DIRECTORY"
adb pull "$APK_REMOTE_PATH" "$OUTPUT_DIRECTORY"
echo "Pulled ${APK_REMOTE_PATH##*/} to $OUTPUT_DIRECTORY/${APK_REMOTE_PATH##*/}"
# Add the saved APKs filename to the array
APK_REMOTE_BASE_NAME="$(basename "$APK_REMOTE_PATH")"
PULLED_APKS+=("$APK_REMOTE_BASE_NAME")
done <<< "$apks"
if [[ ${#PULLED_APKS[@]} -eq 0 ]]; then
echo "No APKs pulled package name $PACKAGE_NAME. Aborting..."
return 1
fi
return 0
}
# Updates a decompiled APK to make it debuggable and charlesable by adding android:debuggable="true" and updating/creating a network_security_config.xml
# First argument is the path to the decompiled APK
make_decompiled_debuggable() {
local INPUT_DIRECTORY=$1
# Create /res/xml directory for the APK if it does not exist
if [ ! -d "$INPUT_DIRECTORY/res/xml" ]; then
mkdir "$INPUT_DIRECTORY/res/xml"
fi
# Create network_security_config.xml or update it
# The pub may have named their networkSecurityConfig.xml something different so we need to grab it
local NSC_GREP=$(grep -E "<application.*?networkSecurityConfig=\".*?\".*?>" "$INPUT_DIRECTORY/AndroidManifest.xml")
# Default name
NSC_NAME="network_security_config"
# Since networkSecurityConfig is not defined, set our default in the Android Manifest if it is not in the application tag
if [[ -z $NSC_GREP ]]; then
sed -E "s/(<application)/\1 android\:networkSecurityConfig=\"@xml\/$NSC_NAME\" /" "$INPUT_DIRECTORY/AndroidManifest.xml" > "$INPUT_DIRECTORY/AndroidManifest.xml.tmp"
mv "$INPUT_DIRECTORY/AndroidManifest.xml.tmp" "$INPUT_DIRECTORY/AndroidManifest.xml"
else
# Make sure that the networkSecurityConfig has android: prefix
local NSC_PREFIX_GREP=$(grep -E "<application.*android:networkSecurityConfig=\".*?\".*?>" "$INPUT_DIRECTORY/AndroidManifest.xml")
# if the networkSecurityConfig is not prefixed with android: replace it
if [[ -z $NSC_PREFIX_GREP ]]; then
sed -E "s/networkSecurityConfig=/android:networkSecurityConfig=/g" "$INPUT_DIRECTORY/AndroidManifest.xml" > "$INPUT_DIRECTORY/AndroidManifest.xml.tmp"
mv "$INPUT_DIRECTORY/AndroidManifest.xml.tmp" "$INPUT_DIRECTORY/AndroidManifest.xml"
fi
# networkSecurityConfig is defined, find the name via regex
# First get a narrow match since ~= doesn't support lazy matching and grep doesn't support capture groups...
NSC_NARROW_MATCH=$(grep -oE "networkSecurityConfig=\"@xml/.*?\"" <<< "$NSC_GREP")
# Extract the networkSecurityConfig name from the narrow match
REGEX="networkSecurityConfig=\"@xml\/(.*)\""
if [[ $NSC_NARROW_MATCH =~ $REGEX ]]; then
NSC_NAME=${BASH_REMATCH[1]}
echo " Found networkSecurityConfig defined as: $NSC_NAME"
fi
fi
# Check for usesCleartextTraffic in the Android Manifest
# android:usesCleartextTraffic="true" allows cleartext traffic in the whole app but it is ignored when we add the network_security_config.xml
# If that option is set add corresponding network_security_config.xml
if grep "android:usesCleartextTraffic=\"true\"" "$INPUT_DIRECTORY/AndroidManifest.xml" || $OVERRIDE_NSC ; then
# android:usesCleartextTraffic is true
# Create a new network_security_config.xml with all cleartext traffic allowed (this will also overwrite any existing files)
cat > "$INPUT_DIRECTORY/res/xml/$NSC_NAME.xml" << EOM
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true">
</base-config>
<debug-overrides>
<trust-anchors>
<certificates src="user" />
</trust-anchors>
</debug-overrides>
</network-security-config>
EOM
fi
# If the network_security_config.xml does not exist
if [ ! -f "$INPUT_DIRECTORY/res/xml/$NSC_NAME.xml" ]; then
# android:usesCleartextTraffic not true or not set
# Create a new network_security_config.xml including only the debug override so we don't accidentally fix cleartext issues
cat > "$INPUT_DIRECTORY/res/xml/$NSC_NAME.xml" << EOM
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<debug-overrides>
<trust-anchors>
<certificates src="user" />
</trust-anchors>
</debug-overrides>
</network-security-config>
EOM
# If the network_security_config.xml already exists and does not contain debug-overrides
# TODO: technically there could be a case where the pub has overrides that do not include user certs, we should guard against that
elif ! grep "debug-overrides" "$INPUT_DIRECTORY/res/xml/$NSC_NAME.xml"; then
# Add debug-overrides to trust user certs
# New lines are escaped for better readability
sed -E "s/<\/network-security-config>/\
<debug-overrides>\
<trust-anchors>\
<certificates src=\"user\" \/>\
<\/trust-anchors>\
<\/debug-overrides>\
<\/network-security-config>/" "$INPUT_DIRECTORY/res/xml/$NSC_NAME.xml" > "$INPUT_DIRECTORY/res/xml/$NSC_NAME.xml.tmp"
mv "$INPUT_DIRECTORY/res/xml/$NSC_NAME.xml.tmp" "$INPUT_DIRECTORY/res/xml/$NSC_NAME.xml"
# if it exists and has debug-overrides but does not allow user certificates
# TODO: improve by handling all these cases more strictly, also maybe with just one pattern if possible
elif ! grep '<certificates src=\"user\"' "$INPUT_DIRECTORY/res/xml/$NSC_NAME.xml"; then
# use tr to translate newlines into carriage returns to have sed run on all lines
tr '\n' '\r' < "$INPUT_DIRECTORY/res/xml/$NSC_NAME.xml" | sed -E 's|(<debug-overrides>.*<trust-anchors>)(\r *)<|\1\2<certificates src="user"/>\2<|' | tr '\r' '\n' > "$INPUT_DIRECTORY/res/xml/$NSC_NAME.xml.tmp"
mv "$INPUT_DIRECTORY/res/xml/$NSC_NAME.xml.tmp" "$INPUT_DIRECTORY/res/xml/$NSC_NAME.xml"
fi
# Set debuggable in the Android Manifest
# TODO: make sure it's correctly inside the application tag
if grep -i "android:debuggable=\"false\"" "$INPUT_DIRECTORY/AndroidManifest.xml"; then
sed -i "" "s|android:debuggable=\"false\"|android:debuggable=\"true\"|g" "$INPUT_DIRECTORY/AndroidManifest.xml"
elif ! grep -i "android:debuggable" "$INPUT_DIRECTORY/AndroidManifest.xml"; then
sed -E "s/(<application)/\1 android\:debuggable=\"true\" /" "$INPUT_DIRECTORY/AndroidManifest.xml" > "$INPUT_DIRECTORY/AndroidManifest.xml.tmp"
mv "$INPUT_DIRECTORY/AndroidManifest.xml.tmp" "$INPUT_DIRECTORY/AndroidManifest.xml"
fi
# Set extractNativeLibs in the Android Manifest. Otherwise the app might crash when starting it on the device
# TODO: make sure it's correctly inside the application tag
if grep -i "extractNativeLibs=\"false\"" "$INPUT_DIRECTORY/AndroidManifest.xml"; then
sed -i "" "s|android:extractNativeLibs=\"false\"|android:extractNativeLibs=\"true\"|g" "$INPUT_DIRECTORY/AndroidManifest.xml"
fi
# Remove android:localeConfig as it's currently causing issues when recompiling
if grep -i "android:localeConfig" "$INPUT_DIRECTORY/AndroidManifest.xml"; then
echo "removing android:localeConfig from AndroidManifest"
sed -i "" "s|android:localeConfig=\"@xml\/locales_config\" ||g" "$INPUT_DIRECTORY/AndroidManifest.xml"
fi
# make locales_config compile by adding android schema
# can't just delete it as it's referenced elsewhere
if [ -f "$INPUT_DIRECTORY/res/xml/locales_config.xml" ]; then
echo "Adding xmlns:android schema to locales_config"
sed -i "" "s|<locale-config>|<locale-config xmlns:android=\"http:\/\/schemas.android.com\/apk\/res\/android\">|g" "$INPUT_DIRECTORY/res/xml/locales_config.xml"
fi
#remove meta data with @null values
if grep -iE "<meta-data[^>]+android:resource=\"@null\"" "$INPUT_DIRECTORY/AndroidManifest.xml"; then
sed -E -i "" "s|<meta-data[^>]+android:resource=\"@null\"/>||g" "$INPUT_DIRECTORY/AndroidManifest.xml"
fi
return 0
}
# Takes an apk and makes it debuggable and charlesable
# First argument is the APK file to make debuggable
# Second optional argument is the output file path for the debuggable APK - defaults to <APK_IN>_debuggable.apk
make_apk_debuggable() {
local -r APK_IN=$1
echo "Transforming $APK_IN to make it debuggable..."
# Get filename without extensions
local -r APK_NAME_WITH_EXT=$(basename "$APK_IN")
local -r APK_NAME="${APK_NAME_WITH_EXT%.*}"
# By default, output to /path/to/<APK_IN>_debuggable.apk
local -r APK_OUT=${2-${APK_IN%\.apk}_debuggable.apk}
echo "Saving output apk in ${APK_OUT}."
# Make sure we decompile in /tmp so we don't create unnecessary folders
local DECOMPIILE_DIRECTORY=${APK_IN%\.apk}
if [[ "$APK_IN" != \/tmp\/* ]]; then
DECOMPIILE_DIRECTORY="/tmp/${APK_NAME}"
fi
# Decompile the APK
decompile_apk "$APK_IN" "$DECOMPIILE_DIRECTORY"
# Extract package name for later use
extract_package_name_from_manifest "$DECOMPIILE_DIRECTORY/AndroidManifest.xml"
# Make it debuggable and charlesable
make_decompiled_debuggable "$DECOMPIILE_DIRECTORY"
# Rebuild it
compile_apk "$DECOMPIILE_DIRECTORY"
if [[ $USE_FALLBACK_DEBUGGABLE == true ]]; then
if [[ -z $NSC_NAME ]]; then
NSC_NAME="network_security_config"
fi
echo "Using $NSC_NAME as nsc name"
echo "Using fallback to manually replace AndroidManifest and networkSecurityConfig."
rm -rf "$DECOMPIILE_DIRECTORY/../uz"
rm -rf "$DECOMPIILE_DIRECTORY/../uz0"
unzip -q -d "$DECOMPIILE_DIRECTORY/../uz" "$DECOMPIILE_DIRECTORY/../base.apk"
unzip -q -d "$DECOMPIILE_DIRECTORY/../uz0" "$DECOMPIILE_DIRECTORY/dist/${APK_NAME}.apk"
cp "$DECOMPIILE_DIRECTORY/../uz0/AndroidManifest.xml" "$DECOMPIILE_DIRECTORY/../uz/AndroidManifest.xml"
cp "$DECOMPIILE_DIRECTORY/../uz0/res/xml/$NSC_NAME.xml" "$DECOMPIILE_DIRECTORY/../uz/res/xml/$NSC_NAME.xml"
pushd "$DECOMPIILE_DIRECTORY/../uz"
zip -q -r -n resources.arsc ../test.apk .
popd
sign_apk "${DECOMPIILE_DIRECTORY}/../test.apk" "$APK_OUT"
else
# Align and sign it
sign_apk "${DECOMPIILE_DIRECTORY}/dist/${APK_NAME}.apk" "$APK_OUT"
fi
}
# Installs an APK or multiple APKs to a device with adb install / adb install-multiple
# Takes a list of APKs to install as arguments
install_apks() {
# TODO: check for arguments
local APKS=("$@")
if [[ $USE_PM_INSTALL == true ]]; then
CREATE_SESSION=$(adb shell pm install-create)
REGEX="Success: created install session \[([0-9]+)\]"
if [[ $CREATE_SESSION =~ $REGEX ]]; then
SESSION_ID=${BASH_REMATCH[1]}
echo "Started install session with session id: $SESSION_ID"
else
echo >&2 "Unable to start install session"
exit 1
fi
for APK in "${APKS[@]}"
do
BASE_APK_NAME=$(basename "$APK")
echo "Pushing $APK to device (/data/local/tmp/$BASE_APK_NAME)"
adb push "$APK" "/data/local/tmp/$BASE_APK_NAME"
echo "Adding $BASE_APK_NAME to install session"
adb shell pm install-write $SESSION_ID "$BASE_APK_NAME" "/data/local/tmp/$BASE_APK_NAME"
done
echo "Finalizing install"
adb shell pm install-commit $SESSION_ID
return 0
fi
# Determine whether we have more then one APK and run adb install-multiple in that case
local cmd="adb install"
if [ ${#APKS[@]} -gt 1 ]; then
cmd="adb install-multiple"
fi
# Install it on the device
echo "Installing the following APK(s): ${APKS[@]}..."
$cmd $INCREMENTAL ${APKS[@]}
}
# Uninstalls a package from a device
# The first argument is the package name to uninstall
uninstall_package() {
# TODO: check for arguments
echo "Uninstalling $1..."
adb uninstall $1
}
# Pulls all apks for a package name, makes them debuggable and reinstalls them
# The first argument is the package name of the app
make_apk_debuggable_from_device() {
local -r PACKAGE_NAME=$1
local -r OUTPUT_DIRECTORY="/tmp/${PACKAGE_NAME}"
echo "Making app $PACKAGE_NAME debuggable..."
echo "Storing files in $OUTPUT_DIRECTORY"
# Pull all APKs
pull_apks "$PACKAGE_NAME" "$OUTPUT_DIRECTORY"
# Pull all OBBs
pull_obbs "$PACKAGE_NAME"
local INDEX=1
local APKS=()
# Iterate over pulled APKs
for APK in "${PULLED_APKS[@]}"
do
# Ignore empty or whitespace entries
if [ -z "${APK// }" ]; then
continue
fi
echo "Transforming $APK..."
if [[ "$APK" == "base.apk" ]]; then
# Base APK must be transformed to make it debuggable
make_apk_debuggable "${OUTPUT_DIRECTORY}/${APK}" "${OUTPUT_DIRECTORY}/0.apk"
# Save as 0.apk and add it to index 0 in the array
APKS[0]="${OUTPUT_DIRECTORY}/0.apk"
else
# Split APKs just need to be resigned so the signature matches the base.apk
sign_apk "${OUTPUT_DIRECTORY}/${APK}" "${OUTPUT_DIRECTORY}/${INDEX}.apk"
# We number the starting at 1 so the base is always at the start of the array
APKS[INDEX]="${OUTPUT_DIRECTORY}/${INDEX}.apk"
((INDEX++))
fi
done
# Uninstall the app as we likely have a different signature now so reinstalling would throw an error
uninstall_package "$PACKAGE_NAME"
# Install our new APK(s)
install_apks "${APKS[@]}"
# Push back any OBBs we pulled so the game will run
push_obbs "$PACKAGE_NAME"
start_app "$PACKAGE_NAME"
}
# Pulls all OBBs associated with a package name and saves them in the array OBBS
# First argument is the package name for which to pull OBBs
# Second optional argument is the output directory to save the OBBs at - defaults to /tmp/<package name>
pull_obbs() {
echo "Pulling OBB(s) for $1..."
# Verify an argument was provided
if [ -z $1 ]; then
echo >&2 "ERROR: No package name provided to pull_obbs!"
exit 1
fi
# Going to have to save the exit code. Declaring variable before we use it since local is itself something that generates an exit code
local EXIT_CODE
local TEMP_OBBS
# Initialize as an empty array
OBBS=()
# Ignore errors since our ls command is not guaranteed to succeed
set +e
# OBBs are always saved at /sdcard/Android/obb/<package name> so we use ls to get a list of files there
TEMP_OBBS=$(adb shell ls "/sdcard/Android/obb/$1")
# Save exit code so we can use it to check if it worked
EXIT_CODE=$?
# Exit on any errors
set -e
# No OBBs found or no device connected
if [[ $EXIT_CODE -ne 0 || -z $TEMP_OBBS ]]; then
echo 'No OBBs found on device.'
return 0
fi
# TODO: technically on some devices this will return code 0 and only a newline as output
# We should stop this here instead of catching it later in the loop
# Determine output directory
local -r OUTPUT_DIRECTORY=${2-/tmp/$1}
# Create output directory if it does not exist
if [ ! -d "$OUTPUT_DIRECTORY" ]; then
mkdir "$OUTPUT_DIRECTORY"
fi
# Iterate over all OBBs we found and pull them from the device
for OBB in "$TEMP_OBBS"; do
# In case there are other files there make sure the obb files end in .obb
if [[ "${OBB: -4}" != ".obb" ]]; then
continue
fi
adb pull "/sdcard/Android/obb/$1/$OBB" "$OUTPUT_DIRECTORY/$OBB"
echo "Pulled $OBB into $OUTPUT_DIRECTORY/$OBB"
OBBS+=$OBB
done
return 0
}
# Pushes OBBs back to the device
# Uses array stored in OBBS variable and assumes they reside in /tmp/<package name>
# First argument is the package name for which to push OBBs for
push_obbs() {
# Verify an argument was provided
if [ -z "$1" ]; then
echo "No package name provided to push_obbs"
exit 1
fi
echo "Pushing OBB(s)..."
echo "$OBBS"
# Safety for empty arrays as if it's empty we would push the entire folder
if [[ ${#OBBS[@]} -eq 0 ]]; then
echo "No OBBs to push"
return 0
fi
# Iterate all OBBs on $OBBS and push them back to the device
for OBB in "$OBBS"; do
adb push "/tmp/$1/$OBB" "/sdcard/Android/obb/$1/$OBB"
done
return 0
}
# Starts an app on the device given a package name
# First argument is the package name to start
start_app() {
# Verify an argument was provided
if [ -z $1 ]; then
echo "No package name provided to start_app"
exit 1
fi
local PACKAGE_NAME=$1
# Monkey is a tool to simulate user interaction. In this case it simulates a press on the app icon
adb shell monkey -p "${PACKAGE_NAME}" -c android.intent.category.LAUNCHER 1 >/dev/null 2>&1
}
# Parses an AndroidManifest.xml to extract the package name
# First argument is the path to the AndroidManifest.xml
# Saves package name in EXTRACTED_PACKAGE_NAME
extract_package_name_from_manifest() {
# Verify an argument was provided
if [ -z $1 ]; then
echo "No argument provided to extract_package_name_from_manifest"
exit 1
fi
if [ ! -f $1 ]; then
echo "$1 is not a path to a valid file"
exit 1
fi
# Get AndroidManifest content
local MANIFEST=$(cat "$1")
local PACKAGE_NAME=
# The manifest will include package inside the manifest tag
# Ex: <manifest package="com.my.package.name">
# Trim start until package="
PACKAGE_NAME=${MANIFEST#*package=\"}
# Trim everything after first "
PACKAGE_NAME=${PACKAGE_NAME%%\"*}
# Check if we have a valid package name
# TODO: We only check if the string is not empty here but we should also guard against other cases like spaces in the string. Probably best to add a regex check like [a-zA-Z\.] to validate
if [[ ! -z "$PACKAGE_NAME" ]]; then
EXTRACTED_PACKAGE_NAME=$PACKAGE_NAME
echo "Extracted package name: ${PACKAGE_NAME}"
else
echo "Unable to determine package name."
fi
}
# Helper method for d[ebug] --apk to unclutter getopts
# Makes provided APK(s) debuggable and may install them incase -i/--install was set
# All splits are provided as a list of arguments
parse_make_apk_debuggable() {
local BASE_APK_OUT=
# Set default output path
if [[ -z $OUT_OPT_ARG ]]; then
BASE_APK_OUT=${BASE_APK_ARG%\.apk}_debuggable.apk
make_apk_debuggable "$BASE_APK_ARG" "$BASE_APK_OUT"
else
# Make sure directory exists
if [[ ! -d "$OUT_OPT_ARG" ]]; then
mkdir "$OUT_OPT_ARG"
fi
# Because of --split and for consistency -o will always be a directory
# Get output name
local -r BASE_APK_NAME_WITH_EXT=$(basename "$BASE_APK_ARG")
local -r BASE_APK_NAME=${BASE_APK_NAME_WITH_EXT%\.apk}_debuggable.apk
BASE_APK_OUT="${OUT_OPT_ARG}/$BASE_APK_NAME"
make_apk_debuggable "$BASE_APK_ARG" "$BASE_APK_OUT"
fi
# Save split locations so we can add them to the install command later
SPLITS=()
if [[ $SPLIT_OPT_SET == true ]]; then
local -r OUTPUT_PATH=${OUT_OPT_ARG:-/tmp/$BASE_APK_ARG}
for SPLIT in "$@"
do
local -r APK_NAME_WITH_EXT=$(basename "$SPLIT")
local -r APK_NAME=${APK_NAME_WITH_EXT%\.apk}_debuggable.apk
local -r split_out_path="${OUTPUT_PATH}/${APK_NAME}"
# Add split to the array
SPLITS+=("$split_out_path")
sign_apk "${SPLIT}" "$split_out_path"
done
fi
# Install the apks if -i/--install is set
if [[ $INSTALL_OPT_SET == true ]]; then
# Ignore errors since uninstall will fail if the app is not yet installed
set +e
# Uninstall the app
uninstall_package $EXTRACTED_PACKAGE_NAME
# Exit on any errors
set -e
# Install the app
install_apks "$BASE_APK_OUT" "${SPLITS[@]}"
# Start the app after it has been installed
start_app "${EXTRACTED_PACKAGE_NAME}"
fi
}
# Exit script after any errors
set -e
# Global variables for return values of pull_apks and pull_obbs and extract_package_name_from_manifest
PULLED_APKS=()
OBBS=()
EXTRACTED_PACKAGE_NAME=
# Parse basic options
while getopts "h?v" opt; do
case "$opt" in
v)
echo "$VERSION"
exit 0
;;
h|\?)
usage
exit 0
;;
esac
done
# End option parsing by dropping all parsed arguments
shift $((OPTIND-1))
# Save subcommand and remove it from list of arguments
SUBCOMMAND=$1
shift
# Initialize option argument variables
BASE_APK_ARG=
OUT_OPT_ARG=
APK_OPT_SET=false
OBB_OPT_SET=false
SPLIT_OPT_SET=false
INSTALL_OPT_SET=false
USE_AAPT2='--use-aapt2'
ALIGN_OPT_SET=false
OVERRIDE_NSC=false
USE_PM_INSTALL=false
INCREMENTAL='--no-incremental'
USE_FALLBACK_DEBUGGABLE=false
# Parse options for subcommand
while getopts "i-:o:" opt; do
case "$opt" in
h|\?)
usage
exit 0
;;
v)
echo "$0 - version: $VERSION"
exit 0
;;
o)
OUT_OPT_ARG="${OPTARG}"
;;
i)
INSTALL_OPT_SET=true
;;
-)
case "${OPTARG}" in
apk)
APK_OPT_SET=true
if [[ $SUBCOMMAND == "d" || $SUBCOMMAND == "debuggable" || $SUBCOMMAND == "install" ]]; then
BASE_APK_ARG="${!OPTIND}";
OPTIND=$(( $OPTIND + 1 ))
# Exit if BASE_APK_ARG does not exist
if [[ ! -f $BASE_APK_ARG ]]; then
echo "ERROR: Input APK $BASE_APK_ARG does not exist."
exit 1
fi
fi
;;
obb)
OBB_OPT_SET=true
;;
split)
SPLIT_OPT_SET=true
;;
use-aapt)
USE_AAPT2=''
;;
use-aapt2)
USE_AAPT2='--use-aapt2'
;;
no-incremental)
INCREMENTAL='--no-incremental'
;;
incremental)
INCREMENTAL=''
;;
install)
INSTALL_OPT_SET=true
;;
align)
ALIGN_OPT_SET=true
;;
override-nsc)
OVERRIDE_NSC=true
;;
pm-install)
USE_PM_INSTALL=true
;;
fallback)
USE_FALLBACK_DEBUGGABLE=true
;;
*) # Others - print usage
usage
exit 1
;;
esac
;;
esac
done
# End option parsing by dropping all parsed arguments
shift $((OPTIND-1))
# We require a subcommand to be provided as the first argument
if [[ -z $SUBCOMMAND ]]; then
usage
exit 1
fi
echo "aldroid v$VERSION"
case $SUBCOMMAND in
d|debuggable)
if [[ $APK_OPT_SET == true ]]; then
echo "Making $BASE_APK_ARG debuggable..."
parse_make_apk_debuggable
else
make_apk_debuggable_from_device "$1"
fi
exit 0
;;
p|pull)
# Verify an argument was provided
if [ -z $1 ]; then
echo >&2 "ERROR: No package name provided to pull!"
exit 1
fi
# If --apk was set, pull APKs
if [[ $APK_OPT_SET == true ]]; then
pull_apks "$1" "$OUT_OPT_ARG"
fi
# If --obb was set, pull OBBs
if [[ $OBB_OPT_SET == true ]]; then
pull_obbs "$1" "$OUT_OPT_ARG"
fi
exit 0
;;
s|start)
# Verify an argument was provided
if [ -z $1 ]; then
echo >&2 "ERROR: No package name provided to start!"
exit 1
fi
start_app $1
exit 0
;;
sign)
# verify input apk was provided
if [ -z $1 ]; then
echo >&2 "ERROR: please provide input apk!"
exit 1
fi
# Strip APK file name of any extension
APK_NAME_WITH_EXT=$(basename "$1")
APK_NAME="${APK_NAME_WITH_EXT%.*}"
# Set output paths
# defaults to just put it in the current working directory
APK_OUT="${APK_NAME}_resigned.apk"
sign_apk "$1" "$APK_OUT"
echo "Signed APK at $APK_OUT"
;;
# TODO: support an install action which pushes obbs too?
# install)
# ;;
# TODO: support pushing a set of obbs with a given package name, to do that push_obbs should accept an optional parameter or the whole obb code needs to be rewritten to no longer need hard coded path for location
# push-obb)
# push_obbs $2
# ;;
b|build)
# verify path was provided
if [ -z $1 ]; then
echo >&2 "ERROR: path to folder to build provided!"
exit 1
fi
# Extract name for APK from apktool.yml
APK_NAME=$(grep "apkFileName: .*.apk" "$1/apktool.yml")
REGEX="apkFileName: (.*).apk"
if [[ $APK_NAME =~ $REGEX ]]; then
APK_NAME=${BASH_REMATCH[1]}
else
echo >&2 "ERROR: Unable to get name from apktool.yml!"
exit 1
fi
# Set output paths
if [[ -z $OUT_OPT_ARG ]]; then
# default to just put it in the current working directory
APK_OUT="${APK_NAME}_rebuilt.apk"
else
# Make sure directory exists
if [[ ! -d "$OUT_OPT_ARG" ]]; then
mkdir "$OUT_OPT_ARG"
fi
# Because of --split and for consistency -o will always be a directory. Combine with name of decoded APK
#TODO maybe we want to support a different argument here to be able to set a specific apk name
# Get output name
APK_OUT="${OUT_OPT_ARG}/${APK_NAME}.apk"
fi
# Rebuild it
compile_apk "$1"
# Align and sign it
sign_apk "$1/dist/${APK_NAME}.apk" "$APK_OUT"
# TODO support specifying other APKs that also need to be installed and auto-pickup of numbered apks (ie 1.apk 2.apk etc)
if [[ $INSTALL_OPT_SET == true ]]; then
install_apks "$APK_OUT"
fi
echo "Output APK at $APK_OUT"
;;
k|kill)
adb shell am force-stop $1
;;
*) # Undefined - print usage
usage
exit 1
;;
esac