-
Notifications
You must be signed in to change notification settings - Fork 427
/
amba_sys_hardcoder.py
executable file
·2903 lines (2617 loc) · 128 KB
/
amba_sys_hardcoder.py
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Ambarella Firmware SYS partiton hard-coded values editor.
The tool can parse Ambarella firmware SYS partition converted to ELF.
It finds certain hard-coded values in the binary data, and allows
exporting or importing them.
Only 'setValue' element in the exported file is really changeable,
all the other data is just informational. This includes `maxValue` and
`minValue` - they don't do anything and changing them in the JSON file
will not influence update operation.
Exported values:
og_hardcoded.p3x_ambarella.*_authority_level -
Authority Level controls whether the module should respond to external
commands. Normally it is set to `1`, but if encryption keys verification
failed at startup, it is set to `0`. These parameters allow to change the
value, so that the camera continues to operate normally even if keys are
different or SHA204 chip is missing. There is no reason to keep the values
unchanged even if encryption pairing currently works fine - the changes might
become helpful in case of hardware malfunction in that area.
Here's an example AmbaShell log when there's an issue with encryption which
results in lowest Authority Level:
```
[DJI_ENCRYPT] [DjiEncryptCheckA9]check a9 mac failed
[DJI_ENCRYPT] [DjiEncryptReGetA9Status]a9's encrypt status[1] verify state[0]
```
og_hardcoded.p3x_ambarella.vid_setting_bitrates_* -
These are bitrates used when encoding videos to SD-card. There are 27 sets,
and which one is used depends on options selected in mobile app and on
model of the drone. Specifics are not known at this point.
"""
# Copyright (C) 2016,2017 Mefistotelis <[email protected]>
# Copyright (C) 2018 Original Gangsters <https://dji-rev.slack.com/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
__version__ = "0.0.3"
__author__ = "Mefistotelis @ Original Gangsters"
__license__ = "GPL"
import sys
import argparse
import os
import re
import io
import collections
import struct
import enum
import json
from ctypes import c_ubyte, c_uint8, c_int, sizeof, LittleEndianStructure
try:
import capstone
from capstone import CS_ARCH_ARM, CS_ARCH_ARM64, CS_ARCH_X86, CS_ARCH_MIPS
from capstone import CS_MODE_ARM, CS_MODE_V8, CS_MODE_32, CS_MODE_64, CS_MODE_MIPS32, CS_MODE_MIPS64
from capstone import CS_MODE_THUMB, CS_MODE_LITTLE_ENDIAN, CS_MODE_BIG_ENDIAN
if not callable(getattr(capstone, "Cs", None)):
raise ImportError("The capstone library provided is incorrect - lacks Cs")
except ImportError:
print("Warning:")
print("This tool requires capstone to disassemble binary bytecode.")
raise
try:
import keystone
from keystone.keystone_const import KS_ARCH_ARM, KS_ARCH_ARM64, KS_ARCH_X86, KS_ARCH_MIPS
from keystone.keystone_const import KS_MODE_ARM, KS_MODE_V8, KS_MODE_32, KS_MODE_64, KS_MODE_MIPS32, KS_MODE_MIPS64
from keystone.keystone_const import KS_MODE_THUMB, KS_MODE_LITTLE_ENDIAN, KS_MODE_BIG_ENDIAN
from keystone import KsError
if not callable(getattr(keystone, "Ks", None)):
raise ImportError("The keystone library provided is incorrect - lacks Ks")
except ImportError:
print("Warning:")
print("This tool requires keystone-engine to re-compile patched assembly.")
raise
sys.path.insert(0, '../pyelftools')
try:
from elftools.elf.elffile import ELFFile
from elftools.elf.constants import SH_FLAGS
if not callable(getattr(ELFFile, "write_changes", None)):
raise ImportError("The pyelftools library provided has no write support")
except ImportError:
print("Warning:")
print("This tool requires version of pyelftools with ELF write support.")
print("Try `arm_bin2elf.py` for details.")
raise
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
class VarType(enum.Enum):
# Variable points to code line from asm regular expression
DIRECT_LINE_OF_CODE = enum.auto()
# Variable contains directly entered integer value
DIRECT_INT_VALUE = enum.auto()
# Variable represents assembler operand
DIRECT_OPERAND = enum.auto()
# Variable contains absolute address to a code chunk or function
ABSOLUTE_ADDR_TO_CODE = enum.auto()
# Variable contains absolute address to a global variable
ABSOLUTE_ADDR_TO_GLOBAL_DATA = enum.auto()
# Variable contains address to a code chunk relative to some base address
RELATIVE_ADDR_TO_CODE = enum.auto()
# Variable contains relative address to a global variable which contains
# absolute address to the code chunk
RELATIVE_ADDR_TO_PTR_TO_CODE = enum.auto()
# Variable contains address to a global variable relative to some base address
RELATIVE_ADDR_TO_GLOBAL_DATA = enum.auto()
# Variable contains relative address to a global variable which contains
# absolute address to the real value
RELATIVE_ADDR_TO_PTR_TO_GLOBAL_DATA = enum.auto()
# Variable contains offset in unknown relation to some address, ie
# field position within a struct; obsolete - use the above instead
RELATIVE_OFFSET = enum.auto()
# Variable contains data not directly bound to any input offset
DETACHED_DATA = enum.auto()
# Variable which value is unused in current variant of the code
UNUSED_DATA = enum.auto()
# Internal variable of the tool, not to be used in pattern definitions
INTERNAL_DATA = enum.auto()
class DataVariety(enum.Enum):
UNKNOWN = enum.auto()
CHAR = enum.auto()
UINT8_T = enum.auto()
UINT16_T = enum.auto()
UINT32_T = enum.auto()
UINT64_T = enum.auto()
INT8_T = enum.auto()
INT16_T = enum.auto()
INT32_T = enum.auto()
INT64_T = enum.auto()
FLOAT = enum.auto()
DOUBLE = enum.auto()
STRUCT = enum.auto()
class CodeVariety(enum.Enum):
# Just a chunk of code, not a function start
CHUNK = enum.auto()
# The pointed place is a function start
FUNCTION = enum.auto()
class DummyStruct(LittleEndianStructure):
_pack_ = 1
_fields_ = [('unk', c_uint8)]
# List of architectures
# based on ropstone by blasty
elf_archs = [
{
'name' : "arm",
'cs_const' : CS_ARCH_ARM,
'ks_const' : KS_ARCH_ARM,
'boundary' : 4,
'modes' : [
{
'name' : "arm",
'desc' : "ARMv7 processor mode",
'cs_const' : CS_MODE_ARM,
'ks_const' : KS_MODE_ARM,
},
{
'name' : "armv8",
'desc' : "ARMv8 processor mode",
'cs_const' : CS_MODE_V8,
'ks_const' : KS_MODE_V8,
},
{
'name' : "thumb",
'desc' : "THUMB processor mode",
'cs_const' : CS_MODE_THUMB,
'ks_const' : KS_MODE_THUMB,
# this overrides the boundary of the parent architecture
'boundary' : 2,
# this adds a shift offset to the output addr to force THUMB mode
'retshift' : 1,
},
{
'name' : "le",
'desc' : "Little endian",
'byteorder': "little",
'cs_const' : CS_MODE_LITTLE_ENDIAN,
'ks_const' : KS_MODE_LITTLE_ENDIAN,
},
{
'name' : "be",
'desc' : "Big endian",
'byteorder': "big",
'cs_const' : CS_MODE_BIG_ENDIAN,
'ks_const' : KS_MODE_BIG_ENDIAN,
},
]
},
{
'name' : "arm64",
'cs_const' : CS_ARCH_ARM64,
'ks_const' : KS_ARCH_ARM64,
'boundary' : 4,
'modes' : [
{
'name' : "le",
'desc' : "Little Endian",
'byteorder': "little",
'cs_const' : CS_MODE_LITTLE_ENDIAN,
'ks_const' : KS_MODE_LITTLE_ENDIAN,
},
]
},
{
'name' : "mips",
'cs_const' : CS_ARCH_MIPS,
'ks_const' : KS_ARCH_MIPS,
'boundary' : 4,
'modes' : [
{
'name' : "32b",
'desc' : "MIPS32",
'cs_const' : CS_MODE_MIPS32,
'ks_const' : KS_MODE_MIPS32,
},
{
'name' : "64b",
'desc' : "MIPS64",
'cs_const' : CS_MODE_MIPS64,
'ks_const' : KS_MODE_MIPS64,
},
{
'name' : "le",
'desc' : "Little endian",
'byteorder': "little",
'cs_const' : CS_MODE_LITTLE_ENDIAN,
'ks_const' : KS_MODE_LITTLE_ENDIAN,
},
{
'name' : "be",
'desc' : "Big endian",
'byteorder': "big",
'cs_const' : CS_MODE_BIG_ENDIAN,
'ks_const' : KS_MODE_BIG_ENDIAN,
},
]
},
{
'name' : "x86",
'cs_const' : CS_ARCH_X86,
'ks_const' : KS_ARCH_X86,
'boundary' : 1,
'modes' : [
{
'name' : "32b",
'desc' : "x86 32bit",
'byteorder': "little",
'cs_const' : CS_MODE_32,
'ks_const' : KS_MODE_32,
},
{
'name' : "64b",
'desc' : "x86_64 64bit",
'byteorder': "little",
'cs_const' : CS_MODE_64,
'ks_const' : KS_MODE_64,
},
]
}
]
# Function with address to _msg_author_level
re_func_DjiMsgAuthorLevelGet = {
'name': "DjiMsgAuthorLevelGet",
'version': "P3X_FW_V01.01",
're': """
DjiMsgAuthorLevelGet:
ldr r0, \[pc, #(?P<msg_author_level>[0-9a-fx]+)\]
ldr r0, \[r0\]
bx lr
""",
'vars': {
'DjiMsgAuthorLevelGet': {'type': VarType.DIRECT_LINE_OF_CODE, 'variety': CodeVariety.FUNCTION},
'msg_author_level': {'type': VarType.RELATIVE_ADDR_TO_PTR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.UINT32_T},
},
}
re_func_DjiMsgSettingsInit = {
'name': "DjiMsgSettingsInit",
'version': "P3X_FW_V01.01",
're': """
DjiMsgSettingsInit:
push {r4, r5, lr}
sub sp, sp, #0x14
mov r4, #0
mov r1, #0
strb r1, \[sp, #0x11\]
mov r1, #0
strb r1, \[sp, #0x10\]
mov r5, #0
ldr r0, \[pc, #(?P<dji_msg_mutex>[0-9a-fx]+)\]
bl #(?P<AmbaKAL_MutexCreate>[0-9a-fx]+)
movs r4, r0
cmp r4, #0
beq #(?P<loc_label02>[0-9a-fx]+)
ldr r0, \[pc, #(?P<printk_log_level>[0-9a-fx]+)\]
ldr r0, \[r0\]
cmp r0, #0
bmi #(?P<loc_label03>[0-9a-fx]+)
mov r5, #0
mov r0, #1
movs r5, r0
bl #(?P<AmbaPrintk_Disabled>[0-9a-fx]+)
cmp r0, #1
beq #(?P<loc_label03>[0-9a-fx]+)
ldr r0, \[pc, #(?P<cstr_func_name>[0-9a-fx]+)\]
str r0, \[sp, #0xc\]
ldr r0, \[pc, #(?P<cstr_fmt_text1>[0-9a-fx]+)\]
str r0, \[sp, #8\]
str r5, \[sp, #4\]
mov r0, #0
str r0, \[sp\]
mov r3, #0
mov r2, #1
mov r1, #1
mov r0, #1
bl #(?P<AmbaPrintk>[0-9a-fx]+)
loc_label03:
movs r0, r4
b #(?P<loc_label06>[0-9a-fx]+)
loc_label02:
mov r0, #0
bl #(?P<DjiMsgAuthorLevelSet>[0-9a-fx]+)
movs r4, r0
add r1, sp, #0x10
add r0, sp, #0x11
bl #(?P<DjiEncryptGetA9Status>[0-9a-fx]+)
cmp r0, #0
beq #(?P<loc_label09>[0-9a-fx]+)
mov r0, #(?P<encrypt_query_fail_authority_level>[0-9a-fx]+)
bl #(?P<DjiMsgAuthorLevelSet>[0-9a-fx]+)
loc_label09:
ldrb r0, \[sp, #0x11\]
cmp r0, #1
bne #(?P<loc_label10>[0-9a-fx]+)
ldrb r0, \[sp, #0x10\]
cmp r0, #1
bne #(?P<loc_label10>[0-9a-fx]+)
mov r0, #(?P<verify_state_good_authority_level>[0-9a-fx]+)
bl #(?P<DjiMsgAuthorLevelSet>[0-9a-fx]+)
b #(?P<loc_label11>[0-9a-fx]+)
loc_label10:
mov r0, #(?P<verify_state_bad_authority_level>[0-9a-fx]+)
bl #(?P<DjiMsgAuthorLevelSet>[0-9a-fx]+)
loc_label11:
mov r5, #0
b #(?P<loc_label12>[0-9a-fx]+)
loc_label13:
ldr r0, \[pc, #(?P<unk_var01>[0-9a-fx]+)\]
lsls r1, r5, #2
ldr r2, \[pc, #(?P<unk_var02>[0-9a-fx]+)\]
adds r1, r1, r2
mov r2, #1
str r2, \[r0, r1\]
adds r5, r5, #1
loc_label12:
cmp r5, #4
blo #(?P<loc_label13>[0-9a-fx]+)
ldr r0, \[pc, #(?P<unk_var03>[0-9a-fx]+)\]
mov r1, #0
str r1, \[r0\]
ldr r0, \[pc, #(?P<unk_var04>[0-9a-fx]+)\]
mov r1, #1
str r1, \[r0\]
ldr r0, \[pc, #(?P<msg_adjust_task_finished>[0-9a-fx]+)\]
mov r1, #0
str r1, \[r0\]
ldr r0, \[pc, #(?P<unk_var05>[0-9a-fx]+)\]
mov r1, #0
str r1, \[r0\]
mov r2, #0x90
mov r1, #0
ldr r0, \[pc, #(?P<unk_var06>[0-9a-fx]+)\]
bl #(?P<memset_0>[0-9a-fx]+)
mov r2, #0x38
mov r1, #0
ldr r0, \[pc, #(?P<unk_var07>[0-9a-fx]+)\]
bl #(?P<memset_0>[0-9a-fx]+)
mov r2, #0xc
mov r1, #0
ldr r0, \[pc, #(?P<unk_var08>[0-9a-fx]+)\]
bl #(?P<memset_0>[0-9a-fx]+)
mov r2, #8
mov r1, #0
ldr r0, \[pc, #(?P<unk_var09>[0-9a-fx]+)\]
bl #(?P<memset_0>[0-9a-fx]+)
ldr r0, \[pc, #(?P<dji_msg_mutex>[0-9a-fx]+)\]
ldr r1, \[pc, #(?P<unk_var10>[0-9a-fx]+)\]
str r1, \[r0, #(?P<unk_offs01>[0-9a-fx]+)\]
movw r2, #0x1010
mov r1, #0
ldr r0, \[pc, #(?P<unk_var11>[0-9a-fx]+)\]
bl #(?P<memset_0>[0-9a-fx]+)
mov r2, #8
mov r1, #0
ldr r0, \[pc, #(?P<unk_var12>[0-9a-fx]+)\]
bl #(?P<memset_0>[0-9a-fx]+)
mov r2, #0xc
mov r1, #0
ldr r0, \[pc, #(?P<unk_var13>[0-9a-fx]+)\]
bl #(?P<memset_0>[0-9a-fx]+)
mov r2, #8
mov r1, #0
ldr r0, \[pc, #(?P<unk_var14>[0-9a-fx]+)\]
bl #(?P<memset_0>[0-9a-fx]+)
mov r2, #0x16
mov r1, #0
ldr r0, \[pc, #(?P<unk_var15>[0-9a-fx]+)\]
bl #(?P<memset_0>[0-9a-fx]+)
ldr r0, \[pc, #(?P<unk_var16>[0-9a-fx]+)\]
mov r1, #0
strb r1, \[r0\]
mov r2, #0x36
mov r1, #0
ldr r0, \[pc, #(?P<unk_var17>[0-9a-fx]+)\]
bl #(?P<memset_0>[0-9a-fx]+)
ldr r0, \[pc, #(?P<unk_var18>[0-9a-fx]+)\]
mov r1, #1
str r1, \[r0\]
mov r2, #0xc
mov r1, #0
ldr r0, \[pc, #(?P<unk_var19>[0-9a-fx]+)\]
bl #(?P<memset_0>[0-9a-fx]+)
mov r2, #4
mov r1, #0
ldr r0, \[pc, #(?P<unk_var20>[0-9a-fx]+)\]
bl #(?P<memset_0>[0-9a-fx]+)
mov r0, #0
loc_label06:
add sp, sp, #0x14
pop {r4, r5, pc}
""",
'vars': {
'DjiMsgSettingsInit': {'type': VarType.DIRECT_LINE_OF_CODE, 'variety': CodeVariety.FUNCTION},
'AmbaKAL_MutexCreate': {'type': VarType.ABSOLUTE_ADDR_TO_CODE, 'variety': CodeVariety.FUNCTION},
'AmbaPrintk_Disabled': {'type': VarType.ABSOLUTE_ADDR_TO_CODE, 'variety': CodeVariety.FUNCTION},
'AmbaPrintk': {'type': VarType.ABSOLUTE_ADDR_TO_CODE, 'variety': CodeVariety.FUNCTION},
'DjiMsgAuthorLevelSet': {'type': VarType.ABSOLUTE_ADDR_TO_CODE, 'variety': CodeVariety.FUNCTION},
'DjiEncryptGetA9Status': {'type': VarType.ABSOLUTE_ADDR_TO_CODE, 'variety': CodeVariety.FUNCTION},
'memset_0': {'type': VarType.ABSOLUTE_ADDR_TO_CODE, 'variety': CodeVariety.FUNCTION},
'cstr_fmt_text1': {'type': VarType.RELATIVE_ADDR_TO_PTR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.CHAR, 'array': "null_term"},
'cstr_func_name': {'type': VarType.RELATIVE_ADDR_TO_PTR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.CHAR, 'array': "null_term"},
'dji_msg_mutex': {'type': VarType.RELATIVE_ADDR_TO_PTR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.STRUCT, 'struct': DummyStruct},
'msg_adjust_task_finished': {'type': VarType.RELATIVE_ADDR_TO_PTR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.UINT32_T},
'printk_log_level': {'type': VarType.RELATIVE_ADDR_TO_PTR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.UINT32_T},
'encrypt_query_fail_authority_level': {'type': VarType.DIRECT_INT_VALUE, 'variety': DataVariety.INT32_T,
'public': "og_hardcoded.p3x_ambarella", 'minValue': "0", 'maxValue': "2", 'defaultValue': "0",
'description': "AuthorityLevel established when SHA204 communication fail; 0-restricted,1-normal,2-superuser"},
'verify_state_good_authority_level': {'type': VarType.DIRECT_INT_VALUE, 'variety': DataVariety.INT32_T,
'public': "og_hardcoded.p3x_ambarella", 'minValue': "0", 'maxValue': "2", 'defaultValue': "1",
'description': "AuthorityLevel established when encryption keys match; 0-restricted,1-normal,2-superuser"},
'verify_state_bad_authority_level': {'type': VarType.DIRECT_INT_VALUE, 'variety': DataVariety.INT32_T,
'public': "og_hardcoded.p3x_ambarella", 'minValue': "0", 'maxValue': "2", 'defaultValue': "0",
'description': "AuthorityLevel established on encryption mismatch; 0-restricted,1-normal,2-superuser"},
'loc_label02': {'type': VarType.ABSOLUTE_ADDR_TO_CODE, 'variety': CodeVariety.CHUNK},
'loc_label03': {'type': VarType.ABSOLUTE_ADDR_TO_CODE, 'variety': CodeVariety.CHUNK},
'loc_label06': {'type': VarType.ABSOLUTE_ADDR_TO_CODE, 'variety': CodeVariety.CHUNK},
'loc_label09': {'type': VarType.ABSOLUTE_ADDR_TO_CODE, 'variety': CodeVariety.CHUNK},
'loc_label10': {'type': VarType.ABSOLUTE_ADDR_TO_CODE, 'variety': CodeVariety.CHUNK},
'loc_label11': {'type': VarType.ABSOLUTE_ADDR_TO_CODE, 'variety': CodeVariety.CHUNK},
'loc_label12': {'type': VarType.ABSOLUTE_ADDR_TO_CODE, 'variety': CodeVariety.CHUNK},
'loc_label13': {'type': VarType.ABSOLUTE_ADDR_TO_CODE, 'variety': CodeVariety.CHUNK},
'unk_offs01': {'type': VarType.DIRECT_INT_VALUE, 'variety': DataVariety.UINT32_T},
'unk_var01': {'type': VarType.RELATIVE_ADDR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.UNKNOWN},
'unk_var02': {'type': VarType.RELATIVE_ADDR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.UNKNOWN},
'unk_var03': {'type': VarType.RELATIVE_ADDR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.UNKNOWN},
'unk_var04': {'type': VarType.RELATIVE_ADDR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.UNKNOWN},
'unk_var05': {'type': VarType.RELATIVE_ADDR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.UNKNOWN},
'unk_var06': {'type': VarType.RELATIVE_ADDR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.UNKNOWN},
'unk_var07': {'type': VarType.RELATIVE_ADDR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.UNKNOWN},
'unk_var08': {'type': VarType.RELATIVE_ADDR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.UNKNOWN},
'unk_var09': {'type': VarType.RELATIVE_ADDR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.UNKNOWN},
'unk_var10': {'type': VarType.RELATIVE_ADDR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.UNKNOWN},
'unk_var11': {'type': VarType.RELATIVE_ADDR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.UNKNOWN},
'unk_var12': {'type': VarType.RELATIVE_ADDR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.UNKNOWN},
'unk_var13': {'type': VarType.RELATIVE_ADDR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.UNKNOWN},
'unk_var14': {'type': VarType.RELATIVE_ADDR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.UNKNOWN},
'unk_var15': {'type': VarType.RELATIVE_ADDR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.UNKNOWN},
'unk_var16': {'type': VarType.RELATIVE_ADDR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.UNKNOWN},
'unk_var17': {'type': VarType.RELATIVE_ADDR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.UNKNOWN},
'unk_var18': {'type': VarType.RELATIVE_ADDR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.UNKNOWN},
'unk_var19': {'type': VarType.RELATIVE_ADDR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.UNKNOWN},
'unk_var20': {'type': VarType.RELATIVE_ADDR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.UNKNOWN},
},
}
class AmbaP3XBitrateTableEntry(LittleEndianStructure):
_pack_ = 1
_fields_ = [('min', c_int),
('avg', c_int),
('max', c_int)]
re_func_DjiUstVideoQualitySetInner = {
'name': "DjiUstVideoQualitySetInner",
'version': "P3X_FW_V01.01",
're': """
DjiUstVideoQualitySetInner:
push {r4, r5, lr}
sub sp, sp, #0x14
movs r4, r0
ldr r0, \[r4\]
cmp r0, #0
beq #(?P<loc_label01>[0-9a-fx]+)
cmp r0, #2
beq #(?P<loc_label02>[0-9a-fx]+)
blo #(?P<loc_label03>[0-9a-fx]+)
b #(?P<loc_label04>[0-9a-fx]+)
loc_label01:
add r0, r2, r2, lsl #1
ldr r1, \[pc, #(?P<vid_setting_bitrates>[0-9a-fx]+)\]
ldr r0, \[r1, r0, lsl #2\]
loc_label06:
cmp r0, #0
beq #(?P<loc_label05>[0-9a-fx]+)
ldr r1, \[pc, #(?P<unk_var01>[0-9a-fx]+)\]
ldrsb r1, \[r1, #0x12\]
mov r2, #0x54
ldr r3, \[pc, #(?P<vid_settings_ust>[0-9a-fx]+)\]
smlabb r1, r1, r2, r3
str r0, \[r1, #8\]
loc_label05:
mov r0, #0
loc_label08:
add sp, sp, #0x14
pop {r4, r5, pc}
loc_label03:
add r0, r2, r2, lsl #1
ldr r1, \[pc, #(?P<vid_setting_bitrates>[0-9a-fx]+)\]
adds r0, r1, r0, lsl #2
ldr r0, \[r0, #4\]
b #(?P<loc_label06>[0-9a-fx]+)
loc_label02:
add r0, r2, r2, lsl #1
ldr r1, \[pc, #(?P<vid_setting_bitrates>[0-9a-fx]+)\]
adds r0, r1, r0, lsl #2
ldr r0, \[r0, #8\]
b #(?P<loc_label06>[0-9a-fx]+)
loc_label04:
ldr r0, \[pc, #(?P<printk_log_level>[0-9a-fx]+)\]
ldr r0, \[r0\]
cmp r0, #0
bmi #(?P<loc_label07>[0-9a-fx]+)
mov r5, #0
mov r0, #1
movs r5, r0
bl #(?P<AmbaPrintk_Disabled>[0-9a-fx]+)
cmp r0, #1
beq #(?P<loc_label07>[0-9a-fx]+)
ldr r0, \[r4\]
str r0, \[sp, #0x10\]
ldr r0, \[pc, #(?P<cstr_func_name>[0-9a-fx]+)\]
str r0, \[sp, #0xc\]
ldr r0, \[pc, #(?P<cstr_fmt_text1>[0-9a-fx]+)\]
str r0, \[sp, #8\]
str r5, \[sp, #4\]
mov r0, #0
str r0, \[sp\]
mov r3, #0
mov r2, #1
mov r1, #1
mov r0, #1
bl #(?P<AmbaPrintk>[0-9a-fx]+)
loc_label07:
mvn r0, #0
b #(?P<loc_label08>[0-9a-fx]+)
""",
'vars': {
'DjiUstVideoQualitySetInner': {'type': VarType.DIRECT_LINE_OF_CODE, 'variety': CodeVariety.FUNCTION},
'cstr_fmt_text1': {'type': VarType.RELATIVE_ADDR_TO_PTR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.CHAR, 'array': "null_term"},
'cstr_func_name': {'type': VarType.RELATIVE_ADDR_TO_PTR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.CHAR, 'array': "null_term"},
'AmbaPrintk_Disabled': {'type': VarType.ABSOLUTE_ADDR_TO_CODE, 'variety': CodeVariety.FUNCTION},
'AmbaPrintk': {'type': VarType.ABSOLUTE_ADDR_TO_CODE, 'variety': CodeVariety.FUNCTION},
'loc_label01': {'type': VarType.ABSOLUTE_ADDR_TO_CODE, 'variety': CodeVariety.CHUNK},
'loc_label02': {'type': VarType.ABSOLUTE_ADDR_TO_CODE, 'variety': CodeVariety.CHUNK},
'loc_label03': {'type': VarType.ABSOLUTE_ADDR_TO_CODE, 'variety': CodeVariety.CHUNK},
'loc_label04': {'type': VarType.ABSOLUTE_ADDR_TO_CODE, 'variety': CodeVariety.CHUNK},
'loc_label05': {'type': VarType.ABSOLUTE_ADDR_TO_CODE, 'variety': CodeVariety.CHUNK},
'loc_label06': {'type': VarType.ABSOLUTE_ADDR_TO_CODE, 'variety': CodeVariety.CHUNK},
'loc_label07': {'type': VarType.ABSOLUTE_ADDR_TO_CODE, 'variety': CodeVariety.CHUNK},
'loc_label08': {'type': VarType.ABSOLUTE_ADDR_TO_CODE, 'variety': CodeVariety.CHUNK},
'unk_var01': {'type': VarType.RELATIVE_ADDR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.UNKNOWN},
'vid_settings_ust': {'type': VarType.RELATIVE_ADDR_TO_PTR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.STRUCT, 'struct': DummyStruct},
'vid_setting_bitrates': {'type': VarType.RELATIVE_ADDR_TO_PTR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.STRUCT, 'array': 27,
'struct': AmbaP3XBitrateTableEntry,
'public': "og_hardcoded.p3x_ambarella", 'minValue': "1000000 1000000 1000000", 'maxValue': "64000000 64000000 64000000",
'description': "Bitrates used for h.264 video compression; 3 values: min, avg, max"},
'printk_log_level': {'type': VarType.RELATIVE_ADDR_TO_PTR_TO_GLOBAL_DATA, 'baseaddr': "PC+", 'variety': DataVariety.UINT32_T},
},
}
re_general_list = [
{'sect': ".text", 'func': re_func_DjiMsgSettingsInit,},
{'sect': ".text", 'func': re_func_DjiUstVideoQualitySetInner,},
]
def get_asm_arch_by_name(arname):
global elf_archs
for arch in elf_archs:
if arch['name'] == arname:
return arch.copy()
return None
def get_asm_mode_by_name(arch, mdname):
for mode in arch['modes']:
if mode['name'] == mdname:
return mode
return None
def elf_march_to_asm_config(elfobj, submode=None):
""" Retrieves machine architecture for given elf.
Returns config for capstone and keystone.
"""
march = elfobj.get_machine_arch()
asm_arch = None
asm_modes = []
if march == "x64":
asm_arch = get_asm_arch_by_name("x86")
asm_modes.append(get_asm_mode_by_name(asm_arch, "64b"))
elif march == "x86":
asm_arch = get_asm_arch_by_name("x86")
asm_modes.append(get_asm_mode_by_name(asm_arch, "32b"))
elif march == "ARM":
asm_arch = get_asm_arch_by_name("arm")
if elfobj.little_endian:
asm_modes.append(get_asm_mode_by_name(asm_arch, "le"))
else:
asm_modes.append(get_asm_mode_by_name(asm_arch, "be"))
elif march == "MIPS":
asm_arch = get_asm_arch_by_name("mips")
asm_modes.append(get_asm_mode_by_name(asm_arch, "32b"))
if elfobj.little_endian:
asm_modes.append(get_asm_mode_by_name(asm_arch, "le"))
else:
asm_modes.append(get_asm_mode_by_name(asm_arch, "be"))
if submode is not None:
asm_modes.append(get_asm_mode_by_name(asm_arch, submode))
return (asm_arch, asm_modes,)
def get_arm_vma_relative_to_pc_register(asm_arch, section, address, size, offset_str):
""" Gets Virtual Memory Address associated with offet given within an asm instruction.
ARMs have a way of storing relative offsets which may be confusing at first.
"""
alignment = asm_arch['boundary']
# In ARM THUMB mode, alignment is 4
if (asm_arch['name'] == "arm") and (alignment == 2):
alignment = 4
if isinstance(offset_str, int):
offset_int = offset_str
else:
offset_int = int(offset_str, 0)
address = address - (address % alignment)
vma = address + size + asm_arch['boundary'] + offset_int
return vma - (vma % alignment)
def get_arm_vma_subtracted_from_pc_register(asm_arch, section, address, size, offset_str):
""" Gets Virt Mem Addr associated to offset subtracted from PC reg within an asm instruction.
"""
alignment = asm_arch['boundary']
# In ARM THUMB mode, alignment is 4
if (asm_arch['name'] == "arm") and (alignment == 2):
alignment = 4
if isinstance(offset_str, int):
offset_int = offset_str
else:
offset_int = int(offset_str, 0)
address = address - (address % alignment)
vma = address + size - offset_int
return vma - (vma % asm_arch['boundary'])
def get_arm_offset_val_relative_to_pc_register(asm_arch, address, size, vma):
""" Gets offset associated with Virt Mem Addr given to place into asm instruction.
"""
offset_val = vma - address - size - asm_arch['boundary']
return offset_val
def get_section_and_offset_from_address(asm_arch, elf_sections, address):
""" Gets Virtual Memory Address associated with offset given within an asm instruction.
"""
for sect_name, sect in elf_sections.items():
offset = address - sect['addr']
if (offset >= 0) and (offset < len(sect['data'])):
return sect_name, offset
return None, None
def armfw_elf_generic_objdump(po, elffh, asm_submode=None):
""" Dump executable in similar manner to objdump disassemble function.
"""
elfobj = ELFFile(elffh)
asm_arch, asm_modes = elf_march_to_asm_config(elfobj, asm_submode)
if len(asm_modes) < 1 or not isinstance(asm_modes[0], collections.abc.Mapping):
raise ValueError("ELF has unsupported machine type ({:s}).".format(elfobj['e_machine']))
cs_mode = 0
retshift = 0
for mode in asm_modes:
cs_mode = cs_mode | mode['cs_const']
# check for mode specific overrides (only needed for THUMB atm)
if 'boundary' in mode:
asm_arch['boundary'] = mode['boundary']
if 'retshift' in mode:
retshift = mode['retshift']
cs = capstone.Cs(asm_arch['cs_const'], cs_mode)
# Get sections dictionary, so that we can easily access them by name
elf_sections = {}
for i in range(elfobj.num_sections()):
esection = elfobj.get_section(i)
if esection['sh_type'] != "SHT_PROGBITS":
continue
if not (esection['sh_flags'] & SH_FLAGS.SHF_ALLOC):
continue
if (po.verbose > 2):
print("{:s}: Found section {:s}".format(po.elffile, esection.name))
section = {
'index': i,
'name': esection.name,
'addr': esection['sh_addr'],
'data': esection.data(),
}
elf_sections[section.name] = section
if (esection['sh_flags'] & SH_FLAGS.SHF_EXECINSTR):
sect_offs = 0
while sect_offs < len(section['data']):
for (address, size, mnemonic, op_str) in cs.disasm_lite(section['data'][sect_offs:], section['addr']+sect_offs):
print("0x{:05x}:\t{:s}\t{:s}".format(address, mnemonic, op_str))
sect_offs += size
size = len(section['data']) - sect_offs
if size > asm_arch['boundary']:
size = asm_arch['boundary']
address = section['addr']+sect_offs
if size > 0:
print("0x{:05x}:\tdcb\t".format(address), end='')
for bt in section['data'][sect_offs:sect_offs+size]:
print("0x{:02x} ".format(bt), end='')
print("")
sect_offs += size
else:
sect_offs = 0
while sect_offs < len(section['data']):
size = len(section['data']) - sect_offs
if size > 4:
size = 4
address = section['addr']+sect_offs
if size > 0:
print("0x{:05x}:\tdcb\t".format(address), end='')
for bt in section['data'][sect_offs:sect_offs+size]:
print("0x{:02x} ".format(bt), end='')
print("")
sect_offs += size
return
def armfw_asm_search_strings_to_re_list(re_patterns):
""" Converts multiline regex string to a list of patterns.
"""
# Divide to lines
re_lines = re_patterns.split(sep="\n")
re_labels = {}
# Remove comments
re_lines = [s.split(";",1)[0] if ";" in s else s for s in re_lines]
# Remove labels
for i, s in enumerate(re_lines):
re_label = re.search(r'^([a-zA-Z0-9_]+):(.*)$', s)
if re_label is not None:
re_lines[i] = re_label.group(2)
re_labels[re_label.group(1)] = i
# Strip whitespaces
re_lines = list(map(str.strip, re_lines))
# Later empty lines will be removed; update re_labels accordingly
reduced_line = 0
for s in re_lines:
if s == "":
for lab_name, lab_line in re_labels.items():
if (lab_line > reduced_line):
re_labels[lab_name] = lab_line - 1
else:
reduced_line += 1
# Remove empty lines
return list(filter(None, re_lines)), re_labels
def armfw_elf_section_search_init(asm_arch, section, patterns):
""" Initialize search data.
"""
search = {}
search['asm_arch'] = asm_arch
search['section'] = section
search['name'] = patterns['name']
search['version'] = patterns['version']
re_lines, re_labels = armfw_asm_search_strings_to_re_list(patterns['re'])
search['re'] = re_lines
search['var_defs'] = patterns['vars'].copy()
for lab_name, lab_line in re_labels.items():
if lab_name in search['var_defs']:
var_def = search['var_defs'][lab_name]
var_def['line'] = lab_line
search['var_vals'] = {}
# Starting address of the current match
search['match_address'] = 0
# Binary size of each matched regex line
search['re_size'] = []
# Amount of lines already matched (aka current line)
search['match_lines'] = 0
search['best_match_address'] = 0
search['best_match_lines'] = 0
# List of datasets for full matches
search['full_matches'] = []
# Variant of the current variable length statement
search['varlen_inc'] = 0
# List of points where variable length lines were found
search['varlen_points'] = []
return search
def armfw_elf_section_search_reset(search):
""" Reset search data after matching failed.
"""
if search['best_match_lines'] < search['match_lines']:
search['best_match_address'] = search['match_address']
search['best_match_lines'] = search['match_lines']
search['var_vals'] = {}
search['match_address'] = 0
search['re_size'] = []
search['match_lines'] = 0
search['varlen_inc'] = 0
search['varlen_points'] = []
return search
def armfw_elf_section_search_varlen_point_mark(search, address, varlen_delta):
""" Add or update variable length point in given search results.
"""
# the search['match_address'], might be unset if we are matching first line;
# in that case, use address from func parameter
if search['match_lines'] < 1:
search['match_address'] = address
# do not change search['varlen_inc'], only the one which will be used
# if matching current one will fail
for varlen in search['varlen_points']:
if varlen['match_address'] != search['match_address']:
continue
if varlen['match_lines'] != search['match_lines']:
continue
if sum(varlen['re_size']) != sum(search['re_size']):
continue
# found pre-existing varlen point
varlen['varlen_delta'] = varlen_delta
if varlen_delta > 0:
varlen['varlen_inc'] += 1
return search
varlen = {}
varlen['var_vals'] = search['var_vals'].copy()
varlen['match_address'] = search['match_address'] # int value
varlen['re_size'] = search['re_size'].copy()
varlen['match_lines'] = search['match_lines'] # int value
varlen['varlen_inc'] = 1 # 0 is already being tested when this is added
varlen['varlen_delta'] = varlen_delta
search['varlen_points'].append(varlen)
return search
def armfw_elf_section_search_varlen_point_rewind(search):
""" Rewinds the search to last varlen entry which may be increased.
"""
if search['best_match_lines'] < search['match_lines']:
search['best_match_address'] = search['match_address']
search['best_match_lines'] = search['match_lines']
for varlen in reversed(search['varlen_points']):
if varlen['varlen_delta'] <= 0:
search['varlen_points'].pop()
continue
search['var_vals'] = varlen['var_vals'].copy()
search['match_address'] = varlen['match_address'] # int value
search['re_size'] = varlen['re_size'].copy()
search['match_lines'] = varlen['match_lines'] # int value
search['varlen_inc'] = varlen['varlen_inc']
return True
return False
def armfw_elf_section_search_progress(search, match_address, match_line_size):
""" Update search data after matching next line suceeded.
"""
search['match_lines'] += 1
if search['match_lines'] == 1:
search['match_address'] = match_address
search['re_size'] = []
search['varlen_inc'] = 0
search['re_size'].append(match_line_size)
if search['match_lines'] == len(search['re']):
search['full_matches'].append({
'address': search['match_address'],
're': search['re'],
're_size': search['re_size'],
'vars': search['var_vals'],
})
search['match_lines'] = 0
return search
def armfw_elf_section_search_print_unused_vars(search):
""" Show messages about unused variables defined in the regex.
To be used after a match is found.
"""
for var_name in search['var_defs']:
if var_name in search['var_vals']:
continue
var_val_found = False
# Handle vars with suffixes
for var_val_name in search['var_vals']:
if var_val_name.startswith(var_name+"_"):
var_val_found = True
break
if var_val_found:
continue
print("Variable '{:s}' defined but not used within matched regex".format(var_name))
def armfw_elf_section_search_get_pattern(search):
""" Get regex pattern to match with next line.
"""
re_patterns = search['re']
match_lines = search['match_lines']
return re_patterns[match_lines]
def armfw_elf_section_search_get_next_search_pos(search, sect_offs):
""" Get position to start a next search before resetting current one.
"""
# We intentionally clean 're_size' only on reset,
# so that it could be used here even after full match
asm_arch = search['asm_arch']
if len(search['re_size']) > 0:
new_offs = search['match_address'] - search['section']['addr'] + \
min(asm_arch['boundary'], search['re_size'][0])
return new_offs
else:
new_offs = sect_offs + asm_arch['boundary']
return new_offs - (new_offs % asm_arch['boundary'])
def variety_is_signed_int(var_variety):
return var_variety in (DataVariety.INT8_T, DataVariety.INT16_T, DataVariety.INT32_T, DataVariety.INT64_T,)