mirror of
https://github.com/mandiant/capa.git
synced 2025-12-14 16:40:44 -08:00
Compare commits
1423 Commits
arm-suppor
...
mr/library
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
304f835a1a | ||
|
|
1f7f24c467 | ||
|
|
f2c329b768 | ||
|
|
22368fbe6f | ||
|
|
6a12ab8598 | ||
|
|
a4fdb0a3ef | ||
|
|
c7bb8b8e67 | ||
|
|
41c5194693 | ||
|
|
8c8b67a6ea | ||
|
|
f0cc0fb2b8 | ||
|
|
fc8089c248 | ||
|
|
d795db9017 | ||
|
|
544e3eee5b | ||
|
|
dfc304d9f6 | ||
|
|
54688517c4 | ||
|
|
21fc77ea28 | ||
|
|
2976974009 | ||
|
|
030954d556 | ||
|
|
389a5eb84f | ||
|
|
6d3b96f0b0 | ||
|
|
2a13bf6c0b | ||
|
|
e9f4f5bc31 | ||
|
|
e7400be99a | ||
|
|
591a1e8fbb | ||
|
|
2f5a227fb0 | ||
|
|
931ff62421 | ||
|
|
3037307ee8 | ||
|
|
d6c1725d7e | ||
|
|
16eae70c17 | ||
|
|
9e7e6be374 | ||
|
|
3e8bed1db2 | ||
|
|
e4ac02a968 | ||
|
|
eff358980a | ||
|
|
108bd7f224 | ||
|
|
ab43c8c0c2 | ||
|
|
585dff8b48 | ||
|
|
cb09041387 | ||
|
|
80899f3f70 | ||
|
|
00d2bb06fd | ||
|
|
ff1043e976 | ||
|
|
51a4eb46b8 | ||
|
|
558bf0fbf2 | ||
|
|
76aff57467 | ||
|
|
f82fc1902c | ||
|
|
e9e8fe42ed | ||
|
|
80e007787c | ||
|
|
bfcc705117 | ||
|
|
834150ad1d | ||
|
|
31ec208a9b | ||
|
|
a5d9459c42 | ||
|
|
06271a88d4 | ||
|
|
c48bccf623 | ||
|
|
9975f769f9 | ||
|
|
c5d8f99d6f | ||
|
|
bcd57a9af1 | ||
|
|
12337be2b7 | ||
|
|
25c4902c21 | ||
|
|
f024e1d54c | ||
|
|
bab7ed9188 | ||
|
|
6eda8c9713 | ||
|
|
22e88c860f | ||
|
|
7884248022 | ||
|
|
4891fd750f | ||
|
|
783e14b949 | ||
|
|
74777ad23e | ||
|
|
01b35e7582 | ||
|
|
e29288cc8d | ||
|
|
c4c35ca6e9 | ||
|
|
3b1e0284c0 | ||
|
|
7b61d28dd2 | ||
|
|
e3267df5b1 | ||
|
|
9076e5475d | ||
|
|
d1d8badc2e | ||
|
|
84d2a18b52 | ||
|
|
954aeb0ce4 | ||
|
|
882a68bbd4 | ||
|
|
3d2d436d92 | ||
|
|
1c64001ed8 | ||
|
|
ab20366e2d | ||
|
|
ce3ba8ec3c | ||
|
|
fe6995a687 | ||
|
|
4d812f085f | ||
|
|
6c8791a541 | ||
|
|
25111f8a95 | ||
|
|
38fa7f0b80 | ||
|
|
6ebbd1db89 | ||
|
|
93fbdbb51f | ||
|
|
adb339419d | ||
|
|
25ca29573c | ||
|
|
f4f0347473 | ||
|
|
dc97f5abb5 | ||
|
|
8b22a7fca2 | ||
|
|
ee17d75be9 | ||
|
|
2fc0783faa | ||
|
|
e07ff1c76c | ||
|
|
f236afe2a6 | ||
|
|
9b64afab60 | ||
|
|
c9f5188c01 | ||
|
|
51d2ea147b | ||
|
|
7b101b33dc | ||
|
|
e70d5b3e27 | ||
|
|
529a5de534 | ||
|
|
9459251e12 | ||
|
|
113b2593fa | ||
|
|
80cae197d1 | ||
|
|
923132b9b7 | ||
|
|
363e70f523 | ||
|
|
eab3ff8726 | ||
|
|
f1453eac59 | ||
|
|
44e6594a1c | ||
|
|
a4e81540d1 | ||
|
|
68e07fbb9a | ||
|
|
729a1a85b7 | ||
|
|
db4798aaf6 | ||
|
|
ce62fecbea | ||
|
|
138c7014e5 | ||
|
|
9d8401a9a7 | ||
|
|
0db53e5086 | ||
|
|
3223d3f24f | ||
|
|
b1a79fba9d | ||
|
|
770fefbba8 | ||
|
|
3108ac0928 | ||
|
|
7e7d511201 | ||
|
|
6d6c245241 | ||
|
|
fa92cfd43d | ||
|
|
ed5dd38e7e | ||
|
|
b4f60eca64 | ||
|
|
e46811685d | ||
|
|
6ce130e6da | ||
|
|
a380609514 | ||
|
|
e71f90c618 | ||
|
|
9eab7eb143 | ||
|
|
e8550f242c | ||
|
|
d98c315eb4 | ||
|
|
a779cf2a28 | ||
|
|
a5c14c32b8 | ||
|
|
88a632c2d4 | ||
|
|
89443742cd | ||
|
|
1ffee81cea | ||
|
|
6c883f37a8 | ||
|
|
dcc74eb07a | ||
|
|
0a6bc20eed | ||
|
|
df3c265bd5 | ||
|
|
73120a5c0b | ||
|
|
a0ed2127f9 | ||
|
|
4df8b2b7ed | ||
|
|
68a38b6e6f | ||
|
|
a33f67b48e | ||
|
|
f2ed09861e | ||
|
|
5b583bdf35 | ||
|
|
9959eb6bae | ||
|
|
c3f24c2f48 | ||
|
|
2c41d3ce89 | ||
|
|
980814f7df | ||
|
|
6049062173 | ||
|
|
05083cfb6e | ||
|
|
0bdfb37287 | ||
|
|
5f5393af69 | ||
|
|
5c1c1b0ba9 | ||
|
|
8fd90883b4 | ||
|
|
22d20ed2b8 | ||
|
|
b3dd76adff | ||
|
|
f6b7582606 | ||
|
|
791f5e2359 | ||
|
|
c4c35e914d | ||
|
|
1593779d6b | ||
|
|
5c6faaefff | ||
|
|
864cd77f9f | ||
|
|
164e075ca9 | ||
|
|
7592cfe268 | ||
|
|
6a2039e7a6 | ||
|
|
0e4872507d | ||
|
|
dd6cb4acc3 | ||
|
|
7e766048fa | ||
|
|
7c26490caa | ||
|
|
c409b2b7ed | ||
|
|
6ff08aeeaf | ||
|
|
4501955728 | ||
|
|
6b4591de14 | ||
|
|
00cce585d6 | ||
|
|
19e2097f79 | ||
|
|
b67bd4d084 | ||
|
|
854759cb43 | ||
|
|
348e0b3203 | ||
|
|
03e2195582 | ||
|
|
076bb13e2d | ||
|
|
76bd1460ba | ||
|
|
14a7bab890 | ||
|
|
8ca88d94d5 | ||
|
|
9d3f732b33 | ||
|
|
d3e3c966d6 | ||
|
|
e402aab41d | ||
|
|
c73abb8855 | ||
|
|
04071606cd | ||
|
|
19698b1ba1 | ||
|
|
25e9e18097 | ||
|
|
3a21648e78 | ||
|
|
8dcb7a473e | ||
|
|
cf91503dc3 | ||
|
|
d8691edd15 | ||
|
|
56a6f9c83e | ||
|
|
e25e68e169 | ||
|
|
728742a1ad | ||
|
|
da273824d1 | ||
|
|
7a6f63cf2b | ||
|
|
d62734ecc2 | ||
|
|
5ccb642929 | ||
|
|
8d5fcdf287 | ||
|
|
be8499238c | ||
|
|
40c7714c48 | ||
|
|
460590cec0 | ||
|
|
25d2ef30e7 | ||
|
|
71ae51ef69 | ||
|
|
216bfb968d | ||
|
|
32cb0365f8 | ||
|
|
b299e4bc1f | ||
|
|
bc2802fd72 | ||
|
|
81a14838bd | ||
|
|
1c9a86ca20 | ||
|
|
32fefa60cc | ||
|
|
09bbe80dfb | ||
|
|
239ad4a17e | ||
|
|
ab3b074c6a | ||
|
|
e863ce5ff3 | ||
|
|
8e4c0e3040 | ||
|
|
401a0ee0ff | ||
|
|
f69fabc2b0 | ||
|
|
c0a7f765c5 | ||
|
|
87f691677c | ||
|
|
ea9853e667 | ||
|
|
312dd0d40f | ||
|
|
44cbe664e4 | ||
|
|
6b8e2b3e81 | ||
|
|
ba9ab7c876 | ||
|
|
1af97f6681 | ||
|
|
05575e1e92 | ||
|
|
9d137a207f | ||
|
|
850ae5a916 | ||
|
|
e8054c277d | ||
|
|
e8ea461456 | ||
|
|
bb8991af8e | ||
|
|
368f635387 | ||
|
|
287e4282a9 | ||
|
|
1f6ce48e40 | ||
|
|
7cb31cf23c | ||
|
|
01e6619182 | ||
|
|
20d7bf1402 | ||
|
|
6b8983c0c4 | ||
|
|
97bd4992b1 | ||
|
|
843fd34737 | ||
|
|
dfc19d8cb2 | ||
|
|
1564f24330 | ||
|
|
0d87bb0504 | ||
|
|
db423d9b0a | ||
|
|
ebfba543e6 | ||
|
|
46c464282e | ||
|
|
aa225dac5c | ||
|
|
c2376eaf7b | ||
|
|
6451fa433b | ||
|
|
765c7cb792 | ||
|
|
b675c9a77c | ||
|
|
ac081336ba | ||
|
|
a15eb835f4 | ||
|
|
fcdaabf34e | ||
|
|
283aa27152 | ||
|
|
f856ea7454 | ||
|
|
ebb778ae0d | ||
|
|
e9e5d2bb12 | ||
|
|
bb1ef6ca56 | ||
|
|
7e64306f1c | ||
|
|
6b19e7b372 | ||
|
|
bb60099ab6 | ||
|
|
d609203fcd | ||
|
|
fcf200f13f | ||
|
|
7cb93c8ebd | ||
|
|
eb69b383a4 | ||
|
|
04d127f69f | ||
|
|
9dd39926d7 | ||
|
|
13d14f6cb6 | ||
|
|
260da8ed2c | ||
|
|
a6884db1d3 | ||
|
|
67d3916c41 | ||
|
|
b0ffc86399 | ||
|
|
07b4e1f8a2 | ||
|
|
4137923c2e | ||
|
|
33be4d1f8e | ||
|
|
8e9eadf98a | ||
|
|
9107819cf1 | ||
|
|
b74738adcf | ||
|
|
b229048b51 | ||
|
|
afb72867f4 | ||
|
|
4fe7f784e9 | ||
|
|
b7b8792f70 | ||
|
|
e47635455e | ||
|
|
e83f289c8e | ||
|
|
3982356945 | ||
|
|
e637e5a09e | ||
|
|
0ea6f1e270 | ||
|
|
f6bc42540c | ||
|
|
a8d849e872 | ||
|
|
62701a2837 | ||
|
|
f60e3fc531 | ||
|
|
b6f0ee539b | ||
|
|
e70e1b0641 | ||
|
|
71c515d4d7 | ||
|
|
139dcc430c | ||
|
|
7bf0b396ee | ||
|
|
87dfa50996 | ||
|
|
8cba23bbce | ||
|
|
1a3cf4aa8e | ||
|
|
51b853de59 | ||
|
|
3043fd6ac8 | ||
|
|
b9c4cc681b | ||
|
|
13261d0c41 | ||
|
|
8476aeee35 | ||
|
|
38cf1f1041 | ||
|
|
d81b123e97 | ||
|
|
029259b8ed | ||
|
|
e3f695b947 | ||
|
|
d25c86c08b | ||
|
|
b967213302 | ||
|
|
05fb8f658f | ||
|
|
7b3812ae19 | ||
|
|
5b7a2be652 | ||
|
|
4aad53c5b3 | ||
|
|
b8d3d77829 | ||
|
|
9a1364c21c | ||
|
|
6e146bb126 | ||
|
|
85373a7ddb | ||
|
|
f6d12bcb41 | ||
|
|
f471386456 | ||
|
|
0028da5270 | ||
|
|
cf3494d427 | ||
|
|
3f33b82ace | ||
|
|
12f1851ba5 | ||
|
|
6da0e5d985 | ||
|
|
e2e84f7f50 | ||
|
|
106c31735e | ||
|
|
277e9d1551 | ||
|
|
9db01e340c | ||
|
|
626ea51c20 | ||
|
|
31e53fab20 | ||
|
|
cbdc7446aa | ||
|
|
46b68d11b7 | ||
|
|
fd686ac591 | ||
|
|
17aab2c4fc | ||
|
|
216ac8dd96 | ||
|
|
d68e057439 | ||
|
|
3c2749734c | ||
|
|
5c60efa81f | ||
|
|
09d86245e5 | ||
|
|
2862cb35c2 | ||
|
|
c3aa306d6c | ||
|
|
6bec5d40bd | ||
|
|
3b94961133 | ||
|
|
6ef485f67b | ||
|
|
4dfc53a58f | ||
|
|
98939f8a8f | ||
|
|
4490097e11 | ||
|
|
2ba2a2b013 | ||
|
|
28792ec6a6 | ||
|
|
658927c103 | ||
|
|
673f7cccfc | ||
|
|
6e0dc83451 | ||
|
|
da6c6cfb48 | ||
|
|
8bf0d16fd8 | ||
|
|
24a31a8bc3 | ||
|
|
6f7cc7cdb0 | ||
|
|
64a09d3146 | ||
|
|
998537ddf8 | ||
|
|
5afea29473 | ||
|
|
fd7bd94b48 | ||
|
|
330c77a32a | ||
|
|
19a6f3ad49 | ||
|
|
100df45cc0 | ||
|
|
cc87ef39d5 | ||
|
|
ec7e43193e | ||
|
|
b68a91e10b | ||
|
|
15889749c0 | ||
|
|
9353e46615 | ||
|
|
af26bef611 | ||
|
|
42fddfbf31 | ||
|
|
5214675eeb | ||
|
|
4f2467cae0 | ||
|
|
28c278b9e6 | ||
|
|
26b5870ef4 | ||
|
|
1f5b6ec52c | ||
|
|
307b0cc327 | ||
|
|
253d70efac | ||
|
|
85632f698f | ||
|
|
931a9b9421 | ||
|
|
06631fc39d | ||
|
|
4bbe9e1ce9 | ||
|
|
e2f5eb7d30 | ||
|
|
5b7a0cad5f | ||
|
|
da0545780b | ||
|
|
bcdaa80dfa | ||
|
|
aad4854a61 | ||
|
|
cbf6ecbd4d | ||
|
|
81581fe85e | ||
|
|
194017bce3 | ||
|
|
76913af20b | ||
|
|
d1f6bb3a44 | ||
|
|
bb86d1485c | ||
|
|
cd3086cfa4 | ||
|
|
120f34e8ef | ||
|
|
5495a8555c | ||
|
|
1a447013bd | ||
|
|
fccb533841 | ||
|
|
3b165c3d8e | ||
|
|
cd5199f873 | ||
|
|
202b5ddae7 | ||
|
|
0b70abca93 | ||
|
|
6de22a0264 | ||
|
|
fd811d1387 | ||
|
|
b617179525 | ||
|
|
28fc671ad5 | ||
|
|
e1b750f1e9 | ||
|
|
1ec680856d | ||
|
|
d79ea074f2 | ||
|
|
e68bcddfe0 | ||
|
|
4929d5936e | ||
|
|
9be35f9a8d | ||
|
|
ec6c9c93bd | ||
|
|
9df611ff13 | ||
|
|
29fa3153b1 | ||
|
|
4b08e62750 | ||
|
|
544899a04e | ||
|
|
9ef705a9ac | ||
|
|
19502efff3 | ||
|
|
ec21f3b3fc | ||
|
|
5be68d0751 | ||
|
|
8757dad054 | ||
|
|
0c9d3d09af | ||
|
|
740c739356 | ||
|
|
d256cc867f | ||
|
|
fbdfea1edc | ||
|
|
453a640de9 | ||
|
|
d10b396300 | ||
|
|
a544aed552 | ||
|
|
a1a171221f | ||
|
|
21887d1ec6 | ||
|
|
789332ec88 | ||
|
|
85a85e99bf | ||
|
|
574d61ad8f | ||
|
|
3cca80860d | ||
|
|
2b70086467 | ||
|
|
d26a806647 | ||
|
|
e5fa800ffb | ||
|
|
be274d1d65 | ||
|
|
b3ebf80d9b | ||
|
|
8f32b7fc65 | ||
|
|
f3d69529b0 | ||
|
|
1975b6455c | ||
|
|
51656fe825 | ||
|
|
1360e08389 | ||
|
|
40061b3c42 | ||
|
|
45fca7adea | ||
|
|
654804878f | ||
|
|
8b913e0544 | ||
|
|
482686ab81 | ||
|
|
67f8c4d28c | ||
|
|
3f151a342b | ||
|
|
00cb7924e1 | ||
|
|
7e079d4d35 | ||
|
|
346a0693ad | ||
|
|
8d3f032434 | ||
|
|
7d0ac71353 | ||
|
|
970b184651 | ||
|
|
ca02b4ac7c | ||
|
|
a797405648 | ||
|
|
a9dafe283c | ||
|
|
e87e8484b6 | ||
|
|
8726de0d65 | ||
|
|
7d1512a3de | ||
|
|
73d76d7aba | ||
|
|
1febb224d1 | ||
|
|
e3ea60d354 | ||
|
|
93cd1dcedd | ||
|
|
7b0270980d | ||
|
|
cce7774705 | ||
|
|
9ec9a6f439 | ||
|
|
97a3fba2c9 | ||
|
|
893352756f | ||
|
|
0cc06aa83d | ||
|
|
bdc94c13ac | ||
|
|
1888d0e7e3 | ||
|
|
52e24e560b | ||
|
|
c97d2d7244 | ||
|
|
833ec47170 | ||
|
|
07ae30875c | ||
|
|
3141e940de | ||
|
|
76a4a5899f | ||
|
|
4d81b7ab98 | ||
|
|
b068890fa6 | ||
|
|
d10d2820b2 | ||
|
|
5239e40beb | ||
|
|
bce8f7b5e5 | ||
|
|
0cf9365816 | ||
|
|
30d23c4d97 | ||
|
|
b3ed42f5f9 | ||
|
|
508a09ef25 | ||
|
|
e517d7dd77 | ||
|
|
142b84f9c5 | ||
|
|
72607c6ae5 | ||
|
|
2fd01835dc | ||
|
|
80600f59c7 | ||
|
|
1ec1185850 | ||
|
|
22e12928a6 | ||
|
|
8ad74ddbb6 | ||
|
|
2c1d5592ca | ||
|
|
267f5e99b7 | ||
|
|
6b77c50ae8 | ||
|
|
8a0a24f269 | ||
|
|
4f2494dc59 | ||
|
|
2e5da3e2bd | ||
|
|
0ac21f036c | ||
|
|
4ecf3a1793 | ||
|
|
b14db68819 | ||
|
|
54106d60ae | ||
|
|
0622f45208 | ||
|
|
adb9de8d4b | ||
|
|
48dd64beba | ||
|
|
abaabae164 | ||
|
|
8316a74ca2 | ||
|
|
1dd2af7048 | ||
|
|
bbc4e5cd97 | ||
|
|
7da3ef89ca | ||
|
|
44e319a604 | ||
|
|
21c346d0c2 | ||
|
|
f9953d1e99 | ||
|
|
9bce98b0ae | ||
|
|
7f39a5b1d6 | ||
|
|
e9cc193dd4 | ||
|
|
5482021c75 | ||
|
|
5507991575 | ||
|
|
65114ec2d7 | ||
|
|
e4ae052f48 | ||
|
|
3ae8183a4a | ||
|
|
b59df659c9 | ||
|
|
519cfb842e | ||
|
|
ee98548bf9 | ||
|
|
8298347c19 | ||
|
|
54d749e845 | ||
|
|
25b9c88198 | ||
|
|
11ae44541b | ||
|
|
f26a109b4d | ||
|
|
d26897afca | ||
|
|
6869ef6520 | ||
|
|
4fbd2ba2b8 | ||
|
|
283ce41a5e | ||
|
|
4b1a5003df | ||
|
|
1cd0f44115 | ||
|
|
824e852184 | ||
|
|
4be0c40fe6 | ||
|
|
4f4adc04c8 | ||
|
|
60d400cf08 | ||
|
|
2f4d8e1d90 | ||
|
|
fdfa838a15 | ||
|
|
baef70d588 | ||
|
|
e24773436e | ||
|
|
a4a4016463 | ||
|
|
30535cb623 | ||
|
|
2355603340 | ||
|
|
9a23e6837d | ||
|
|
0488c86bc7 | ||
|
|
b4092980e3 | ||
|
|
18bdf23f03 | ||
|
|
ac6e9f8aae | ||
|
|
abb6d01c1d | ||
|
|
984c1b2d39 | ||
|
|
e3dcbbb386 | ||
|
|
a8f382ebe8 | ||
|
|
4fb10780ec | ||
|
|
efc7540aa6 | ||
|
|
f1c4ff8e17 | ||
|
|
f44b4ebebd | ||
|
|
19000409df | ||
|
|
42849573b3 | ||
|
|
c02440f4b7 | ||
|
|
676f98acc8 | ||
|
|
e3a9c75316 | ||
|
|
2a54689cc6 | ||
|
|
cd11787bd8 | ||
|
|
9171dc2dad | ||
|
|
c695b37b0e | ||
|
|
e1d0ba22c7 | ||
|
|
7debc54dbd | ||
|
|
7b50065fea | ||
|
|
37306af37a | ||
|
|
c03405c29f | ||
|
|
8fe8981570 | ||
|
|
463f2f1d62 | ||
|
|
9a5f4562b8 | ||
|
|
7bc298de1a | ||
|
|
cbadab8521 | ||
|
|
0eaf055a46 | ||
|
|
0eb4291b25 | ||
|
|
9d1f110d24 | ||
|
|
0f0a23946b | ||
|
|
5b2122a3c6 | ||
|
|
49231366f1 | ||
|
|
10a4381ad5 | ||
|
|
7707984237 | ||
|
|
f6b0673b0f | ||
|
|
1c1e5c02b0 | ||
|
|
fe13f9ce76 | ||
|
|
04e3f268f3 | ||
|
|
12234c3572 | ||
|
|
92cfc0caa7 | ||
|
|
58e4a30156 | ||
|
|
bf4695c6bf | ||
|
|
d63c6f1f9e | ||
|
|
08b3ae60d7 | ||
|
|
f5893d7bd3 | ||
|
|
3a90247e5b | ||
|
|
bb0dff0610 | ||
|
|
610a86e5e2 | ||
|
|
cabb9c0975 | ||
|
|
c28f4fc890 | ||
|
|
9a449b6bd9 | ||
|
|
65b5c46029 | ||
|
|
8857511e55 | ||
|
|
ffcabf1e0b | ||
|
|
c6b43d7492 | ||
|
|
8af3a19d61 | ||
|
|
2252e69eed | ||
|
|
5e85fc9ede | ||
|
|
4e529d5c1f | ||
|
|
0f9dd9095b | ||
|
|
b163f82a71 | ||
|
|
bd3cc18a25 | ||
|
|
4e2f175b9f | ||
|
|
fdd097a141 | ||
|
|
1b4e5258f8 | ||
|
|
1d78900862 | ||
|
|
8807d6844d | ||
|
|
318a3d1610 | ||
|
|
b86b66a29c | ||
|
|
c263670a21 | ||
|
|
fc840d8e7d | ||
|
|
b751a7bba3 | ||
|
|
c8765a4116 | ||
|
|
4955a23c52 | ||
|
|
16814c376f | ||
|
|
05fb1a5c00 | ||
|
|
df8056f415 | ||
|
|
fde1de3250 | ||
|
|
7ab8dbbd4e | ||
|
|
2ddb6b0773 | ||
|
|
5fd532845c | ||
|
|
2a59284621 | ||
|
|
9adb669921 | ||
|
|
034894330b | ||
|
|
a3a8e36911 | ||
|
|
2c93c5fc83 | ||
|
|
9929967634 | ||
|
|
3436aab3fd | ||
|
|
9a76558fdf | ||
|
|
2e5761a414 | ||
|
|
2f2d4a1d6b | ||
|
|
1a4f2559fa | ||
|
|
66c2f07ca8 | ||
|
|
75800b9d2e | ||
|
|
bae4091661 | ||
|
|
ba044a980f | ||
|
|
2e7642ef8a | ||
|
|
3e4479e3bb | ||
|
|
437732174b | ||
|
|
f845382471 | ||
|
|
06aa3f6528 | ||
|
|
45ebc3e3d6 | ||
|
|
c3301d3b3f | ||
|
|
d2e1a47192 | ||
|
|
85e1495fed | ||
|
|
35ec5511e4 | ||
|
|
009cf0c854 | ||
|
|
96f68620ca | ||
|
|
0676e80c20 | ||
|
|
1c89d01982 | ||
|
|
692aba1b1d | ||
|
|
7e0cd565fd | ||
|
|
be97d68182 | ||
|
|
f9bceaa3d7 | ||
|
|
597f449bfa | ||
|
|
b032eec993 | ||
|
|
1a44e899cb | ||
|
|
734bfd4ad2 | ||
|
|
12b628318d | ||
|
|
be30117030 | ||
|
|
6b41e02d63 | ||
|
|
d2ca130060 | ||
|
|
50dcf7ca20 | ||
|
|
9bc04ec612 | ||
|
|
966976d97c | ||
|
|
05d7083890 | ||
|
|
1dc72a3183 | ||
|
|
efc26be196 | ||
|
|
f3bc132565 | ||
|
|
ad46b33bb7 | ||
|
|
9e5cc07a48 | ||
|
|
f4fecf43bf | ||
|
|
7426574741 | ||
|
|
9ab7a24153 | ||
|
|
f37b598010 | ||
|
|
5ca59634f3 | ||
|
|
42c1a307f3 | ||
|
|
ef5063171b | ||
|
|
7584e4a5e6 | ||
|
|
62474c764a | ||
|
|
1fc26b4f27 | ||
|
|
037a97381c | ||
|
|
ef65f14260 | ||
|
|
3214ecf0ee | ||
|
|
23c5e6797f | ||
|
|
e940890c29 | ||
|
|
21b76fc91e | ||
|
|
05ef952129 | ||
|
|
22f4251ad6 | ||
|
|
92478d2469 | ||
|
|
2aaba6ef16 | ||
|
|
8120fb796e | ||
|
|
f3c38ae300 | ||
|
|
bf56ee0311 | ||
|
|
4a84660e76 | ||
|
|
382c20cd58 | ||
|
|
2dbac05716 | ||
|
|
3f449f3c0f | ||
|
|
51b63b465b | ||
|
|
afb3426e96 | ||
|
|
1d3ae1f216 | ||
|
|
f229c8ecb8 | ||
|
|
e3da2d88d0 | ||
|
|
e4eb4340b1 | ||
|
|
a8e7611252 | ||
|
|
8531acd7c5 | ||
|
|
d6f7d2180f | ||
|
|
d1b213aaac | ||
|
|
51ddadbc87 | ||
|
|
cd52b1937b | ||
|
|
ca14dab804 | ||
|
|
fbe0440361 | ||
|
|
4c3586b5e9 | ||
|
|
47019e4d7c | ||
|
|
a236a952bc | ||
|
|
73ea822123 | ||
|
|
3c159a1f52 | ||
|
|
7db40c3af8 | ||
|
|
9a996d07c7 | ||
|
|
93cfb6ef8c | ||
|
|
a29c320f95 | ||
|
|
277d7e0687 | ||
|
|
e66c2efcf5 | ||
|
|
583f8b5688 | ||
|
|
b4c6bf859e | ||
|
|
ba9da0dd82 | ||
|
|
92770dd5c7 | ||
|
|
8946cb633e | ||
|
|
8f0eb5676e | ||
|
|
cb1a037502 | ||
|
|
c8d0071443 | ||
|
|
e6b8a3e505 | ||
|
|
f328df1bc4 | ||
|
|
d1aa1557b2 | ||
|
|
a0929124ec | ||
|
|
84ed6c8d24 | ||
|
|
61c8e30f65 | ||
|
|
6a4994f1ef | ||
|
|
fce105060d | ||
|
|
d84457eac7 | ||
|
|
890c879e7c | ||
|
|
f201ef1d22 | ||
|
|
f763d14266 | ||
|
|
6f0be06f86 | ||
|
|
347687579c | ||
|
|
d61d1dc591 | ||
|
|
235a3bede0 | ||
|
|
cf35d2c497 | ||
|
|
f6048b9e99 | ||
|
|
9d1e60d4a2 | ||
|
|
fb1235d26f | ||
|
|
3fe2328bd2 | ||
|
|
647abb669f | ||
|
|
a5e1eca8cc | ||
|
|
fdb96709ae | ||
|
|
490271e50b | ||
|
|
a870c92a2f | ||
|
|
de5f08871e | ||
|
|
2f60ec03af | ||
|
|
987eb2d358 | ||
|
|
6e3fff4bae | ||
|
|
a705bf9eab | ||
|
|
c68c68d5cb | ||
|
|
82013f0e24 | ||
|
|
210a13d94e | ||
|
|
0d5ff45c76 | ||
|
|
11b98cb0b1 | ||
|
|
3c9ab63521 | ||
|
|
a2fde921aa | ||
|
|
d4f7c77be8 | ||
|
|
f0f95824ac | ||
|
|
0ba5c23847 | ||
|
|
dee0aa73eb | ||
|
|
41a397661f | ||
|
|
52997e70a0 | ||
|
|
1acc2d1959 | ||
|
|
74f70856a6 | ||
|
|
e5b7ee96fc | ||
|
|
92d43f5327 | ||
|
|
48abd297a8 | ||
|
|
d64a10a287 | ||
|
|
abf83fe8cf | ||
|
|
6380d936ae | ||
|
|
18ab8d28d9 | ||
|
|
a52af3895a | ||
|
|
5d31bc462b | ||
|
|
7678897334 | ||
|
|
75ff58edaa | ||
|
|
eb12ec43f0 | ||
|
|
f7c72cd1c3 | ||
|
|
0da614aa4f | ||
|
|
9c81ccf88a | ||
|
|
c141f7ec6e | ||
|
|
274a710bb1 | ||
|
|
4a7e488e4c | ||
|
|
348120dea9 | ||
|
|
435eea1b80 | ||
|
|
621d42a093 | ||
|
|
15701c6d12 | ||
|
|
ec7fc86dc5 | ||
|
|
8d55c2f249 | ||
|
|
66607f1412 | ||
|
|
0097822e51 | ||
|
|
e559cc27d5 | ||
|
|
a0cec3f07d | ||
|
|
874faf0901 | ||
|
|
4750913fad | ||
|
|
e7198b2aaf | ||
|
|
426931c392 | ||
|
|
fec1e6a947 | ||
|
|
db53424548 | ||
|
|
8029fed31c | ||
|
|
3572b512d9 | ||
|
|
ab06c94d80 | ||
|
|
9e6919f33c | ||
|
|
99042f232d | ||
|
|
393b0e63f0 | ||
|
|
ee4f02908c | ||
|
|
c9df78252a | ||
|
|
788251ba2b | ||
|
|
62d4b008c5 | ||
|
|
be6f87318e | ||
|
|
aae72667a3 | ||
|
|
d6c5d98b0d | ||
|
|
d5ae2ffd91 | ||
|
|
96fb204d9d | ||
|
|
20604c4b41 | ||
|
|
423d942bd0 | ||
|
|
f9b87417e6 | ||
|
|
fc4618e234 | ||
|
|
1143f2ba56 | ||
|
|
10dc4b92b1 | ||
|
|
bfecf414fb | ||
|
|
0231ceef87 | ||
|
|
0ae8f34aff | ||
|
|
b8b55f4e19 | ||
|
|
d42829d7e7 | ||
|
|
c724a4b311 | ||
|
|
84e22b187d | ||
|
|
b6a0d6e1f3 | ||
|
|
1cb3ca61cd | ||
|
|
288313a300 | ||
|
|
2cc6a37713 | ||
|
|
fbeb33a91f | ||
|
|
3519125e03 | ||
|
|
98360328f9 | ||
|
|
3d4facd9a3 | ||
|
|
8b0ba1e656 | ||
|
|
7bc3fba7b0 | ||
|
|
d5e187bc70 | ||
|
|
85610a82c5 | ||
|
|
f2011c162c | ||
|
|
37caeb2736 | ||
|
|
5c48f38208 | ||
|
|
8687c740d5 | ||
|
|
9609d63f8a | ||
|
|
772f806eb6 | ||
|
|
5eaba611d1 | ||
|
|
b6f13f3489 | ||
|
|
178cfce456 | ||
|
|
94cf53a1e3 | ||
|
|
2cfd45022a | ||
|
|
26a2d1b4d1 | ||
|
|
6dbd3768ce | ||
|
|
21f9e0736d | ||
|
|
7cd5aa1c40 | ||
|
|
55e4fddc51 | ||
|
|
1aac4a1a69 | ||
|
|
92daf3a530 | ||
|
|
547502051f | ||
|
|
884b714be2 | ||
|
|
7205bc26ef | ||
|
|
e1b3a3f6b4 | ||
|
|
cb5fa36fc8 | ||
|
|
8ee97acf2a | ||
|
|
44d05f9498 | ||
|
|
bf233c1c7a | ||
|
|
182a9868ca | ||
|
|
40d9587fa4 | ||
|
|
430fdb074b | ||
|
|
0324d24490 | ||
|
|
41c286d1a3 | ||
|
|
187cf40d6f | ||
|
|
c37a0e525c | ||
|
|
de0c35b6ad | ||
|
|
d99b454c0e | ||
|
|
44f156925a | ||
|
|
599c115767 | ||
|
|
6ecc9b77b9 | ||
|
|
412d296d6b | ||
|
|
db32d90480 | ||
|
|
9a66c265db | ||
|
|
a1aca3aeb3 | ||
|
|
ffe6ab6842 | ||
|
|
d1b7afbe13 | ||
|
|
77de088ac9 | ||
|
|
40ba6679f0 | ||
|
|
8b6fa35e9f | ||
|
|
f85ea915bf | ||
|
|
312ad48041 | ||
|
|
65b80d4d13 | ||
|
|
fb098fde5f | ||
|
|
eedec933c2 | ||
|
|
559f2fd162 | ||
|
|
953b2e82d2 | ||
|
|
cd268d6327 | ||
|
|
23ecb248a5 | ||
|
|
bc165331db | ||
|
|
5d66a389d3 | ||
|
|
248a51c15f | ||
|
|
8a0628f357 | ||
|
|
2ec87f717a | ||
|
|
4430fce314 | ||
|
|
174c8121ca | ||
|
|
fa1371cfa8 | ||
|
|
a0a2b07b85 | ||
|
|
a9daa92c9a | ||
|
|
b315aacd73 | ||
|
|
3dd051582a | ||
|
|
5f7b4fbf74 | ||
|
|
8b287c1704 | ||
|
|
28a722d4c3 | ||
|
|
35f64f37bb | ||
|
|
7d9ae57692 | ||
|
|
838205b375 | ||
|
|
0fbec49708 | ||
|
|
0bdc727dce | ||
|
|
8ea7708a38 | ||
|
|
c6c54c316f | ||
|
|
8331ed6ea0 | ||
|
|
72e836166f | ||
|
|
d64ab41dfd | ||
|
|
5b4c167489 | ||
|
|
2a757b0cbb | ||
|
|
69836a0f13 | ||
|
|
866c7c5ce4 | ||
|
|
3725618d50 | ||
|
|
766b05e5c3 | ||
|
|
dd0eadb438 | ||
|
|
f905ed611b | ||
|
|
cfa703eaae | ||
|
|
9ec1bf3e42 | ||
|
|
d83c0e70de | ||
|
|
1d8e650d7b | ||
|
|
99caa87a3d | ||
|
|
6317153ef0 | ||
|
|
24dad6bcc4 | ||
|
|
73c158ad68 | ||
|
|
47330e69d4 | ||
|
|
0987673bf3 | ||
|
|
2c75f786c3 | ||
|
|
09afcfbac1 | ||
|
|
ab3747e448 | ||
|
|
9dc457e61e | ||
|
|
9eb88e6ca7 | ||
|
|
214a355b9c | ||
|
|
4d538b939e | ||
|
|
8c9e676868 | ||
|
|
b0133f0aa1 | ||
|
|
49adecb25c | ||
|
|
e9a9b3a6b6 | ||
|
|
d5daa79547 | ||
|
|
90df85b332 | ||
|
|
88ee6e661e | ||
|
|
08c9bbcc91 | ||
|
|
f96b9e6a6e | ||
|
|
9bbd3184b0 | ||
|
|
e4c1361d42 | ||
|
|
17e4765728 | ||
|
|
7e258a91ec | ||
|
|
b88853f327 | ||
|
|
a60401fc7e | ||
|
|
a734358377 | ||
|
|
ebcbad3ae3 | ||
|
|
8ff74d4a04 | ||
|
|
bd0d8eb403 | ||
|
|
9b79aa1983 | ||
|
|
172968c77e | ||
|
|
f1a7049ab5 | ||
|
|
155a2904fb | ||
|
|
4c2e8fd718 | ||
|
|
95e279a03b | ||
|
|
f2909c82f3 | ||
|
|
164b08276c | ||
|
|
b930523d44 | ||
|
|
f34b0355e7 | ||
|
|
3ee56e3bee | ||
|
|
49bf2eb6d4 | ||
|
|
707dee4c3f | ||
|
|
0ded827290 | ||
|
|
f74107d960 | ||
|
|
acd3a30d27 | ||
|
|
b636f23e3c | ||
|
|
70eae1a6f0 | ||
|
|
3574bd49bd | ||
|
|
46217a3acb | ||
|
|
9eb1255b29 | ||
|
|
d66f834e54 | ||
|
|
7c101f01e5 | ||
|
|
42689ef1da | ||
|
|
5ba7325646 | ||
|
|
86effec1a2 | ||
|
|
cdb469eca0 | ||
|
|
39c8fd8286 | ||
|
|
5730e5515f | ||
|
|
901ba551bc | ||
|
|
77b3fadf79 | ||
|
|
44fc3357d1 | ||
|
|
25414044ef | ||
|
|
d1068991e3 | ||
|
|
4ab240e990 | ||
|
|
9489927bed | ||
|
|
c160f45849 | ||
|
|
5b585c0e39 | ||
|
|
c6ee919619 | ||
|
|
675ad364ac | ||
|
|
21cefa0932 | ||
|
|
89c8c6d212 | ||
|
|
e5af7165ea | ||
|
|
ee936f9257 | ||
|
|
6482848fa4 | ||
|
|
7c2a736c4b | ||
|
|
918ec22667 | ||
|
|
1027da9be0 | ||
|
|
521bd25d31 | ||
|
|
e7c0bea6e5 | ||
|
|
a8bd5b1119 | ||
|
|
9144d12e51 | ||
|
|
d741544514 | ||
|
|
5e31f0df23 | ||
|
|
18dff9d664 | ||
|
|
350094759a | ||
|
|
b10275e851 | ||
|
|
05cf7201ad | ||
|
|
8cd5e03e87 | ||
|
|
120917e0b5 | ||
|
|
264958ebfe | ||
|
|
3614ce1409 | ||
|
|
c80542ded3 | ||
|
|
3350a936b7 | ||
|
|
724db83920 | ||
|
|
8788a40d12 | ||
|
|
6f7bf96776 | ||
|
|
e943a71dff | ||
|
|
4be1c89c5b | ||
|
|
2eda053c79 | ||
|
|
26539e68d9 | ||
|
|
046427cf55 | ||
|
|
25aabcd7e4 | ||
|
|
d8bea816dd | ||
|
|
bb2b1824a9 | ||
|
|
59a129d6d6 | ||
|
|
db40d9bc7a | ||
|
|
827b4b29b4 | ||
|
|
2a31b16567 | ||
|
|
c001c883f7 | ||
|
|
476c7ff749 | ||
|
|
4978aa74e7 | ||
|
|
4411911664 | ||
|
|
0e1ce21488 | ||
|
|
88aa17fa7b | ||
|
|
d648fdf6c0 | ||
|
|
846bd62817 | ||
|
|
84cddc70fd | ||
|
|
2a83f1fc23 | ||
|
|
751231b730 | ||
|
|
c6d400bcf3 | ||
|
|
fd1cd05b99 | ||
|
|
8202e9e921 | ||
|
|
3c069a6784 | ||
|
|
e100a63cc8 | ||
|
|
3057b5fb9d | ||
|
|
c91dc71e75 | ||
|
|
f48e4a8ad8 | ||
|
|
dafbefb325 | ||
|
|
6de23a9748 | ||
|
|
1cf33e4343 | ||
|
|
34db63171f | ||
|
|
19495f69d7 | ||
|
|
c1fbb27d73 | ||
|
|
3cf748a135 | ||
|
|
85b58d041b | ||
|
|
ae9d773e04 | ||
|
|
582bb7c897 | ||
|
|
681d4fb007 | ||
|
|
a185341a4d | ||
|
|
aacd9f51b3 | ||
|
|
95148d445a | ||
|
|
65ac422e36 | ||
|
|
5ffb6ca0cd | ||
|
|
85f151303a | ||
|
|
216cd01b3c | ||
|
|
23bd2e7cd4 | ||
|
|
f461f65a86 | ||
|
|
8dc4adbb5e | ||
|
|
8b36cd1e35 | ||
|
|
cd700a1782 | ||
|
|
60e94adeb1 | ||
|
|
eafed0f1d4 | ||
|
|
7c14c51012 | ||
|
|
4f9d24598f | ||
|
|
4277b4bef8 | ||
|
|
3c3205adf1 | ||
|
|
4e1527df95 | ||
|
|
ca2760fb46 | ||
|
|
61924672e2 | ||
|
|
7fdd988e4f | ||
|
|
a85e0523f8 | ||
|
|
462024ad03 | ||
|
|
f0d09899a1 | ||
|
|
b8212b3da7 | ||
|
|
3d812edc4d | ||
|
|
2efb7f2975 | ||
|
|
44c5e96cf0 | ||
|
|
97c878db22 | ||
|
|
16e32f8441 | ||
|
|
d6aced5ec7 | ||
|
|
b843382065 | ||
|
|
f4bdff0824 | ||
|
|
d8c28e80eb | ||
|
|
344b3e9931 | ||
|
|
c32ac19c0d | ||
|
|
d13114e907 | ||
|
|
90298fe2c8 | ||
|
|
3d1a1fb9fa | ||
|
|
830bad54bd | ||
|
|
c4ba5afe6b | ||
|
|
4ec39d49aa | ||
|
|
ab585ef951 | ||
|
|
674122999f | ||
|
|
8085caef35 | ||
|
|
3ab3c61d5e | ||
|
|
736b2cd689 | ||
|
|
bd8331678c | ||
|
|
6f3fb42385 | ||
|
|
da4e887aee | ||
|
|
b1e468dae4 | ||
|
|
6d1a885864 | ||
|
|
24b3abd706 | ||
|
|
806bc1853d | ||
|
|
6ee1dfd656 | ||
|
|
ab092cb536 | ||
|
|
b4cf50fb6e | ||
|
|
2b2b2b6545 | ||
|
|
fd7b926a33 | ||
|
|
482e0d386b | ||
|
|
d99b16ed5e | ||
|
|
0a4fe58ac6 | ||
|
|
8ac9caf45c | ||
|
|
1029b369f2 | ||
|
|
5ae588deaa | ||
|
|
a2f31ab8ae | ||
|
|
666c9c21a1 | ||
|
|
a675c4c7a1 | ||
|
|
16eab6b5e5 | ||
|
|
d520bfc753 | ||
|
|
301b10d261 | ||
|
|
e38e56ccf6 | ||
|
|
7de223f116 | ||
|
|
c5d08ec0d1 | ||
|
|
4e4b1235c3 | ||
|
|
e5d7903475 | ||
|
|
bc46bf3202 | ||
|
|
4af84e53d5 | ||
|
|
e3f60ea0fb | ||
|
|
ce15a2b01e | ||
|
|
9c878458b8 | ||
|
|
53d897da09 | ||
|
|
17030395c6 | ||
|
|
34d3d6c1f9 | ||
|
|
e335c9f977 | ||
|
|
4ee38cbe29 | ||
|
|
12c9154f55 | ||
|
|
0e312d6dfe | ||
|
|
7e18eeddba | ||
|
|
0db7141e33 | ||
|
|
1ef0b16f11 | ||
|
|
37c1bf98eb | ||
|
|
85d4c00096 | ||
|
|
078978a5b5 | ||
|
|
841d393f8b | ||
|
|
740d1f6d4e | ||
|
|
b615c103ef | ||
|
|
f879f53a6b | ||
|
|
42baa10bcb | ||
|
|
6feb9f540f | ||
|
|
f86ecfe446 | ||
|
|
64a16314ab | ||
|
|
dccebaeff8 | ||
|
|
d2e5dea3e2 | ||
|
|
ec59886031 | ||
|
|
917dd8b0db | ||
|
|
63e273efd4 | ||
|
|
9394194031 | ||
|
|
af256bc0e9 | ||
|
|
37e4b913b0 | ||
|
|
722ee2f3d0 | ||
|
|
e5f5d542d0 | ||
|
|
1ac64aca10 | ||
|
|
78054eea5a | ||
|
|
ff63b0ff1a | ||
|
|
e2e367f091 | ||
|
|
5aa1a1afc7 | ||
|
|
a2d6bd693b | ||
|
|
7f57fccefb | ||
|
|
72e123e319 | ||
|
|
d29e7140b6 | ||
|
|
b6580f99db | ||
|
|
605fbaf803 | ||
|
|
03b0493d29 | ||
|
|
5e295f59a4 | ||
|
|
f3135630d1 | ||
|
|
e140fba5df | ||
|
|
fa7a7c294e | ||
|
|
9dd65bfcb9 | ||
|
|
a8f722c4de | ||
|
|
0c56291e4a | ||
|
|
c916e3b07f | ||
|
|
32f936ce8c | ||
|
|
47aebcbdd4 | ||
|
|
4649c9a61d | ||
|
|
9300e68225 | ||
|
|
19e40a3383 | ||
|
|
9ffe85fd9c | ||
|
|
8ba86e9cea | ||
|
|
c042a28af1 | ||
|
|
1b59efc79a | ||
|
|
f1d7ac36eb | ||
|
|
21cecb2aec | ||
|
|
8a93a06b71 | ||
|
|
d2ff0af34a | ||
|
|
ae5f2ec104 | ||
|
|
6f0566581e | ||
|
|
e726c7894c | ||
|
|
c4bb4d9508 | ||
|
|
cfad228d3c | ||
|
|
670faf1d1d | ||
|
|
659163a93c | ||
|
|
2b163edc0e | ||
|
|
0d38f85db7 | ||
|
|
1dc2825a75 | ||
|
|
630e2d23c9 | ||
|
|
c73187e7d4 | ||
|
|
e18afe5d1e | ||
|
|
7534e3f739 | ||
|
|
0e01d91cec | ||
|
|
06aea6b97c | ||
|
|
a99ff813cb | ||
|
|
92734416a6 | ||
|
|
2f32d4fe49 | ||
|
|
81d35eb645 | ||
|
|
ac24ac2507 | ||
|
|
b172f9a354 | ||
|
|
63e4d3d5eb | ||
|
|
c74c8871f8 | ||
|
|
3f5d08aedb | ||
|
|
ddcb299834 | ||
|
|
a9f70dd1e5 | ||
|
|
aff0c6b49b | ||
|
|
417bb42ac8 | ||
|
|
040ed4fa57 | ||
|
|
94fc7b4e9a | ||
|
|
172e7a7649 | ||
|
|
37ed138dcf | ||
|
|
5f6aade92b | ||
|
|
0c62a5736e | ||
|
|
f1406c1ffd | ||
|
|
1cdc3e5232 | ||
|
|
bd9870254e | ||
|
|
0442b8c1e1 | ||
|
|
585876d6af | ||
|
|
902d726ea6 | ||
|
|
3f35b426dd | ||
|
|
761d861888 | ||
|
|
9f185ed5c0 | ||
|
|
63b2077335 | ||
|
|
12d5beec6e | ||
|
|
b77e68df19 | ||
|
|
fcdd4fa410 | ||
|
|
07c48bca68 | ||
|
|
79ff76d124 | ||
|
|
de2ba1ca94 | ||
|
|
45002bd51d | ||
|
|
be7ebad956 | ||
|
|
64189a4d08 | ||
|
|
708cb28ed0 | ||
|
|
6712801b01 | ||
|
|
f29db693c8 | ||
|
|
0502bfd95d | ||
|
|
78a3901c61 | ||
|
|
0a4e3008af | ||
|
|
d03ba5394f | ||
|
|
2262e6c7d0 | ||
|
|
31a349b13b | ||
|
|
1ba143ef26 | ||
|
|
1532ce1bab | ||
|
|
fa9b920b71 | ||
|
|
40b2d5f724 | ||
|
|
0623a5a8de | ||
|
|
cfa1d08e7e | ||
|
|
6196814672 | ||
|
|
f5af2bf393 | ||
|
|
374fb033c1 | ||
|
|
4db80e75a4 | ||
|
|
8547277958 | ||
|
|
ec3366b0e5 | ||
|
|
48bd04b387 | ||
|
|
41a481252c | ||
|
|
a7cf3b5b10 | ||
|
|
ba63188f27 | ||
|
|
9cc34cb70f | ||
|
|
b9a4d72b42 | ||
|
|
8eef210547 | ||
|
|
ef999ed954 | ||
|
|
33de609560 | ||
|
|
624151c3f7 | ||
|
|
c88f859dae | ||
|
|
49b77d5477 | ||
|
|
d4c4a17eb7 | ||
|
|
3c8abab574 | ||
|
|
38596f8d0e | ||
|
|
4acdca090d | ||
|
|
f02178852b | ||
|
|
98e7acddf4 | ||
|
|
9458e851c0 | ||
|
|
a04512d7b8 | ||
|
|
d6fa832d83 | ||
|
|
dbad921fa5 | ||
|
|
e1535dd574 | ||
|
|
22640eb900 | ||
|
|
7e51e03043 | ||
|
|
865616284f | ||
|
|
0cf728b7e1 | ||
|
|
a2d563b081 | ||
|
|
8119aa6933 | ||
|
|
6b953363d1 | ||
|
|
139b240250 | ||
|
|
36b5dff1f0 | ||
|
|
7ae07d4de5 | ||
|
|
59ef52a271 | ||
|
|
34a1b22a38 | ||
|
|
b4f01fa6c2 | ||
|
|
2d6d16dcd0 | ||
|
|
1ccae4fef2 | ||
|
|
ee30acab32 | ||
|
|
5189bef325 | ||
|
|
17597580f4 | ||
|
|
f97f9e8646 | ||
|
|
91f1d41324 | ||
|
|
d9d9d98ea0 | ||
|
|
e7115c7316 | ||
|
|
6c58e26f14 | ||
|
|
dc371580a5 | ||
|
|
2a047073e9 | ||
|
|
6e3b1bc240 | ||
|
|
51faaae1d0 | ||
|
|
f55804ef06 | ||
|
|
e671e1c87c | ||
|
|
a7aa817dce | ||
|
|
dcce4db6d5 | ||
|
|
64c4f0f1aa | ||
|
|
a8f928200b | ||
|
|
58d42b09d9 | ||
|
|
0cd481b149 | ||
|
|
a66c55ca14 | ||
|
|
18715dbe2e | ||
|
|
23dee61389 | ||
|
|
23dc3f29cd | ||
|
|
4c701f4b6c | ||
|
|
7a94f524b4 | ||
|
|
23deb41436 | ||
|
|
7198ebefc9 | ||
|
|
32cb57532e | ||
|
|
edcfece993 | ||
|
|
baf209f3cc | ||
|
|
ece47c9ed5 | ||
|
|
3d40ed968a | ||
|
|
10f56de5e8 | ||
|
|
5ee4fc2cd5 | ||
|
|
a7917a0f3d | ||
|
|
0274cf3ec7 | ||
|
|
3aa7c96902 | ||
|
|
ffa1851bbf | ||
|
|
45c3345bbc | ||
|
|
a6ca3aaa66 | ||
|
|
5a10b612a1 | ||
|
|
632b3ff07c | ||
|
|
efe1d1c0ac | ||
|
|
86e2f83a7d | ||
|
|
a2b3a38f86 | ||
|
|
f243749d38 | ||
|
|
dac103c621 | ||
|
|
35e53e9691 |
2
.github/CONTRIBUTING.md
vendored
2
.github/CONTRIBUTING.md
vendored
@@ -57,7 +57,7 @@ When we make a significant decision in how we maintain the project and what we c
|
|||||||
we will document it in the [capa issues tracker](https://github.com/mandiant/capa/issues).
|
we will document it in the [capa issues tracker](https://github.com/mandiant/capa/issues).
|
||||||
This is the best place review our discussions about what/how/why we do things in the project.
|
This is the best place review our discussions about what/how/why we do things in the project.
|
||||||
If you have a question, check to see if it is documented there.
|
If you have a question, check to see if it is documented there.
|
||||||
If it is *not* documented there, or you can't find an answer, please open a issue.
|
If it is *not* documented there, or you can't find an answer, please open an issue.
|
||||||
We'll link to existing issues when appropriate to keep discussions in one place.
|
We'll link to existing issues when appropriate to keep discussions in one place.
|
||||||
|
|
||||||
## How Can I Contribute?
|
## How Can I Contribute?
|
||||||
|
|||||||
3
.github/dependabot.yml
vendored
3
.github/dependabot.yml
vendored
@@ -4,3 +4,6 @@ updates:
|
|||||||
directory: "/"
|
directory: "/"
|
||||||
schedule:
|
schedule:
|
||||||
interval: "weekly"
|
interval: "weekly"
|
||||||
|
ignore:
|
||||||
|
- dependency-name: "*"
|
||||||
|
update-types: ["version-update:semver-patch"]
|
||||||
|
|||||||
4
.github/flake8.ini
vendored
4
.github/flake8.ini
vendored
@@ -10,6 +10,8 @@ extend-ignore =
|
|||||||
F811,
|
F811,
|
||||||
# E501 line too long (prefer black)
|
# E501 line too long (prefer black)
|
||||||
E501,
|
E501,
|
||||||
|
# E701 multiple statements on one line (colon) (prefer black, see https://github.com/psf/black/issues/4173)
|
||||||
|
E701,
|
||||||
# B010 Do not call setattr with a constant attribute value
|
# B010 Do not call setattr with a constant attribute value
|
||||||
B010,
|
B010,
|
||||||
# G200 Logging statement uses exception in arguments
|
# G200 Logging statement uses exception in arguments
|
||||||
@@ -38,4 +40,4 @@ per-file-ignores =
|
|||||||
|
|
||||||
copyright-check = True
|
copyright-check = True
|
||||||
copyright-min-file-size = 1
|
copyright-min-file-size = 1
|
||||||
copyright-regexp = Copyright \(C\) 2023 Mandiant, Inc. All Rights Reserved.
|
copyright-regexp = Copyright \(C\) \d{4} Mandiant, Inc. All Rights Reserved.
|
||||||
6
.github/mypy/mypy.ini
vendored
6
.github/mypy/mypy.ini
vendored
@@ -1,11 +1,5 @@
|
|||||||
[mypy]
|
[mypy]
|
||||||
|
|
||||||
[mypy-halo.*]
|
|
||||||
ignore_missing_imports = True
|
|
||||||
|
|
||||||
[mypy-tqdm.*]
|
|
||||||
ignore_missing_imports = True
|
|
||||||
|
|
||||||
[mypy-ruamel.*]
|
[mypy-ruamel.*]
|
||||||
ignore_missing_imports = True
|
ignore_missing_imports = True
|
||||||
|
|
||||||
|
|||||||
2
.github/pyinstaller/hooks/hook-vivisect.py
vendored
2
.github/pyinstaller/hooks/hook-vivisect.py
vendored
@@ -24,7 +24,7 @@ excludedimports = [
|
|||||||
"pyqtwebengine",
|
"pyqtwebengine",
|
||||||
# the above are imported by these viv modules.
|
# the above are imported by these viv modules.
|
||||||
# so really, we'd want to exclude these submodules of viv.
|
# so really, we'd want to exclude these submodules of viv.
|
||||||
# but i dont think this works.
|
# but i don't think this works.
|
||||||
"vqt",
|
"vqt",
|
||||||
"vdb.qt",
|
"vdb.qt",
|
||||||
"envi.qt",
|
"envi.qt",
|
||||||
|
|||||||
31
.github/pyinstaller/pyinstaller.spec
vendored
31
.github/pyinstaller/pyinstaller.spec
vendored
@@ -1,10 +1,18 @@
|
|||||||
# -*- mode: python -*-
|
# -*- mode: python -*-
|
||||||
# Copyright (C) 2020 Mandiant, Inc. All Rights Reserved.
|
# Copyright (C) 2020 Mandiant, Inc. All Rights Reserved.
|
||||||
import os.path
|
import sys
|
||||||
import subprocess
|
|
||||||
|
|
||||||
import wcwidth
|
import capa.rules.cache
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
# SPECPATH is a global variable which points to .spec file path
|
||||||
|
capa_dir = Path(SPECPATH).parent.parent
|
||||||
|
rules_dir = capa_dir / 'rules'
|
||||||
|
cache_dir = capa_dir / 'cache'
|
||||||
|
|
||||||
|
if not capa.rules.cache.generate_rule_cache(rules_dir, cache_dir):
|
||||||
|
sys.exit(-1)
|
||||||
|
|
||||||
a = Analysis(
|
a = Analysis(
|
||||||
# when invoking pyinstaller from the project root,
|
# when invoking pyinstaller from the project root,
|
||||||
@@ -20,13 +28,6 @@ a = Analysis(
|
|||||||
("../../rules", "rules"),
|
("../../rules", "rules"),
|
||||||
("../../sigs", "sigs"),
|
("../../sigs", "sigs"),
|
||||||
("../../cache", "cache"),
|
("../../cache", "cache"),
|
||||||
# capa.render.default uses tabulate that depends on wcwidth.
|
|
||||||
# it seems wcwidth uses a json file `version.json`
|
|
||||||
# and this doesn't get picked up by pyinstaller automatically.
|
|
||||||
# so we manually embed the wcwidth resources here.
|
|
||||||
#
|
|
||||||
# ref: https://stackoverflow.com/a/62278462/87207
|
|
||||||
(os.path.dirname(wcwidth.__file__), "wcwidth"),
|
|
||||||
],
|
],
|
||||||
# when invoking pyinstaller from the project root,
|
# when invoking pyinstaller from the project root,
|
||||||
# this gets run from the project root.
|
# this gets run from the project root.
|
||||||
@@ -39,11 +40,6 @@ a = Analysis(
|
|||||||
"tkinter",
|
"tkinter",
|
||||||
"_tkinter",
|
"_tkinter",
|
||||||
"Tkinter",
|
"Tkinter",
|
||||||
# tqdm provides renderers for ipython,
|
|
||||||
# however, this drags in a lot of dependencies.
|
|
||||||
# since we don't spawn a notebook, we can safely remove these.
|
|
||||||
"IPython",
|
|
||||||
"ipywidgets",
|
|
||||||
# these are pulled in by networkx
|
# these are pulled in by networkx
|
||||||
# but we don't need to compute the strongly connected components.
|
# but we don't need to compute the strongly connected components.
|
||||||
"numpy",
|
"numpy",
|
||||||
@@ -61,7 +57,10 @@ a = Analysis(
|
|||||||
"qt5",
|
"qt5",
|
||||||
"pyqtwebengine",
|
"pyqtwebengine",
|
||||||
"pyasn1",
|
"pyasn1",
|
||||||
|
# don't pull in Binary Ninja/IDA bindings that should
|
||||||
|
# only be installed locally.
|
||||||
"binaryninja",
|
"binaryninja",
|
||||||
|
"ida",
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -79,7 +78,7 @@ exe = EXE(
|
|||||||
name="capa",
|
name="capa",
|
||||||
icon="logo.ico",
|
icon="logo.ico",
|
||||||
debug=False,
|
debug=False,
|
||||||
strip=None,
|
strip=False,
|
||||||
upx=True,
|
upx=True,
|
||||||
console=True,
|
console=True,
|
||||||
)
|
)
|
||||||
|
|||||||
8
.github/ruff.toml
vendored
8
.github/ruff.toml
vendored
@@ -1,16 +1,16 @@
|
|||||||
# Enable the pycodestyle (`E`) and Pyflakes (`F`) rules by default.
|
# Enable the pycodestyle (`E`) and Pyflakes (`F`) rules by default.
|
||||||
# Unlike Flake8, Ruff doesn't enable pycodestyle warnings (`W`) or
|
# Unlike Flake8, Ruff doesn't enable pycodestyle warnings (`W`) or
|
||||||
# McCabe complexity (`C901`) by default.
|
# McCabe complexity (`C901`) by default.
|
||||||
select = ["E", "F"]
|
lint.select = ["E", "F"]
|
||||||
|
|
||||||
# Allow autofix for all enabled rules (when `--fix`) is provided.
|
# Allow autofix for all enabled rules (when `--fix`) is provided.
|
||||||
fixable = ["ALL"]
|
lint.fixable = ["ALL"]
|
||||||
unfixable = []
|
lint.unfixable = []
|
||||||
|
|
||||||
# E402 module level import not at top of file
|
# E402 module level import not at top of file
|
||||||
# E722 do not use bare 'except'
|
# E722 do not use bare 'except'
|
||||||
# E501 line too long
|
# E501 line too long
|
||||||
ignore = ["E402", "E722", "E501"]
|
lint.ignore = ["E402", "E722", "E501"]
|
||||||
|
|
||||||
line-length = 120
|
line-length = 120
|
||||||
|
|
||||||
|
|||||||
54
.github/workflows/build.yml
vendored
54
.github/workflows/build.yml
vendored
@@ -3,6 +3,10 @@ name: build
|
|||||||
on:
|
on:
|
||||||
pull_request:
|
pull_request:
|
||||||
branches: [ master ]
|
branches: [ master ]
|
||||||
|
paths-ignore:
|
||||||
|
- 'web/**'
|
||||||
|
- 'doc/**'
|
||||||
|
- '**.md'
|
||||||
release:
|
release:
|
||||||
types: [edited, published]
|
types: [edited, published]
|
||||||
|
|
||||||
@@ -11,57 +15,68 @@ permissions:
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
name: PyInstaller for ${{ matrix.os }}
|
name: PyInstaller for ${{ matrix.os }} / Py ${{ matrix.python_version }}
|
||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
strategy:
|
strategy:
|
||||||
# set to false for debugging
|
# set to false for debugging
|
||||||
fail-fast: true
|
fail-fast: true
|
||||||
matrix:
|
matrix:
|
||||||
|
# using Python 3.8 to support running across multiple operating systems including Windows 7
|
||||||
include:
|
include:
|
||||||
- os: ubuntu-20.04
|
- os: ubuntu-20.04
|
||||||
# use old linux so that the shared library versioning is more portable
|
# use old linux so that the shared library versioning is more portable
|
||||||
artifact_name: capa
|
artifact_name: capa
|
||||||
asset_name: linux
|
asset_name: linux
|
||||||
|
python_version: 3.8
|
||||||
|
- os: ubuntu-20.04
|
||||||
|
artifact_name: capa
|
||||||
|
asset_name: linux-py312
|
||||||
|
python_version: 3.12
|
||||||
- os: windows-2019
|
- os: windows-2019
|
||||||
artifact_name: capa.exe
|
artifact_name: capa.exe
|
||||||
asset_name: windows
|
asset_name: windows
|
||||||
- os: macos-11
|
python_version: 3.8
|
||||||
|
- os: macos-12
|
||||||
# use older macOS for assumed better portability
|
# use older macOS for assumed better portability
|
||||||
artifact_name: capa
|
artifact_name: capa
|
||||||
asset_name: macos
|
asset_name: macos
|
||||||
|
python_version: 3.8
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout capa
|
- name: Checkout capa
|
||||||
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0
|
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
|
||||||
with:
|
with:
|
||||||
submodules: true
|
submodules: true
|
||||||
# using Python 3.8 to support running across multiple operating systems including Windows 7
|
- name: Set up Python ${{ matrix.python_version }}
|
||||||
- name: Set up Python 3.8
|
uses: actions/setup-python@0a5c61591373683505ea898e09a3ea4f39ef2b9c # v5.0.0
|
||||||
uses: actions/setup-python@d27e3f3d7c64b4bbf8e4abfb9b63b83e846e0435 # v4.5.0
|
|
||||||
with:
|
with:
|
||||||
python-version: 3.8
|
python-version: ${{ matrix.python_version }}
|
||||||
- if: matrix.os == 'ubuntu-20.04'
|
- if: matrix.os == 'ubuntu-20.04'
|
||||||
run: sudo apt-get install -y libyaml-dev
|
run: sudo apt-get install -y libyaml-dev
|
||||||
- name: Upgrade pip, setuptools
|
- name: Upgrade pip, setuptools
|
||||||
run: python -m pip install --upgrade pip setuptools
|
run: python -m pip install --upgrade pip setuptools
|
||||||
- name: Install capa with build requirements
|
- name: Install capa with build requirements
|
||||||
run: pip install -e .[build]
|
run: |
|
||||||
- name: Cache the rule set
|
pip install -r requirements.txt
|
||||||
run: python ./scripts/cache-ruleset.py ./rules/ ./cache/
|
pip install -e .[build]
|
||||||
- name: Build standalone executable
|
- name: Build standalone executable
|
||||||
run: pyinstaller --log-level DEBUG .github/pyinstaller/pyinstaller.spec
|
run: pyinstaller --log-level DEBUG .github/pyinstaller/pyinstaller.spec
|
||||||
- name: Does it run (PE)?
|
- name: Does it run (PE)?
|
||||||
run: dist/capa "tests/data/Practical Malware Analysis Lab 01-01.dll_"
|
run: dist/capa -d "tests/data/Practical Malware Analysis Lab 01-01.dll_"
|
||||||
- name: Does it run (Shellcode)?
|
- name: Does it run (Shellcode)?
|
||||||
run: dist/capa "tests/data/499c2a85f6e8142c3f48d4251c9c7cd6.raw32"
|
run: dist/capa -d "tests/data/499c2a85f6e8142c3f48d4251c9c7cd6.raw32"
|
||||||
- name: Does it run (ELF)?
|
- name: Does it run (ELF)?
|
||||||
run: dist/capa "tests/data/7351f8a40c5450557b24622417fc478d.elf_"
|
run: dist/capa -d "tests/data/7351f8a40c5450557b24622417fc478d.elf_"
|
||||||
- uses: actions/upload-artifact@0b7f8abb1508181956e8e162db84b466c27e18ce # v3.1.2
|
- name: Does it run (CAPE)?
|
||||||
|
run: |
|
||||||
|
7z e "tests/data/dynamic/cape/v2.2/d46900384c78863420fb3e297d0a2f743cd2b6b3f7f82bf64059a168e07aceb7.json.gz"
|
||||||
|
dist/capa -d "d46900384c78863420fb3e297d0a2f743cd2b6b3f7f82bf64059a168e07aceb7.json"
|
||||||
|
- uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 # v4.3.1
|
||||||
with:
|
with:
|
||||||
name: ${{ matrix.asset_name }}
|
name: ${{ matrix.asset_name }}
|
||||||
path: dist/${{ matrix.artifact_name }}
|
path: dist/${{ matrix.artifact_name }}
|
||||||
|
|
||||||
test_run:
|
test_run:
|
||||||
name: Test run on ${{ matrix.os }}
|
name: Test run on ${{ matrix.os }} / ${{ matrix.asset_name }}
|
||||||
runs-on: ${{ matrix.os }}
|
runs-on: ${{ matrix.os }}
|
||||||
needs: [build]
|
needs: [build]
|
||||||
strategy:
|
strategy:
|
||||||
@@ -71,12 +86,15 @@ jobs:
|
|||||||
- os: ubuntu-22.04
|
- os: ubuntu-22.04
|
||||||
artifact_name: capa
|
artifact_name: capa
|
||||||
asset_name: linux
|
asset_name: linux
|
||||||
|
- os: ubuntu-22.04
|
||||||
|
artifact_name: capa
|
||||||
|
asset_name: linux-py312
|
||||||
- os: windows-2022
|
- os: windows-2022
|
||||||
artifact_name: capa.exe
|
artifact_name: capa.exe
|
||||||
asset_name: windows
|
asset_name: windows
|
||||||
steps:
|
steps:
|
||||||
- name: Download ${{ matrix.asset_name }}
|
- name: Download ${{ matrix.asset_name }}
|
||||||
uses: actions/download-artifact@9bc31d5ccc31df68ecc42ccf4149144866c47d8a # v3.0.2
|
uses: actions/download-artifact@eaceaf801fd36c7dee90939fad912460b18a1ffe # v4.1.2
|
||||||
with:
|
with:
|
||||||
name: ${{ matrix.asset_name }}
|
name: ${{ matrix.asset_name }}
|
||||||
- name: Set executable flag
|
- name: Set executable flag
|
||||||
@@ -96,13 +114,15 @@ jobs:
|
|||||||
include:
|
include:
|
||||||
- asset_name: linux
|
- asset_name: linux
|
||||||
artifact_name: capa
|
artifact_name: capa
|
||||||
|
- asset_name: linux-py312
|
||||||
|
artifact_name: capa
|
||||||
- asset_name: windows
|
- asset_name: windows
|
||||||
artifact_name: capa.exe
|
artifact_name: capa.exe
|
||||||
- asset_name: macos
|
- asset_name: macos
|
||||||
artifact_name: capa
|
artifact_name: capa
|
||||||
steps:
|
steps:
|
||||||
- name: Download ${{ matrix.asset_name }}
|
- name: Download ${{ matrix.asset_name }}
|
||||||
uses: actions/download-artifact@9bc31d5ccc31df68ecc42ccf4149144866c47d8a # v3.0.2
|
uses: actions/download-artifact@eaceaf801fd36c7dee90939fad912460b18a1ffe # v4.1.2
|
||||||
with:
|
with:
|
||||||
name: ${{ matrix.asset_name }}
|
name: ${{ matrix.asset_name }}
|
||||||
- name: Set executable flag
|
- name: Set executable flag
|
||||||
|
|||||||
9
.github/workflows/changelog.yml
vendored
9
.github/workflows/changelog.yml
vendored
@@ -7,7 +7,8 @@ on:
|
|||||||
pull_request_target:
|
pull_request_target:
|
||||||
types: [opened, edited, synchronize]
|
types: [opened, edited, synchronize]
|
||||||
|
|
||||||
permissions: read-all
|
permissions:
|
||||||
|
pull-requests: write
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
check_changelog:
|
check_changelog:
|
||||||
@@ -19,7 +20,7 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Get changed files
|
- name: Get changed files
|
||||||
id: files
|
id: files
|
||||||
uses: Ana06/get-changed-files@e0c398b7065a8d84700c471b6afc4116d1ba4e96 # v2.2.0
|
uses: Ana06/get-changed-files@25f79e676e7ea1868813e21465014798211fad8c # v2.3.0
|
||||||
- name: check changelog updated
|
- name: check changelog updated
|
||||||
id: changelog_updated
|
id: changelog_updated
|
||||||
env:
|
env:
|
||||||
@@ -29,14 +30,14 @@ jobs:
|
|||||||
echo $FILES | grep -qF 'CHANGELOG.md' || echo $PR_BODY | grep -qiF "$NO_CHANGELOG"
|
echo $FILES | grep -qF 'CHANGELOG.md' || echo $PR_BODY | grep -qiF "$NO_CHANGELOG"
|
||||||
- name: Reject pull request if no CHANGELOG update
|
- name: Reject pull request if no CHANGELOG update
|
||||||
if: ${{ always() && steps.changelog_updated.outcome == 'failure' }}
|
if: ${{ always() && steps.changelog_updated.outcome == 'failure' }}
|
||||||
uses: Ana06/automatic-pull-request-review@0cf4e8a17ba79344ed3fdd7fed6dd0311d08a9d4 # v0.1.0
|
uses: Ana06/automatic-pull-request-review@76aaf9b15b116a54e1da7a28a46f91fe089600bf # v0.2.0
|
||||||
with:
|
with:
|
||||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
event: REQUEST_CHANGES
|
event: REQUEST_CHANGES
|
||||||
body: "Please add bug fixes, new features, breaking changes and anything else you think is worthwhile mentioning to the `master (unreleased)` section of CHANGELOG.md. If no CHANGELOG update is needed add the following to the PR description: `${{ env.NO_CHANGELOG }}`"
|
body: "Please add bug fixes, new features, breaking changes and anything else you think is worthwhile mentioning to the `master (unreleased)` section of CHANGELOG.md. If no CHANGELOG update is needed add the following to the PR description: `${{ env.NO_CHANGELOG }}`"
|
||||||
allow_duplicate: false
|
allow_duplicate: false
|
||||||
- name: Dismiss previous review if CHANGELOG update
|
- name: Dismiss previous review if CHANGELOG update
|
||||||
uses: Ana06/automatic-pull-request-review@0cf4e8a17ba79344ed3fdd7fed6dd0311d08a9d4 # v0.1.0
|
uses: Ana06/automatic-pull-request-review@76aaf9b15b116a54e1da7a28a46f91fe089600bf # v0.2.0
|
||||||
with:
|
with:
|
||||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
event: DISMISS
|
event: DISMISS
|
||||||
|
|||||||
21
.github/workflows/pip-audit.yml
vendored
Normal file
21
.github/workflows/pip-audit.yml
vendored
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
name: PIP audit
|
||||||
|
|
||||||
|
on:
|
||||||
|
schedule:
|
||||||
|
- cron: '0 8 * * 1'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 20
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
python-version: ["3.11"]
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Check out repository code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- uses: pypa/gh-action-pip-audit@v1.0.8
|
||||||
|
with:
|
||||||
|
inputs: .
|
||||||
7
.github/workflows/publish.yml
vendored
7
.github/workflows/publish.yml
vendored
@@ -17,20 +17,21 @@ jobs:
|
|||||||
permissions:
|
permissions:
|
||||||
id-token: write
|
id-token: write
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0
|
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
|
||||||
- name: Set up Python
|
- name: Set up Python
|
||||||
uses: actions/setup-python@d27e3f3d7c64b4bbf8e4abfb9b63b83e846e0435 # v4.5.0
|
uses: actions/setup-python@0a5c61591373683505ea898e09a3ea4f39ef2b9c # v5.0.0
|
||||||
with:
|
with:
|
||||||
python-version: '3.8'
|
python-version: '3.8'
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: |
|
run: |
|
||||||
python -m pip install --upgrade pip
|
python -m pip install --upgrade pip
|
||||||
|
pip install -r requirements.txt
|
||||||
pip install -e .[build]
|
pip install -e .[build]
|
||||||
- name: build package
|
- name: build package
|
||||||
run: |
|
run: |
|
||||||
python -m build
|
python -m build
|
||||||
- name: upload package artifacts
|
- name: upload package artifacts
|
||||||
uses: actions/upload-artifact@0b7f8abb1508181956e8e162db84b466c27e18ce # v3.1.2
|
uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 # v4.3.1
|
||||||
with:
|
with:
|
||||||
path: dist/*
|
path: dist/*
|
||||||
- name: publish package
|
- name: publish package
|
||||||
|
|||||||
8
.github/workflows/scorecard.yml
vendored
8
.github/workflows/scorecard.yml
vendored
@@ -32,12 +32,12 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: "Checkout code"
|
- name: "Checkout code"
|
||||||
uses: actions/checkout@93ea575cb5d8a053eaa0ac8fa3b40d7e05a33cc8 # v3.1.0
|
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
|
||||||
with:
|
with:
|
||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
|
|
||||||
- name: "Run analysis"
|
- name: "Run analysis"
|
||||||
uses: ossf/scorecard-action@99c53751e09b9529366343771cc321ec74e9bd3d # v2.0.6
|
uses: ossf/scorecard-action@0864cf19026789058feabb7e87baa5f140aac736 # v2.3.1
|
||||||
with:
|
with:
|
||||||
results_file: results.sarif
|
results_file: results.sarif
|
||||||
results_format: sarif
|
results_format: sarif
|
||||||
@@ -59,7 +59,7 @@ jobs:
|
|||||||
# Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF
|
# Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF
|
||||||
# format to the repository Actions tab.
|
# format to the repository Actions tab.
|
||||||
- name: "Upload artifact"
|
- name: "Upload artifact"
|
||||||
uses: actions/upload-artifact@3cea5372237819ed00197afe530f5a7ea3e805c8 # v3.1.0
|
uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 # v4.3.1
|
||||||
with:
|
with:
|
||||||
name: SARIF file
|
name: SARIF file
|
||||||
path: results.sarif
|
path: results.sarif
|
||||||
@@ -67,6 +67,6 @@ jobs:
|
|||||||
|
|
||||||
# Upload the results to GitHub's code scanning dashboard.
|
# Upload the results to GitHub's code scanning dashboard.
|
||||||
- name: "Upload to code-scanning"
|
- name: "Upload to code-scanning"
|
||||||
uses: github/codeql-action/upload-sarif@807578363a7869ca324a79039e6db9c843e0e100 # v2.1.27
|
uses: github/codeql-action/upload-sarif@8a470fddafa5cbb6266ee11b37ef4d8aae19c571 # v3.24.6
|
||||||
with:
|
with:
|
||||||
sarif_file: results.sarif
|
sarif_file: results.sarif
|
||||||
|
|||||||
4
.github/workflows/tag.yml
vendored
4
.github/workflows/tag.yml
vendored
@@ -12,7 +12,7 @@ jobs:
|
|||||||
runs-on: ubuntu-20.04
|
runs-on: ubuntu-20.04
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout capa-rules
|
- name: Checkout capa-rules
|
||||||
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0
|
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
|
||||||
with:
|
with:
|
||||||
repository: mandiant/capa-rules
|
repository: mandiant/capa-rules
|
||||||
token: ${{ secrets.CAPA_TOKEN }}
|
token: ${{ secrets.CAPA_TOKEN }}
|
||||||
@@ -25,7 +25,7 @@ jobs:
|
|||||||
git tag $name -m "https://github.com/mandiant/capa/releases/$name"
|
git tag $name -m "https://github.com/mandiant/capa/releases/$name"
|
||||||
# TODO update branch name-major=${name%%.*}
|
# TODO update branch name-major=${name%%.*}
|
||||||
- name: Push tag to capa-rules
|
- name: Push tag to capa-rules
|
||||||
uses: ad-m/github-push-action@0fafdd62b84042d49ec0cb92d9cac7f7ce4ec79e # master
|
uses: ad-m/github-push-action@d91a481090679876dfc4178fef17f286781251df # v0.8.0
|
||||||
with:
|
with:
|
||||||
repository: mandiant/capa-rules
|
repository: mandiant/capa-rules
|
||||||
github_token: ${{ secrets.CAPA_TOKEN }}
|
github_token: ${{ secrets.CAPA_TOKEN }}
|
||||||
|
|||||||
103
.github/workflows/tests.yml
vendored
103
.github/workflows/tests.yml
vendored
@@ -1,10 +1,22 @@
|
|||||||
name: CI
|
name: CI
|
||||||
|
|
||||||
|
# tests.yml workflow will run for all changes except:
|
||||||
|
# any file or directory under web/ or doc/
|
||||||
|
# any Markdown (.md) file anywhere in the repository
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [ master ]
|
branches: [ master ]
|
||||||
|
paths-ignore:
|
||||||
|
- 'web/**'
|
||||||
|
- 'doc/**'
|
||||||
|
- '**.md'
|
||||||
pull_request:
|
pull_request:
|
||||||
branches: [ master ]
|
branches: [ master ]
|
||||||
|
paths-ignore:
|
||||||
|
- 'web/**'
|
||||||
|
- 'doc/**'
|
||||||
|
- '**.md'
|
||||||
|
|
||||||
permissions: read-all
|
permissions: read-all
|
||||||
|
|
||||||
@@ -17,7 +29,7 @@ jobs:
|
|||||||
runs-on: ubuntu-20.04
|
runs-on: ubuntu-20.04
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout capa
|
- name: Checkout capa
|
||||||
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0
|
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
|
||||||
# The sync GH action in capa-rules relies on a single '- *$' in the CHANGELOG file
|
# The sync GH action in capa-rules relies on a single '- *$' in the CHANGELOG file
|
||||||
- name: Ensure CHANGELOG has '- *$'
|
- name: Ensure CHANGELOG has '- *$'
|
||||||
run: |
|
run: |
|
||||||
@@ -28,38 +40,44 @@ jobs:
|
|||||||
runs-on: ubuntu-20.04
|
runs-on: ubuntu-20.04
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout capa
|
- name: Checkout capa
|
||||||
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0
|
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
|
||||||
# use latest available python to take advantage of best performance
|
# use latest available python to take advantage of best performance
|
||||||
- name: Set up Python 3.11
|
- name: Set up Python 3.11
|
||||||
uses: actions/setup-python@d27e3f3d7c64b4bbf8e4abfb9b63b83e846e0435 # v4.5.0
|
uses: actions/setup-python@0a5c61591373683505ea898e09a3ea4f39ef2b9c # v5.0.0
|
||||||
with:
|
with:
|
||||||
python-version: "3.11"
|
python-version: "3.11"
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: pip install -e .[dev]
|
run: |
|
||||||
|
pip install -r requirements.txt
|
||||||
|
pip install -e .[dev,scripts]
|
||||||
- name: Lint with ruff
|
- name: Lint with ruff
|
||||||
run: pre-commit run ruff
|
run: pre-commit run ruff
|
||||||
- name: Lint with isort
|
- name: Lint with isort
|
||||||
run: pre-commit run isort
|
run: pre-commit run isort --show-diff-on-failure
|
||||||
- name: Lint with black
|
- name: Lint with black
|
||||||
run: pre-commit run black
|
run: pre-commit run black --show-diff-on-failure
|
||||||
- name: Lint with flake8
|
- name: Lint with flake8
|
||||||
run: pre-commit run flake8
|
run: pre-commit run flake8 --hook-stage manual
|
||||||
- name: Check types with mypy
|
- name: Check types with mypy
|
||||||
run: pre-commit run mypy
|
run: pre-commit run mypy --hook-stage manual
|
||||||
|
- name: Check imports against dependencies
|
||||||
|
run: pre-commit run deptry --hook-stage manual
|
||||||
|
|
||||||
rule_linter:
|
rule_linter:
|
||||||
runs-on: ubuntu-20.04
|
runs-on: ubuntu-20.04
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout capa with submodules
|
- name: Checkout capa with submodules
|
||||||
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0
|
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
|
||||||
with:
|
with:
|
||||||
submodules: recursive
|
submodules: recursive
|
||||||
- name: Set up Python 3.11
|
- name: Set up Python 3.11
|
||||||
uses: actions/setup-python@d27e3f3d7c64b4bbf8e4abfb9b63b83e846e0435 # v4.5.0
|
uses: actions/setup-python@0a5c61591373683505ea898e09a3ea4f39ef2b9c # v5.0.0
|
||||||
with:
|
with:
|
||||||
python-version: "3.11"
|
python-version: "3.11"
|
||||||
- name: Install capa
|
- name: Install capa
|
||||||
run: pip install -e .[dev]
|
run: |
|
||||||
|
pip install -r requirements.txt
|
||||||
|
pip install -e .[dev,scripts]
|
||||||
- name: Run rule linter
|
- name: Run rule linter
|
||||||
run: python scripts/lint.py rules/
|
run: python scripts/lint.py rules/
|
||||||
|
|
||||||
@@ -70,7 +88,7 @@ jobs:
|
|||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
os: [ubuntu-20.04, windows-2019, macos-11]
|
os: [ubuntu-20.04, windows-2019, macos-12]
|
||||||
# across all operating systems
|
# across all operating systems
|
||||||
python-version: ["3.8", "3.11"]
|
python-version: ["3.8", "3.11"]
|
||||||
include:
|
include:
|
||||||
@@ -83,18 +101,24 @@ jobs:
|
|||||||
python-version: "3.10"
|
python-version: "3.10"
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout capa with submodules
|
- name: Checkout capa with submodules
|
||||||
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0
|
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
|
||||||
with:
|
with:
|
||||||
submodules: recursive
|
submodules: recursive
|
||||||
- name: Set up Python ${{ matrix.python-version }}
|
- name: Set up Python ${{ matrix.python-version }}
|
||||||
uses: actions/setup-python@d27e3f3d7c64b4bbf8e4abfb9b63b83e846e0435 # v4.5.0
|
uses: actions/setup-python@0a5c61591373683505ea898e09a3ea4f39ef2b9c # v5.0.0
|
||||||
with:
|
with:
|
||||||
python-version: ${{ matrix.python-version }}
|
python-version: ${{ matrix.python-version }}
|
||||||
- name: Install pyyaml
|
- name: Install pyyaml
|
||||||
if: matrix.os == 'ubuntu-20.04'
|
if: matrix.os == 'ubuntu-20.04'
|
||||||
run: sudo apt-get install -y libyaml-dev
|
run: sudo apt-get install -y libyaml-dev
|
||||||
- name: Install capa
|
- name: Install capa
|
||||||
run: pip install -e .[dev]
|
run: |
|
||||||
|
pip install -r requirements.txt
|
||||||
|
pip install -e .[dev,scripts]
|
||||||
|
- name: Run tests (fast)
|
||||||
|
# this set of tests runs about 80% of the cases in 20% of the time,
|
||||||
|
# and should catch most errors quickly.
|
||||||
|
run: pre-commit run pytest-fast --all-files --hook-stage manual
|
||||||
- name: Run tests
|
- name: Run tests
|
||||||
run: pytest -v tests/
|
run: pytest -v tests/
|
||||||
|
|
||||||
@@ -102,22 +126,22 @@ jobs:
|
|||||||
name: Binary Ninja tests for ${{ matrix.python-version }}
|
name: Binary Ninja tests for ${{ matrix.python-version }}
|
||||||
env:
|
env:
|
||||||
BN_SERIAL: ${{ secrets.BN_SERIAL }}
|
BN_SERIAL: ${{ secrets.BN_SERIAL }}
|
||||||
runs-on: ubuntu-20.04
|
runs-on: ubuntu-22.04
|
||||||
needs: [code_style, rule_linter]
|
needs: [tests]
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
python-version: ["3.8", "3.11"]
|
python-version: ["3.9", "3.11"]
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout capa with submodules
|
- name: Checkout capa with submodules
|
||||||
# do only run if BN_SERIAL is available, have to do this in every step, see https://github.com/orgs/community/discussions/26726#discussioncomment-3253118
|
# do only run if BN_SERIAL is available, have to do this in every step, see https://github.com/orgs/community/discussions/26726#discussioncomment-3253118
|
||||||
if: ${{ env.BN_SERIAL != 0 }}
|
if: ${{ env.BN_SERIAL != 0 }}
|
||||||
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0
|
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
|
||||||
with:
|
with:
|
||||||
submodules: recursive
|
submodules: recursive
|
||||||
- name: Set up Python ${{ matrix.python-version }}
|
- name: Set up Python ${{ matrix.python-version }}
|
||||||
if: ${{ env.BN_SERIAL != 0 }}
|
if: ${{ env.BN_SERIAL != 0 }}
|
||||||
uses: actions/setup-python@d27e3f3d7c64b4bbf8e4abfb9b63b83e846e0435 # v4.5.0
|
uses: actions/setup-python@0a5c61591373683505ea898e09a3ea4f39ef2b9c # v5.0.0
|
||||||
with:
|
with:
|
||||||
python-version: ${{ matrix.python-version }}
|
python-version: ${{ matrix.python-version }}
|
||||||
- name: Install pyyaml
|
- name: Install pyyaml
|
||||||
@@ -125,7 +149,9 @@ jobs:
|
|||||||
run: sudo apt-get install -y libyaml-dev
|
run: sudo apt-get install -y libyaml-dev
|
||||||
- name: Install capa
|
- name: Install capa
|
||||||
if: ${{ env.BN_SERIAL != 0 }}
|
if: ${{ env.BN_SERIAL != 0 }}
|
||||||
run: pip install -e .[dev]
|
run: |
|
||||||
|
pip install -r requirements.txt
|
||||||
|
pip install -e .[dev,scripts]
|
||||||
- name: install Binary Ninja
|
- name: install Binary Ninja
|
||||||
if: ${{ env.BN_SERIAL != 0 }}
|
if: ${{ env.BN_SERIAL != 0 }}
|
||||||
run: |
|
run: |
|
||||||
@@ -143,37 +169,29 @@ jobs:
|
|||||||
ghidra-tests:
|
ghidra-tests:
|
||||||
name: Ghidra tests for ${{ matrix.python-version }}
|
name: Ghidra tests for ${{ matrix.python-version }}
|
||||||
runs-on: ubuntu-20.04
|
runs-on: ubuntu-20.04
|
||||||
needs: [code_style, rule_linter]
|
needs: [tests]
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
python-version: ["3.8", "3.11"]
|
python-version: ["3.8", "3.11"]
|
||||||
java-version: ["17"]
|
java-version: ["17"]
|
||||||
gradle-version: ["7.3"]
|
ghidra-version: ["11.0.1"]
|
||||||
ghidra-version: ["10.3"]
|
public-version: ["PUBLIC_20240130"] # for ghidra releases
|
||||||
public-version: ["PUBLIC_20230510"] # for ghidra releases
|
ghidrathon-version: ["4.0.0"]
|
||||||
jep-version: ["4.1.1"]
|
|
||||||
ghidrathon-version: ["3.0.0"]
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout capa with submodules
|
- name: Checkout capa with submodules
|
||||||
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # v3.3.0
|
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
|
||||||
with:
|
with:
|
||||||
submodules: true
|
submodules: true
|
||||||
- name: Set up Python ${{ matrix.python-version }}
|
- name: Set up Python ${{ matrix.python-version }}
|
||||||
uses: actions/setup-python@d27e3f3d7c64b4bbf8e4abfb9b63b83e846e0435 # v4.5.0
|
uses: actions/setup-python@0a5c61591373683505ea898e09a3ea4f39ef2b9c # v5.0.0
|
||||||
with:
|
with:
|
||||||
python-version: ${{ matrix.python-version }}
|
python-version: ${{ matrix.python-version }}
|
||||||
- name: Set up Java ${{ matrix.java-version }}
|
- name: Set up Java ${{ matrix.java-version }}
|
||||||
uses: actions/setup-java@5ffc13f4174014e2d4d4572b3d74c3fa61aeb2c2 # v3
|
uses: actions/setup-java@387ac29b308b003ca37ba93a6cab5eb57c8f5f93 # v4.0.0
|
||||||
with:
|
with:
|
||||||
distribution: 'temurin'
|
distribution: 'temurin'
|
||||||
java-version: ${{ matrix.java-version }}
|
java-version: ${{ matrix.java-version }}
|
||||||
- name: Set up Gradle ${{ matrix.gradle-version }}
|
|
||||||
uses: gradle/gradle-build-action@40b6781dcdec2762ad36556682ac74e31030cfe2 # v2.5.1
|
|
||||||
with:
|
|
||||||
gradle-version: ${{ matrix.gradle-version }}
|
|
||||||
- name: Install Jep ${{ matrix.jep-version }}
|
|
||||||
run : pip install jep==${{ matrix.jep-version }}
|
|
||||||
- name: Install Ghidra ${{ matrix.ghidra-version }}
|
- name: Install Ghidra ${{ matrix.ghidra-version }}
|
||||||
run: |
|
run: |
|
||||||
mkdir ./.github/ghidra
|
mkdir ./.github/ghidra
|
||||||
@@ -182,14 +200,17 @@ jobs:
|
|||||||
- name: Install Ghidrathon
|
- name: Install Ghidrathon
|
||||||
run : |
|
run : |
|
||||||
mkdir ./.github/ghidrathon
|
mkdir ./.github/ghidrathon
|
||||||
curl -o ./.github/ghidrathon/ghidrathon-${{ matrix.ghidrathon-version }}.zip "https://codeload.github.com/mandiant/Ghidrathon/zip/refs/tags/v${{ matrix.ghidrathon-version }}"
|
wget "https://github.com/mandiant/Ghidrathon/releases/download/v${{ matrix.ghidrathon-version }}/Ghidrathon-v${{ matrix.ghidrathon-version}}.zip" -O ./.github/ghidrathon/ghidrathon-v${{ matrix.ghidrathon-version }}.zip
|
||||||
unzip .github/ghidrathon/ghidrathon-${{ matrix.ghidrathon-version }}.zip -d .github/ghidrathon/
|
unzip .github/ghidrathon/ghidrathon-v${{ matrix.ghidrathon-version }}.zip -d .github/ghidrathon/
|
||||||
gradle -p ./.github/ghidrathon/Ghidrathon-${{ matrix.ghidrathon-version }}/ -PGHIDRA_INSTALL_DIR=$(pwd)/.github/ghidra/ghidra_${{ matrix.ghidra-version }}_PUBLIC
|
python -m pip install -r .github/ghidrathon/requirements.txt
|
||||||
unzip .github/ghidrathon/Ghidrathon-${{ matrix.ghidrathon-version }}/dist/*.zip -d .github/ghidra/ghidra_${{ matrix.ghidra-version }}_PUBLIC/Ghidra/Extensions
|
python .github/ghidrathon/ghidrathon_configure.py $(pwd)/.github/ghidra/ghidra_${{ matrix.ghidra-version }}_PUBLIC
|
||||||
|
unzip .github/ghidrathon/Ghidrathon-v${{ matrix.ghidrathon-version }}.zip -d .github/ghidra/ghidra_${{ matrix.ghidra-version }}_PUBLIC/Ghidra/Extensions
|
||||||
- name: Install pyyaml
|
- name: Install pyyaml
|
||||||
run: sudo apt-get install -y libyaml-dev
|
run: sudo apt-get install -y libyaml-dev
|
||||||
- name: Install capa
|
- name: Install capa
|
||||||
run: pip install -e .[dev]
|
run: |
|
||||||
|
pip install -r requirements.txt
|
||||||
|
pip install -e .[dev,scripts]
|
||||||
- name: Run tests
|
- name: Run tests
|
||||||
run: |
|
run: |
|
||||||
mkdir ./.github/ghidra/project
|
mkdir ./.github/ghidra/project
|
||||||
|
|||||||
134
.github/workflows/web-deploy.yml
vendored
Normal file
134
.github/workflows/web-deploy.yml
vendored
Normal file
@@ -0,0 +1,134 @@
|
|||||||
|
name: deploy web to GitHub Pages
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [ master ]
|
||||||
|
paths:
|
||||||
|
- 'web/**'
|
||||||
|
|
||||||
|
# Allows to run this workflow manually from the Actions tab
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
# Sets the GITHUB_TOKEN permissions to allow deployment to GitHub Pages
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
pages: write
|
||||||
|
id-token: write
|
||||||
|
|
||||||
|
# Allow one concurrent deployment
|
||||||
|
concurrency:
|
||||||
|
group: 'pages'
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build-landing-page:
|
||||||
|
name: Build landing page
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: landing-page
|
||||||
|
path: './web/public'
|
||||||
|
|
||||||
|
build-explorer:
|
||||||
|
name: Build capa Explorer Web
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
submodules: 'recursive'
|
||||||
|
fetch-depth: 1
|
||||||
|
show-progress: true
|
||||||
|
- name: Set up Node
|
||||||
|
uses: actions/setup-node@0a44ba7841725637a19e28fa30b79a866c81b0a6 # v4.0.4
|
||||||
|
with:
|
||||||
|
node-version: 20
|
||||||
|
cache: 'npm'
|
||||||
|
cache-dependency-path: './web/explorer/package-lock.json'
|
||||||
|
- name: Install dependencies
|
||||||
|
run: npm ci
|
||||||
|
working-directory: ./web/explorer
|
||||||
|
- name: Generate release bundle
|
||||||
|
run: npm run build:bundle
|
||||||
|
working-directory: ./web/explorer
|
||||||
|
- name: Zip release bundle
|
||||||
|
run: zip -r public/capa-explorer-web.zip capa-explorer-web
|
||||||
|
working-directory: ./web/explorer
|
||||||
|
- name: Build
|
||||||
|
run: npm run build
|
||||||
|
working-directory: ./web/explorer
|
||||||
|
- uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: explorer
|
||||||
|
path: './web/explorer/dist'
|
||||||
|
|
||||||
|
build-rules:
|
||||||
|
name: Build rules site
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Check out the repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
submodules: 'recursive'
|
||||||
|
# full depth so that capa-rules has a full history
|
||||||
|
# and we can construct a timeline of rule updates.
|
||||||
|
fetch-depth: 0
|
||||||
|
- name: Set up Python
|
||||||
|
uses: actions/setup-python@0a5c61591373683505ea898e09a3ea4f39ef2b9c # v5.0.0
|
||||||
|
with:
|
||||||
|
python-version: '3.12'
|
||||||
|
- uses: extractions/setup-just@v2
|
||||||
|
- name: Install pagefind
|
||||||
|
uses: supplypike/setup-bin@v4
|
||||||
|
with:
|
||||||
|
uri: "https://github.com/CloudCannon/pagefind/releases/download/v1.1.0/pagefind-v1.1.0-x86_64-unknown-linux-musl.tar.gz"
|
||||||
|
name: "pagefind"
|
||||||
|
version: "1.1.0"
|
||||||
|
- name: Install dependencies
|
||||||
|
working-directory: ./web/rules
|
||||||
|
run: pip install -r requirements.txt
|
||||||
|
- name: Build the website
|
||||||
|
working-directory: ./web/rules
|
||||||
|
run: just build
|
||||||
|
- name: Index the website
|
||||||
|
working-directory: ./web/rules
|
||||||
|
run: pagefind --site "public"
|
||||||
|
# upload the build website to artifacts
|
||||||
|
# so that we can download and inspect, if desired.
|
||||||
|
- uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: rules
|
||||||
|
path: './web/rules/public'
|
||||||
|
|
||||||
|
deploy:
|
||||||
|
name: Deploy site to GitHub Pages
|
||||||
|
environment:
|
||||||
|
name: github-pages
|
||||||
|
url: ${{ steps.deployment.outputs.page_url }}
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: [build-landing-page, build-explorer, build-rules]
|
||||||
|
steps:
|
||||||
|
- uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
name: landing-page
|
||||||
|
path: './public/'
|
||||||
|
- uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
name: explorer
|
||||||
|
path: './public/explorer'
|
||||||
|
- uses: actions/download-artifact@v4
|
||||||
|
with:
|
||||||
|
name: rules
|
||||||
|
path: './public/rules'
|
||||||
|
- name: Setup Pages
|
||||||
|
uses: actions/configure-pages@v4
|
||||||
|
- name: Upload artifact
|
||||||
|
uses: actions/upload-pages-artifact@v3
|
||||||
|
with:
|
||||||
|
path: './public'
|
||||||
|
- name: Deploy to GitHub Pages
|
||||||
|
id: deployment
|
||||||
|
uses: actions/deploy-pages@v4
|
||||||
42
.github/workflows/web-tests.yml
vendored
Normal file
42
.github/workflows/web-tests.yml
vendored
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
name: Capa Explorer Web tests
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
branches: [ master ]
|
||||||
|
paths:
|
||||||
|
- 'web/explorer/**'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
submodules: 'recursive'
|
||||||
|
fetch-depth: 1
|
||||||
|
show-progress: true
|
||||||
|
|
||||||
|
- name: Set up Node
|
||||||
|
uses: actions/setup-node@0a44ba7841725637a19e28fa30b79a866c81b0a6 # v4.0.4
|
||||||
|
with:
|
||||||
|
node-version: 20
|
||||||
|
cache: 'npm'
|
||||||
|
cache-dependency-path: './web/explorer/package-lock.json'
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: npm ci
|
||||||
|
working-directory: ./web/explorer
|
||||||
|
|
||||||
|
- name: Lint
|
||||||
|
run: npm run lint
|
||||||
|
working-directory: ./web/explorer
|
||||||
|
|
||||||
|
- name: Format
|
||||||
|
run: npm run format:check
|
||||||
|
working-directory: ./web/explorer
|
||||||
|
|
||||||
|
- name: Run unit tests
|
||||||
|
run: npm run test
|
||||||
|
working-directory: ./web/explorer
|
||||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -126,3 +126,5 @@ Pipfile.lock
|
|||||||
.github/binja/binaryninja
|
.github/binja/binaryninja
|
||||||
.github/binja/download_headless.py
|
.github/binja/download_headless.py
|
||||||
.github/binja/BinaryNinja-headless.zip
|
.github/binja/BinaryNinja-headless.zip
|
||||||
|
justfile
|
||||||
|
data/
|
||||||
|
|||||||
4
.gitmodules
vendored
4
.gitmodules
vendored
@@ -1,6 +1,6 @@
|
|||||||
[submodule "rules"]
|
[submodule "rules"]
|
||||||
path = rules
|
path = rules
|
||||||
url = ../capa-rules.git
|
url = ../../mandiant/capa-rules.git
|
||||||
[submodule "tests/data"]
|
[submodule "tests/data"]
|
||||||
path = tests/data
|
path = tests/data
|
||||||
url = ../capa-testfiles.git
|
url = ../../mandiant/capa-testfiles.git
|
||||||
|
|||||||
25
.justfile
Normal file
25
.justfile
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
@isort:
|
||||||
|
pre-commit run isort --show-diff-on-failure --all-files
|
||||||
|
|
||||||
|
@black:
|
||||||
|
pre-commit run black --show-diff-on-failure --all-files
|
||||||
|
|
||||||
|
@ruff:
|
||||||
|
pre-commit run ruff --all-files
|
||||||
|
|
||||||
|
@flake8:
|
||||||
|
pre-commit run flake8 --hook-stage manual --all-files
|
||||||
|
|
||||||
|
@mypy:
|
||||||
|
pre-commit run mypy --hook-stage manual --all-files
|
||||||
|
|
||||||
|
@deptry:
|
||||||
|
pre-commit run deptry --hook-stage manual --all-files
|
||||||
|
|
||||||
|
@lint:
|
||||||
|
-just isort
|
||||||
|
-just black
|
||||||
|
-just ruff
|
||||||
|
-just flake8
|
||||||
|
-just mypy
|
||||||
|
-just deptry
|
||||||
@@ -25,7 +25,7 @@ repos:
|
|||||||
hooks:
|
hooks:
|
||||||
- id: isort
|
- id: isort
|
||||||
name: isort
|
name: isort
|
||||||
stages: [commit, push]
|
stages: [commit, push, manual]
|
||||||
language: system
|
language: system
|
||||||
entry: isort
|
entry: isort
|
||||||
args:
|
args:
|
||||||
@@ -38,6 +38,7 @@ repos:
|
|||||||
- "capa/"
|
- "capa/"
|
||||||
- "scripts/"
|
- "scripts/"
|
||||||
- "tests/"
|
- "tests/"
|
||||||
|
- "web/rules/scripts/"
|
||||||
always_run: true
|
always_run: true
|
||||||
pass_filenames: false
|
pass_filenames: false
|
||||||
|
|
||||||
@@ -45,7 +46,7 @@ repos:
|
|||||||
hooks:
|
hooks:
|
||||||
- id: black
|
- id: black
|
||||||
name: black
|
name: black
|
||||||
stages: [commit, push]
|
stages: [commit, push, manual]
|
||||||
language: system
|
language: system
|
||||||
entry: black
|
entry: black
|
||||||
args:
|
args:
|
||||||
@@ -55,6 +56,7 @@ repos:
|
|||||||
- "capa/"
|
- "capa/"
|
||||||
- "scripts/"
|
- "scripts/"
|
||||||
- "tests/"
|
- "tests/"
|
||||||
|
- "web/rules/scripts/"
|
||||||
always_run: true
|
always_run: true
|
||||||
pass_filenames: false
|
pass_filenames: false
|
||||||
|
|
||||||
@@ -62,7 +64,7 @@ repos:
|
|||||||
hooks:
|
hooks:
|
||||||
- id: ruff
|
- id: ruff
|
||||||
name: ruff
|
name: ruff
|
||||||
stages: [commit, push]
|
stages: [commit, push, manual]
|
||||||
language: system
|
language: system
|
||||||
entry: ruff
|
entry: ruff
|
||||||
args:
|
args:
|
||||||
@@ -72,6 +74,7 @@ repos:
|
|||||||
- "capa/"
|
- "capa/"
|
||||||
- "scripts/"
|
- "scripts/"
|
||||||
- "tests/"
|
- "tests/"
|
||||||
|
- "web/rules/scripts/"
|
||||||
always_run: true
|
always_run: true
|
||||||
pass_filenames: false
|
pass_filenames: false
|
||||||
|
|
||||||
@@ -79,17 +82,18 @@ repos:
|
|||||||
hooks:
|
hooks:
|
||||||
- id: flake8
|
- id: flake8
|
||||||
name: flake8
|
name: flake8
|
||||||
stages: [commit, push]
|
stages: [push, manual]
|
||||||
language: system
|
language: system
|
||||||
entry: flake8
|
entry: flake8
|
||||||
args:
|
args:
|
||||||
- "--config"
|
- "--config"
|
||||||
- ".github/flake8.ini"
|
- ".github/flake8.ini"
|
||||||
- "--extend-exclude"
|
- "--extend-exclude"
|
||||||
- "capa/render/proto/capa_pb2.py"
|
- "capa/render/proto/capa_pb2.py,capa/features/extractors/binexport2/binexport2_pb2.py"
|
||||||
- "capa/"
|
- "capa/"
|
||||||
- "scripts/"
|
- "scripts/"
|
||||||
- "tests/"
|
- "tests/"
|
||||||
|
- "web/rules/scripts/"
|
||||||
always_run: true
|
always_run: true
|
||||||
pass_filenames: false
|
pass_filenames: false
|
||||||
|
|
||||||
@@ -97,7 +101,7 @@ repos:
|
|||||||
hooks:
|
hooks:
|
||||||
- id: mypy
|
- id: mypy
|
||||||
name: mypy
|
name: mypy
|
||||||
stages: [commit, push]
|
stages: [push, manual]
|
||||||
language: system
|
language: system
|
||||||
entry: mypy
|
entry: mypy
|
||||||
args:
|
args:
|
||||||
@@ -107,5 +111,35 @@ repos:
|
|||||||
- "capa/"
|
- "capa/"
|
||||||
- "scripts/"
|
- "scripts/"
|
||||||
- "tests/"
|
- "tests/"
|
||||||
|
- "web/rules/scripts/"
|
||||||
always_run: true
|
always_run: true
|
||||||
pass_filenames: false
|
pass_filenames: false
|
||||||
|
|
||||||
|
- repo: local
|
||||||
|
hooks:
|
||||||
|
- id: deptry
|
||||||
|
name: deptry
|
||||||
|
stages: [push, manual]
|
||||||
|
language: system
|
||||||
|
entry: deptry .
|
||||||
|
always_run: true
|
||||||
|
pass_filenames: false
|
||||||
|
|
||||||
|
- repo: local
|
||||||
|
hooks:
|
||||||
|
- id: pytest-fast
|
||||||
|
name: pytest (fast)
|
||||||
|
stages: [manual]
|
||||||
|
language: system
|
||||||
|
entry: pytest
|
||||||
|
args:
|
||||||
|
- "tests/"
|
||||||
|
- "--ignore=tests/test_binja_features.py"
|
||||||
|
- "--ignore=tests/test_ghidra_features.py"
|
||||||
|
- "--ignore=tests/test_ida_features.py"
|
||||||
|
- "--ignore=tests/test_viv_features.py"
|
||||||
|
- "--ignore=tests/test_main.py"
|
||||||
|
- "--ignore=tests/test_scripts.py"
|
||||||
|
always_run: true
|
||||||
|
pass_filenames: false
|
||||||
|
|
||||||
|
|||||||
482
CHANGELOG.md
482
CHANGELOG.md
@@ -3,31 +3,407 @@
|
|||||||
## master (unreleased)
|
## master (unreleased)
|
||||||
|
|
||||||
### New Features
|
### New Features
|
||||||
- ghidra: add Ghidra feature extractor and supporting code #1770 @colton-gabertan
|
|
||||||
- ghidra: add entry script helping users run capa against a loaded Ghidra database #1767 @mike-hunhoff
|
|
||||||
- binja: add support for forwarded exports #1646 @xusheng6
|
|
||||||
- binja: add support for symtab names #1504 @xusheng6
|
|
||||||
|
|
||||||
### Breaking Changes
|
### Breaking Changes
|
||||||
|
|
||||||
### New Rules (1)
|
### New Rules (0)
|
||||||
|
|
||||||
- nursery/get-ntoskrnl-base-address @mr-tz
|
|
||||||
-
|
-
|
||||||
|
|
||||||
### Bug Fixes
|
### Bug Fixes
|
||||||
- ghidra: fix ints_to_bytes performance #1761 @mike-hunhoff
|
|
||||||
- binja: improve function call site detection @xusheng6
|
- extractor: fix exception when PE extractor encounters unknown architecture #2440 @Tamir-K
|
||||||
- binja: use binaryninja.load to open files @xusheng6
|
- IDA Pro: rename ida to idapro module for plugin and idalib in IDA 9.0 #2453 @mr-tz
|
||||||
- binja: bump binja version to 3.5 #1789 @xusheng6
|
|
||||||
|
### capa Explorer Web
|
||||||
|
|
||||||
|
### capa Explorer IDA Pro plugin
|
||||||
|
|
||||||
|
### Development
|
||||||
|
|
||||||
|
### Raw diffs
|
||||||
|
- [capa v7.4.0...master](https://github.com/mandiant/capa/compare/v7.4.0...master)
|
||||||
|
- [capa-rules v7.4.0...master](https://github.com/mandiant/capa-rules/compare/v7.4.0...master)
|
||||||
|
|
||||||
|
## v7.4.0
|
||||||
|
|
||||||
|
The v7.4.0 capa release fixes a bug when processing VMRay analysis archives and enhances API extraction for all dynamic backends. For better terminal rendering capa now solely relies on the rich library.
|
||||||
|
|
||||||
|
The standalone capa executable can now automatically detect installations of relevant third party applications and use their backends (notably, idalib and Binary Ninja). For the extra standalone Linux build we've upgraded from Python 3.11 to 3.12.
|
||||||
|
|
||||||
|
Twelve new rules have been added. Thanks to all the contributors!
|
||||||
|
|
||||||
|
*This is the last capa version supporting Python 3.8 and 3.9. If you have major concerns about this please reach out to us.*
|
||||||
|
|
||||||
|
### New Features
|
||||||
|
|
||||||
|
- add IDA v9.0 backend via idalib #2376 @williballenthin
|
||||||
|
- locate Binary Ninja API using XDG Desktop Entries #2376 @williballenthin
|
||||||
|
|
||||||
|
### New Rules (15)
|
||||||
|
|
||||||
|
- nursery/access-unmanaged-com-objects-in-dotnet mehunhoff@google.com
|
||||||
|
- nursery/implement-ui-automation-client-in-dotnet mehunhoff@google.com
|
||||||
|
- nursery/interact-with-shortcut-via-iwshshortcut-in-dotnet mehunhoff@google.com
|
||||||
|
- nursery/interact-with-windows-scripting-host-in-dotnet mehunhoff@google.com
|
||||||
|
- nursery/use-dotnet-library-simplejson mehunhoff@google.com
|
||||||
|
- nursery/use-dotnet-library-websocket-sharp mehunhoff@google.com
|
||||||
|
- linking/runtime-linking/populate-syswhispers2-syscall-list still@teamt5.org
|
||||||
|
- host-interaction/os/hide-shutdown-actions-via-policy still@teamt5.org
|
||||||
|
- host-interaction/process/get-process-filename matthew.williams@mandiant.com
|
||||||
|
- host-interaction/driver/complete-processing-asynchronous-io-request moritz.raabe@mandiant.com
|
||||||
|
- anti-analysis/packer/nmm-protect/packed-with-nmm-protect william.ballenthin@mandiant.com
|
||||||
|
- host-interaction/firewall/modify/access-firewall-policy-via-inetfwpolicy2 jakub.jozwiak@mandiant.com
|
||||||
|
- host-interaction/firewall/modify/access-firewall-rule-properties-via-inetfwrule jakub.jozwiak@mandiant.com
|
||||||
|
- host-interaction/registry/open-recentdocs-registry-key matthew.williams@mandiant.com
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
- use Python 3.12 to build extra standalone build on Linux #2383 @williballenthin
|
||||||
|
- bump minimum Python version to 3.8.1 to satisfy uv #2387 @williballenthin
|
||||||
|
- vmray: collect more process information from flog.xml #2394 @mr-tz @mike-hunhoff
|
||||||
|
- replace tabulate, tqdm, and termcolor with rich #2374 @s-ff
|
||||||
|
- dynamic: emit complete features for A/W APIs #2409 @mike-hunhoff
|
||||||
|
- vmray: fix backslash handling in string call arguments #2428 @mr-tz
|
||||||
|
|
||||||
|
### capa Explorer Web
|
||||||
|
- improve navigation in capa Explorer Web @s-ff #2425
|
||||||
|
|
||||||
|
### Raw diffs
|
||||||
|
|
||||||
|
- [capa v7.3.0...v7.4.0](https://github.com/mandiant/capa/compare/v7.3.0...v7.4.0)
|
||||||
|
- [capa-rules v7.3.0...v7.4.0](https://github.com/mandiant/capa-rules/compare/v7.3.0...v7.4.0)
|
||||||
|
|
||||||
|
## v7.3.0
|
||||||
|
|
||||||
|
This release comes with the following three major enhancements:
|
||||||
|
|
||||||
|
### 1. Support for VMRay sandbox analysis archives
|
||||||
|
|
||||||
|
Unlock powerful malware analysis with capa's new [VMRay sandbox](https://www.vmray.com/) integration! Simply provide a VMRay analysis archive, and capa will automatically extract and match capabilities to streamline your workflow. This is the second support for the analysis of dynamic analysis results after [CAPE](https://www.mandiant.com/resources/blog/dynamic-capa-executable-behavior-cape-sandbox).
|
||||||
|
|
||||||
|
### 2. Support for BinExport files generated by Ghidra
|
||||||
|
|
||||||
|
[BinExport](https://github.com/google/binexport) files store disassembled data into a Protocol Buffer format. capa now supports the analysis of BinExport files generated by Ghidra. Using Ghidra and the BinExport file format users can now analyze ARM (AARCH64) ELF files targeting Android.
|
||||||
|
|
||||||
|
### 3. Introducing the capa rules website
|
||||||
|
|
||||||
|
You can now browse capa's default rule set at https://mandiant.github.io/capa/rules. In modern terminals the CLI capa tool hyperlinks to resources on the web, including entries on the capa rules website.
|
||||||
|
Furthermore, https://mandiant.github.io/capa provides a landing page for the capa tool project.
|
||||||
|
|
||||||
|
### Additional updates
|
||||||
|
|
||||||
|
- [capa Explorer Web](https://mandiant.github.io/capa/explorer/) received several enhancements and bug fixes.
|
||||||
|
- Support for the IDA Pro 9.0 IDAPython API while keeping compatibility to older IDA Pro versions
|
||||||
|
- Six rules have been added and two rules have been updated
|
||||||
|
|
||||||
|
Thanks to @r-sm2024 for their contribution in https://github.com/mandiant/capa/pull/2155 and their further work. And of course a big thanks to the community for reporting issues, participating in discussions, and supporting the capa tool and capa rules.
|
||||||
|
|
||||||
|
### New Features
|
||||||
|
|
||||||
|
- regenerate ruleset cache automatically on source change (only in dev mode) #2133 @s-ff
|
||||||
|
- add landing page https://mandiant.github.io/capa/ @williballenthin #2310
|
||||||
|
- add rules website https://mandiant.github.io/capa/rules @DeeyaSingh #2310
|
||||||
|
- add .justfile @williballenthin #2325
|
||||||
|
- dynamic: add support for VMRay dynamic sandbox traces #2208 @mike-hunhoff @r-sm2024 @mr-tz
|
||||||
|
- cli: use modern terminal features to hyperlink to the rules website #2337 @williballenthin
|
||||||
|
- support analyzing BinExport2 files generated by Ghidra #1950 @williballenthin @mehunhoff @mr-tz
|
||||||
|
- add support for Android OS #1950 @williballenthin @mehunhoff @mr-tz
|
||||||
|
- add support for aarch64 architecture via BinExport2 backend #1950 @williballenthin @mehunhoff @mr-tz
|
||||||
|
|
||||||
|
### New Rules (6)
|
||||||
|
|
||||||
|
- linking/static/minhook/linked-against-minhook jakub.jozwiak@mandiant.com
|
||||||
|
- linking/static/sqlite3/linked-against-sqlcipher wballenthin@google.com
|
||||||
|
- host-interaction/network/traffic/filter/delete-network-filter-via-wfp-api jakub.jozwiak@mandiant.com
|
||||||
|
- host-interaction/network/traffic/filter/enumerate-network-filters-via-wfp-api jakub.jozwiak@mandiant.com
|
||||||
|
- nursery/check-thread-suspend-count-exceeded ervinocampo@google.com
|
||||||
|
- nursery/create-thread-bypassing-process-freeze ervinocampo@google.com
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
- fix duplicate features shown in vverbose mode @williballenthin #2323
|
||||||
|
- fix code path reference in linter @williballenthin #2350
|
||||||
|
|
||||||
|
### capa explorer IDA Pro plugin
|
||||||
|
|
||||||
|
- update IDAPython to IDA Pro 9.0 @mr-tz
|
||||||
|
- fix byte search IDA Pro 7.5 compatibility @mr-tz #2371
|
||||||
|
|
||||||
|
### Raw diffs
|
||||||
|
|
||||||
|
- [capa v7.2.0...v7.3.0](https://github.com/mandiant/capa/compare/v7.2.0...v7.3.0)
|
||||||
|
- [capa-rules v7.2.0...v7.3.0](https://github.com/mandiant/capa-rules/compare/v7.2.0...v7.3.0)
|
||||||
|
|
||||||
|
## v7.2.0
|
||||||
|
|
||||||
|
capa v7.2.0 introduces a first version of capa explorer web: a web-based user interface to inspect capa results using your browser. Users can inspect capa result JSON documents in an online web instance or a standalone HTML page for offline usage. capa explorer supports interactive exploring of capa results to make it easier to understand them. Users can filter, sort, and see the details of all identified capabilities. capa explorer web was worked on by @s-ff as part of a [GSoC project](https://summerofcode.withgoogle.com/programs/2024/projects/cR3hjbsq), and it is available at https://mandiant.github.io/capa/explorer/#/.
|
||||||
|
|
||||||
|
This release also adds a feature extractor for output from the DRAKVUF sandbox. Now, analysts can pass the resulting `drakmon.log` file to capa and extract capabilities from the artifacts captured by the sandbox. This feature extractor will also be added to the DRAKVUF sandbox as a post-processing script, and it was worked on by @yelhamer as part of a [GSoC project](https://summerofcode.withgoogle.com/programs/2024/projects/fCnBGuEC).
|
||||||
|
|
||||||
|
Additionally, we fixed several bugs handling ELF files, and added the ability to filter capa analysis by functions or processes. We also added support to the IDA Pro extractor to leverage analyst recovered API names.
|
||||||
|
|
||||||
|
Special thanks to our repeat and new contributors:
|
||||||
|
|
||||||
|
- @lakshayletsgo for their first contribution in https://github.com/mandiant/capa/pull/2248
|
||||||
|
- @msm-cert for their first contribution in https://github.com/mandiant/capa/pull/2143
|
||||||
|
- @VascoSch92 for their first contribution in https://github.com/mandiant/capa/pull/2143
|
||||||
|
|
||||||
|
### New Features
|
||||||
|
|
||||||
|
- webui: explore capa analysis results in a web-based UI online and offline #2224 @s-ff
|
||||||
|
- support analyzing DRAKVUF traces #2143 @yelhamer
|
||||||
|
- IDA extractor: extract names from dynamically resolved APIs stored in renamed global variables #2201 @Ana06
|
||||||
|
- cli: add the ability to select which specific functions or processes to analyze @yelhamer
|
||||||
|
|
||||||
|
### Breaking Changes
|
||||||
|
|
||||||
|
### New Rules (5)
|
||||||
|
|
||||||
|
- nursery/upload-file-to-onedrive jaredswilson@google.com ervinocampo@google.com
|
||||||
|
- data-manipulation/encoding/base64/decode-data-using-base64-via-vbmi-lookup-table still@teamt5.org
|
||||||
|
- communication/socket/attach-bpf-to-socket-on-linux jakub.jozwiak@mandiant.com
|
||||||
|
- anti-analysis/anti-av/overwrite-dll-text-section-to-remove-hooks jakub.jozwiak@mandiant.com
|
||||||
|
- nursery/delete-file-on-linux mehunhoff@google.com
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
- elf: extract import / export symbols from stripped binaries #2096 @ygasparis
|
||||||
|
- elf: fix handling of symbols in corrupt ELF files #2226 @williballenthin
|
||||||
|
|
||||||
### capa explorer IDA Pro plugin
|
### capa explorer IDA Pro plugin
|
||||||
|
|
||||||
### Development
|
### Development
|
||||||
|
|
||||||
|
- CI: use macos-12 since macos-11 is deprecated and will be removed on June 28th, 2024 #2173 @mr-tz
|
||||||
|
- CI: update Binary Ninja version to 4.1 and use Python 3.9 to test it #2211 @xusheng6
|
||||||
|
- CI: update tests.yml workflow to exclude web and documentation files #2263 @s-ff
|
||||||
|
- CI: update build.yml workflow to exclude web and documentation files #2270 @s-ff
|
||||||
|
|
||||||
### Raw diffs
|
### Raw diffs
|
||||||
- [capa v6.1.0...master](https://github.com/mandiant/capa/compare/v6.1.0...master)
|
|
||||||
- [capa-rules v6.1.0...master](https://github.com/mandiant/capa-rules/compare/v6.1.0...master)
|
- [capa v7.1.0...7.2.0](https://github.com/mandiant/capa/compare/v7.1.0...7.2.0)
|
||||||
|
- [capa-rules v7.1.0...7.2.0](https://github.com/mandiant/capa-rules/compare/v7.1.0...7.2.0)
|
||||||
|
|
||||||
|
## v7.1.0
|
||||||
|
|
||||||
|
The v7.1.0 release brings large performance improvements to capa's rule matching engine.
|
||||||
|
Additionally, we've fixed various bugs and added new features for people using and developing capa.
|
||||||
|
|
||||||
|
Special thanks to our repeat and new contributors:
|
||||||
|
|
||||||
|
- @sjha2048 made their first contribution in https://github.com/mandiant/capa/pull/2000
|
||||||
|
- @Rohit1123 made their first contribution in https://github.com/mandiant/capa/pull/1990
|
||||||
|
- @psahithireddy made their first contribution in https://github.com/mandiant/capa/pull/2020
|
||||||
|
- @Atlas-64 made their first contribution in https://github.com/mandiant/capa/pull/2018
|
||||||
|
- @s-ff made their first contribution in https://github.com/mandiant/capa/pull/2011
|
||||||
|
- @samadpls made their first contribution in https://github.com/mandiant/capa/pull/2024
|
||||||
|
- @acelynnzhang made their first contribution in https://github.com/mandiant/capa/pull/2044
|
||||||
|
- @RainRat made their first contribution in https://github.com/mandiant/capa/pull/2058
|
||||||
|
- @ReversingWithMe made their first contribution in https://github.com/mandiant/capa/pull/2093
|
||||||
|
- @malwarefrank made their first contribution in https://github.com/mandiant/capa/pull/2037
|
||||||
|
|
||||||
|
### New Features
|
||||||
|
|
||||||
|
- Emit "dotnet" as format to ResultDocument when processing .NET files #2024 @samadpls
|
||||||
|
- ELF: detect OS from statically-linked Go binaries #1978 @williballenthin
|
||||||
|
- add function in capa/helpers to load plain and compressed JSON reports #1883 @Rohit1123
|
||||||
|
- document Antivirus warnings and VirusTotal false positive detections #2028 @RionEV @mr-tz
|
||||||
|
- Add json to sarif conversion script @reversingwithme
|
||||||
|
- render maec/\* fields #843 @s-ff
|
||||||
|
- replace Halo spinner with Rich #2086 @s-ff
|
||||||
|
- optimize rule matching #2080 @williballenthin
|
||||||
|
- add aarch64 as a valid architecture #2144 mehunhoff@google.com @williballenthin
|
||||||
|
- relax dependency version requirements for the capa library #2053 @williballenthin
|
||||||
|
- add scripts dependency group and update documentation #2145 @mr-tz
|
||||||
|
|
||||||
|
### New Rules (25)
|
||||||
|
|
||||||
|
- impact/wipe-disk/delete-drive-layout-via-ioctl william.ballenthin@mandiant.com
|
||||||
|
- host-interaction/driver/interact-with-driver-via-ioctl moritz.raabe@mandiant.com
|
||||||
|
- host-interaction/driver/unload-driver moritz.raabe@mandiant.com
|
||||||
|
- nursery/get-disk-information-via-ioctl william.ballenthin@mandiant.com
|
||||||
|
- nursery/get-volume-information-via-ioctl william.ballenthin@mandiant.com
|
||||||
|
- nursery/unmount-volume-via-ioctl william.ballenthin@mandiant.com
|
||||||
|
- data-manipulation/encryption/rc4/encrypt-data-using-rc4-via-systemfunction033 daniel.stepanic@elastic.co
|
||||||
|
- anti-analysis/anti-forensic/self-deletion/self-delete-using-alternate-data-streams daniel.stepanic@elastic.co
|
||||||
|
- nursery/change-memory-permission-on-linux mehunhoff@google.com
|
||||||
|
- nursery/check-file-permission-on-linux mehunhoff@google.com
|
||||||
|
- nursery/check-if-process-is-running-under-android-emulator-on-android mehunhoff@google.com
|
||||||
|
- nursery/map-or-unmap-memory-on-linux mehunhoff@google.com
|
||||||
|
- persistence/act-as-share-provider-dll jakub.jozwiak@mandiant.com
|
||||||
|
- persistence/act-as-windbg-extension jakub.jozwiak@mandiant.com
|
||||||
|
- persistence/act-as-time-provider-dll jakub.jozwiak@mandiant.com
|
||||||
|
- host-interaction/gui/window/hide/hide-graphical-window-from-taskbar jakub.jozwiak@mandiant.com
|
||||||
|
- compiler/dart/compiled-with-dart jakub.jozwiak@mandiant.com
|
||||||
|
- nursery/bypass-hidden-api-restrictions-via-jni-on-android mehunhoff@google.com
|
||||||
|
- nursery/get-current-process-filesystem-mounts-on-linux mehunhoff@google.com
|
||||||
|
- nursery/get-current-process-memory-mapping-on-linux mehunhoff@google.com
|
||||||
|
- nursery/get-system-property-on-android mehunhoff@google.com
|
||||||
|
- nursery/hook-routines-via-lsplant mehunhoff@google.com
|
||||||
|
- nursery/load-packed-dex-via-jiagu-on-android mehunhoff@google.com
|
||||||
|
- nursery/modify-api-blacklist-or-denylist-via-jni-on-android mehunhoff@google.com
|
||||||
|
- nursery/truncate-file-on-linux mehunhoff@google.com
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
- do some imports closer to where they are used #1810 @williballenthin
|
||||||
|
- binja: fix and simplify stack string detection code after binja 4.0 @xusheng6
|
||||||
|
- binja: add support for forwarded export #1646 @xusheng6
|
||||||
|
- cape: support more report formats #2035 @mr-tz
|
||||||
|
|
||||||
|
### capa explorer IDA Pro plugin
|
||||||
|
|
||||||
|
- replace deprecated IDA API find_binary with bin_search #1606 @s-ff
|
||||||
|
|
||||||
|
### Development
|
||||||
|
|
||||||
|
- ci: Fix PR review in the changelog check GH action #2004 @Ana06
|
||||||
|
- ci: use rules number badge stored in our bot gist and generated using `schneegans/dynamic-badges-action` #2001 capa-rules#882 @Ana06
|
||||||
|
- ci: update github workflows to use latest version of actions that were using a deprecated version of node #1967 #2003 capa-rules#883 @sjha2048 @Ana06
|
||||||
|
- ci: update binja version to stable 4.0 #2016 @xusheng6
|
||||||
|
- ci: update github workflows to reflect the latest ghidrathon installation and bumped up jep, ghidra versions #2020 @psahithireddy
|
||||||
|
- ci: include rule caching in PyInstaller build process #2097 @s-ff
|
||||||
|
- add deptry support #1497 @s-ff
|
||||||
|
|
||||||
|
### Raw diffs
|
||||||
|
|
||||||
|
- [capa v7.0.1...v7.1.0](https://github.com/mandiant/capa/compare/v7.0.1...v7.1.0)
|
||||||
|
- [capa-rules v7.0.1...v7.1.0](https://github.com/mandiant/capa-rules/compare/v7.0.1...v7.1.0)
|
||||||
|
|
||||||
|
## v7.0.1
|
||||||
|
|
||||||
|
This release fixes a circular import error when using capa as a library.
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
- fix potentially circular import errors #1969 @williballenthin
|
||||||
|
|
||||||
|
### Raw diffs
|
||||||
|
|
||||||
|
- [capa v7.0.0...v7.0.1](https://github.com/mandiant/capa/compare/v7.0.0...v7.0.1)
|
||||||
|
- [capa-rules v7.0.0...v7.0.1](https://github.com/mandiant/capa-rules/compare/v7.0.0...v7.0.1)
|
||||||
|
|
||||||
|
## v7.0.0
|
||||||
|
|
||||||
|
This is the v7.0.0 release of capa which was mainly worked on during the Google Summer of Code (GSoC) 2023. A huge
|
||||||
|
shoutout to our GSoC contributors @colton-gabertan and @yelhamer for their amazing work.
|
||||||
|
|
||||||
|
Also, a big thanks to the other contributors: @aaronatp, @Aayush-Goel-04, @bkojusner, @doomedraven, @ruppde, @larchchen, @JCoonradt, and @xusheng6.
|
||||||
|
|
||||||
|
### New Features
|
||||||
|
|
||||||
|
- add Ghidra backend #1770 #1767 @colton-gabertan @mike-hunhoff
|
||||||
|
- add Ghidra UI integration #1734 @colton-gabertan @mike-hunhoff
|
||||||
|
- add dynamic analysis via CAPE sandbox reports #48 #1535 @yelhamer
|
||||||
|
- add call scope #771 @yelhamer
|
||||||
|
- add thread scope #1517 @yelhamer
|
||||||
|
- add process scope #1517 @yelhamer
|
||||||
|
- rules: change `meta.scope` to `meta.scopes` @yelhamer
|
||||||
|
- protobuf: add `Metadata.flavor` @williballenthin
|
||||||
|
- binja: add support for forwarded exports #1646 @xusheng6
|
||||||
|
- binja: add support for symtab names #1504 @xusheng6
|
||||||
|
- add com class/interface features #322 @Aayush-goel-04
|
||||||
|
- dotnet: emit enclosing class information for nested classes #1780 #1913 @bkojusner @mike-hunhoff
|
||||||
|
|
||||||
|
### Breaking Changes
|
||||||
|
|
||||||
|
- remove the `SCOPE_*` constants in favor of the `Scope` enum #1764 @williballenthin
|
||||||
|
- protobuf: deprecate `RuleMetadata.scope` in favor of `RuleMetadata.scopes` @williballenthin
|
||||||
|
- protobuf: deprecate `Metadata.analysis` in favor of `Metadata.analysis2` that is dynamic analysis aware @williballenthin
|
||||||
|
- update freeze format to v3, adding support for dynamic analysis @williballenthin
|
||||||
|
- extractor: ignore DLL name for api features #1815 @mr-tz
|
||||||
|
- main: introduce wrapping routines within main for working with CLI args #1813 @williballenthin
|
||||||
|
- move functions from `capa.main` to new `capa.loader` namespace #1821 @williballenthin
|
||||||
|
- proto: add `package` declaration #1960 @larchchen
|
||||||
|
|
||||||
|
### New Rules (41)
|
||||||
|
|
||||||
|
- nursery/get-ntoskrnl-base-address @mr-tz
|
||||||
|
- host-interaction/network/connectivity/set-tcp-connection-state @johnk3r
|
||||||
|
- nursery/capture-process-snapshot-data @mr-tz
|
||||||
|
- collection/network/capture-packets-using-sharppcap jakub.jozwiak@mandiant.com
|
||||||
|
- nursery/communicate-with-kernel-module-via-netlink-socket-on-linux michael.hunhoff@mandiant.com
|
||||||
|
- nursery/get-current-pid-on-linux michael.hunhoff@mandiant.com
|
||||||
|
- nursery/get-file-system-information-on-linux michael.hunhoff@mandiant.com
|
||||||
|
- nursery/get-password-database-entry-on-linux michael.hunhoff@mandiant.com
|
||||||
|
- nursery/mark-thread-detached-on-linux michael.hunhoff@mandiant.com
|
||||||
|
- nursery/persist-via-gnome-autostart-on-linux michael.hunhoff@mandiant.com
|
||||||
|
- nursery/set-thread-name-on-linux michael.hunhoff@mandiant.com
|
||||||
|
- load-code/dotnet/load-windows-common-language-runtime michael.hunhoff@mandiant.com blas.kojusner@mandiant.com jakub.jozwiak@mandiant.com
|
||||||
|
- nursery/log-keystrokes-via-input-method-manager @mr-tz
|
||||||
|
- nursery/encrypt-data-using-rc4-via-systemfunction032 richard.weiss@mandiant.com
|
||||||
|
- nursery/add-value-to-global-atom-table @mr-tz
|
||||||
|
- nursery/enumerate-processes-that-use-resource @Ana06
|
||||||
|
- host-interaction/process/inject/allocate-or-change-rwx-memory @mr-tz
|
||||||
|
- lib/allocate-or-change-rw-memory 0x534a@mailbox.org @mr-tz
|
||||||
|
- lib/change-memory-protection @mr-tz
|
||||||
|
- anti-analysis/anti-av/patch-antimalware-scan-interface-function jakub.jozwiak@mandiant.com
|
||||||
|
- executable/dotnet-singlefile/bundled-with-dotnet-single-file-deployment sara.rincon@mandiant.com
|
||||||
|
- internal/limitation/file/internal-dotnet-single-file-deployment-limitation sara.rincon@mandiant.com
|
||||||
|
- data-manipulation/encoding/encode-data-using-add-xor-sub-operations jakub.jozwiak@mandiant.com
|
||||||
|
- nursery/access-camera-in-dotnet-on-android michael.hunhoff@mandiant.com
|
||||||
|
- nursery/capture-microphone-audio-in-dotnet-on-android michael.hunhoff@mandiant.com
|
||||||
|
- nursery/capture-screenshot-in-dotnet-on-android michael.hunhoff@mandiant.com
|
||||||
|
- nursery/check-for-incoming-call-in-dotnet-on-android michael.hunhoff@mandiant.com
|
||||||
|
- nursery/check-for-outgoing-call-in-dotnet-on-android michael.hunhoff@mandiant.com
|
||||||
|
- nursery/compiled-with-xamarin michael.hunhoff@mandiant.com
|
||||||
|
- nursery/get-os-version-in-dotnet-on-android michael.hunhoff@mandiant.com
|
||||||
|
- data-manipulation/compression/create-cabinet-on-windows michael.hunhoff@mandiant.com jakub.jozwiak@mandiant.com
|
||||||
|
- data-manipulation/compression/extract-cabinet-on-windows jakub.jozwiak@mandiant.com
|
||||||
|
- lib/create-file-decompression-interface-context-on-windows jakub.jozwiak@mandiant.com
|
||||||
|
- nursery/enumerate-files-in-dotnet moritz.raabe@mandiant.com anushka.virgaonkar@mandiant.com
|
||||||
|
- nursery/get-mac-address-in-dotnet moritz.raabe@mandiant.com michael.hunhoff@mandiant.com echernofsky@google.com
|
||||||
|
- nursery/get-current-process-command-line william.ballenthin@mandiant.com
|
||||||
|
- nursery/get-current-process-file-path william.ballenthin@mandiant.com
|
||||||
|
- nursery/hook-routines-via-dlsym-rtld_next william.ballenthin@mandiant.com
|
||||||
|
- nursery/linked-against-hp-socket still@teamt5.org
|
||||||
|
- host-interaction/process/inject/process-ghostly-hollowing sara.rincon@mandiant.com
|
||||||
|
|
||||||
|
### Bug Fixes
|
||||||
|
|
||||||
|
- ghidra: fix `ints_to_bytes` performance #1761 @mike-hunhoff
|
||||||
|
- binja: improve function call site detection @xusheng6
|
||||||
|
- binja: use `binaryninja.load` to open files @xusheng6
|
||||||
|
- binja: bump binja version to 3.5 #1789 @xusheng6
|
||||||
|
- elf: better detect ELF OS via GCC .ident directives #1928 @williballenthin
|
||||||
|
- elf: better detect ELF OS via Android dependencies #1947 @williballenthin
|
||||||
|
- fix setuptools package discovery #1886 @gmacon @mr-tz
|
||||||
|
- remove unnecessary scripts/vivisect-py2-vs-py3.sh file #1949 @JCoonradt
|
||||||
|
|
||||||
|
### capa explorer IDA Pro plugin
|
||||||
|
|
||||||
|
- various integration updates and minor bug fixes
|
||||||
|
|
||||||
|
### Development
|
||||||
|
|
||||||
|
- update ATT&CK/MBC data for linting #1932 @mr-tz
|
||||||
|
|
||||||
|
#### Developer Notes
|
||||||
|
|
||||||
|
With this new release, many classes and concepts have been split up into static (mostly identical to the
|
||||||
|
prior implementations) and dynamic ones. For example, the legacy FeatureExtractor class has been renamed to
|
||||||
|
StaticFeatureExtractor and the DynamicFeatureExtractor has been added.
|
||||||
|
|
||||||
|
Starting from version 7.0, we have moved the component responsible for feature extractor from main to a new
|
||||||
|
capabilities' module. Now, users wishing to utilize capa’s feature extraction abilities should use that module instead
|
||||||
|
of importing the relevant logic from the main file.
|
||||||
|
|
||||||
|
For sandbox-based feature extractors, we are using Pydantic models. Contributions of more models for other sandboxes
|
||||||
|
are very welcome!
|
||||||
|
|
||||||
|
With this release we've reorganized the logic found in `main()` to localize logic and ease readability and ease changes
|
||||||
|
and integrations. The new "main routines" are expected to be used only within main functions, either capa main or
|
||||||
|
related scripts. These functions should not be invoked from library code.
|
||||||
|
|
||||||
|
Beyond copying code around, we've refined the handling of the input file/format/backend. The logic for picking the
|
||||||
|
format and backend is more consistent. We've documented that the input file is not necessarily the sample itself
|
||||||
|
(cape/freeze/etc.) inputs are not actually the sample.
|
||||||
|
|
||||||
|
### Raw diffs
|
||||||
|
|
||||||
|
- [capa v6.1.0...v7.0.0](https://github.com/mandiant/capa/compare/v6.1.0...v7.0.0)
|
||||||
|
- [capa-rules v6.1.0...v7.0.0](https://github.com/mandiant/capa-rules/compare/v6.1.0...v7.0.0)
|
||||||
|
|
||||||
## v6.1.0
|
## v6.1.0
|
||||||
|
|
||||||
@@ -39,6 +415,7 @@ You could use this script to find opportunities for new rules.
|
|||||||
Speaking of new rules, we have eight additions, coming from Ronnie, Jakub, Moritz, Ervin, and still@teamt5.org!
|
Speaking of new rules, we have eight additions, coming from Ronnie, Jakub, Moritz, Ervin, and still@teamt5.org!
|
||||||
|
|
||||||
### New Features
|
### New Features
|
||||||
|
|
||||||
- ELF: implement import and export name extractor #1607 #1608 @Aayush-Goel-04
|
- ELF: implement import and export name extractor #1607 #1608 @Aayush-Goel-04
|
||||||
- bump pydantic from 1.10.9 to 2.1.1 #1582 @Aayush-Goel-04
|
- bump pydantic from 1.10.9 to 2.1.1 #1582 @Aayush-Goel-04
|
||||||
- develop script to highlight features not used during matching #331 @Aayush-Goel-04
|
- develop script to highlight features not used during matching #331 @Aayush-Goel-04
|
||||||
@@ -64,9 +441,11 @@ Speaking of new rules, we have eight additions, coming from Ronnie, Jakub, Morit
|
|||||||
- pytest: don't mark IDA tests as pytest tests #1719 @williballenthin
|
- pytest: don't mark IDA tests as pytest tests #1719 @williballenthin
|
||||||
|
|
||||||
### capa explorer IDA Pro plugin
|
### capa explorer IDA Pro plugin
|
||||||
|
|
||||||
- fix unhandled exception when resolving rule path #1693 @mike-hunhoff
|
- fix unhandled exception when resolving rule path #1693 @mike-hunhoff
|
||||||
|
|
||||||
### Raw diffs
|
### Raw diffs
|
||||||
|
|
||||||
- [capa v6.0.0...v6.1.0](https://github.com/mandiant/capa/compare/v6.0.0...v6.1.0)
|
- [capa v6.0.0...v6.1.0](https://github.com/mandiant/capa/compare/v6.0.0...v6.1.0)
|
||||||
- [capa-rules v6.0.0...v6.1.0](https://github.com/mandiant/capa-rules/compare/v6.0.0...v6.1.0)
|
- [capa-rules v6.0.0...v6.1.0](https://github.com/mandiant/capa-rules/compare/v6.0.0...v6.1.0)
|
||||||
|
|
||||||
@@ -77,12 +456,14 @@ capa v6.0 brings many bug fixes and quality improvements, including 64 rule upda
|
|||||||
For those that use capa as a library, we've introduced some limited breaking changes that better represent data types (versus less-structured data like dictionaries and strings). With the recent deprecation, we've also dropped support for Python 3.7.
|
For those that use capa as a library, we've introduced some limited breaking changes that better represent data types (versus less-structured data like dictionaries and strings). With the recent deprecation, we've also dropped support for Python 3.7.
|
||||||
|
|
||||||
### New Features
|
### New Features
|
||||||
|
|
||||||
- add script to detect feature overlap between new and existing capa rules [#1451](https://github.com/mandiant/capa/issues/1451) [@Aayush-Goel-04](https://github.com/aayush-goel-04)
|
- add script to detect feature overlap between new and existing capa rules [#1451](https://github.com/mandiant/capa/issues/1451) [@Aayush-Goel-04](https://github.com/aayush-goel-04)
|
||||||
- extract forwarded exports from PE files #1624 @williballenthin
|
- extract forwarded exports from PE files #1624 @williballenthin
|
||||||
- extract function and API names from ELF symtab entries @yelhamer https://github.com/mandiant/capa-rules/issues/736
|
- extract function and API names from ELF symtab entries @yelhamer https://github.com/mandiant/capa-rules/issues/736
|
||||||
- use fancy box drawing characters for default output #1586 @williballenthin
|
- use fancy box drawing characters for default output #1586 @williballenthin
|
||||||
|
|
||||||
### Breaking Changes
|
### Breaking Changes
|
||||||
|
|
||||||
- use a class to represent Metadata (not dict) #1411 @Aayush-Goel-04 @manasghandat
|
- use a class to represent Metadata (not dict) #1411 @Aayush-Goel-04 @manasghandat
|
||||||
- use pathlib.Path to represent file paths #1534 @Aayush-Goel-04
|
- use pathlib.Path to represent file paths #1534 @Aayush-Goel-04
|
||||||
- Python 3.8 is now the minimum supported Python version #1578 @williballenthin
|
- Python 3.8 is now the minimum supported Python version #1578 @williballenthin
|
||||||
@@ -117,6 +498,7 @@ For those that use capa as a library, we've introduced some limited breaking cha
|
|||||||
- linking/runtime-linking/resolve-function-by-brute-ratel-badger-hash jakub.jozwiak@mandiant.com
|
- linking/runtime-linking/resolve-function-by-brute-ratel-badger-hash jakub.jozwiak@mandiant.com
|
||||||
|
|
||||||
### Bug Fixes
|
### Bug Fixes
|
||||||
|
|
||||||
- extractor: add a Binary Ninja test that asserts its version #1487 @xusheng6
|
- extractor: add a Binary Ninja test that asserts its version #1487 @xusheng6
|
||||||
- extractor: update Binary Ninja stack string detection after the new constant outlining feature #1473 @xusheng6
|
- extractor: update Binary Ninja stack string detection after the new constant outlining feature #1473 @xusheng6
|
||||||
- extractor: update vivisect Arch extraction #1334 @mr-tz
|
- extractor: update vivisect Arch extraction #1334 @mr-tz
|
||||||
@@ -137,6 +519,7 @@ For those that use capa as a library, we've introduced some limited breaking cha
|
|||||||
### capa explorer IDA Pro plugin
|
### capa explorer IDA Pro plugin
|
||||||
|
|
||||||
### Development
|
### Development
|
||||||
|
|
||||||
- update ATT&CK/MBC data for linting #1568 @mr-tz
|
- update ATT&CK/MBC data for linting #1568 @mr-tz
|
||||||
- log time taken to analyze each function #1290 @williballenthin
|
- log time taken to analyze each function #1290 @williballenthin
|
||||||
- tests: make fixture available via conftest.py #1592 @williballenthin
|
- tests: make fixture available via conftest.py #1592 @williballenthin
|
||||||
@@ -144,19 +527,21 @@ For those that use capa as a library, we've introduced some limited breaking cha
|
|||||||
- migrate to pyproject.toml #1301 @williballenthin
|
- migrate to pyproject.toml #1301 @williballenthin
|
||||||
- use [pre-commit](https://pre-commit.com/) to invoke linters #1579 @williballenthin
|
- use [pre-commit](https://pre-commit.com/) to invoke linters #1579 @williballenthin
|
||||||
|
|
||||||
|
|
||||||
### Raw diffs
|
### Raw diffs
|
||||||
|
|
||||||
- [capa v5.1.0...v6.0.0](https://github.com/mandiant/capa/compare/v5.1.0...v6.0.0)
|
- [capa v5.1.0...v6.0.0](https://github.com/mandiant/capa/compare/v5.1.0...v6.0.0)
|
||||||
- [capa-rules v5.1.0...v6.0.0](https://github.com/mandiant/capa-rules/compare/v5.1.0...v6.0.0)
|
- [capa-rules v5.1.0...v6.0.0](https://github.com/mandiant/capa-rules/compare/v5.1.0...v6.0.0)
|
||||||
|
|
||||||
## v5.1.0
|
## v5.1.0
|
||||||
capa version 5.1.0 adds a Protocol Buffers (protobuf) format for result documents. Additionally, the [Vector35](https://vector35.com/) team contributed a new feature extractor using Binary Ninja. Other new features are a new CLI flag to override the detected operating system, functionality to read and render existing result documents, and a output color format that's easier to read.
|
|
||||||
|
capa version 5.1.0 adds a Protocol Buffers (protobuf) format for result documents. Additionally, the [Vector35](https://vector35.com/) team contributed a new feature extractor using Binary Ninja. Other new features are a new CLI flag to override the detected operating system, functionality to read and render existing result documents, and an output color format that's easier to read.
|
||||||
|
|
||||||
Over 25 capa rules have been added and improved.
|
Over 25 capa rules have been added and improved.
|
||||||
|
|
||||||
Thanks for all the support, especially to @xusheng6, @captainGeech42, @ggold7046, @manasghandat, @ooprathamm, @linpeiyu164, @yelhamer, @HongThatCong, @naikordian, @stevemk14ebr, @emtuls, @raymondlleong, @bkojusner, @joren485, and everyone else who submitted bugs and provided feedback!
|
Thanks for all the support, especially to @xusheng6, @captainGeech42, @ggold7046, @manasghandat, @ooprathamm, @linpeiyu164, @yelhamer, @HongThatCong, @naikordian, @stevemk14ebr, @emtuls, @raymondlleong, @bkojusner, @joren485, and everyone else who submitted bugs and provided feedback!
|
||||||
|
|
||||||
### New Features
|
### New Features
|
||||||
|
|
||||||
- add protobuf format for result documents #1219 @williballenthin @mr-tz
|
- add protobuf format for result documents #1219 @williballenthin @mr-tz
|
||||||
- extractor: add Binary Ninja feature extractor @xusheng6
|
- extractor: add Binary Ninja feature extractor @xusheng6
|
||||||
- new cli flag `--os` to override auto-detected operating system for a sample @captainGeech42
|
- new cli flag `--os` to override auto-detected operating system for a sample @captainGeech42
|
||||||
@@ -194,6 +579,7 @@ Thanks for all the support, especially to @xusheng6, @captainGeech42, @ggold7046
|
|||||||
- nursery/contain-a-thread-local-storage-tls-section-in-dotnet michael.hunhoff@mandiant.com
|
- nursery/contain-a-thread-local-storage-tls-section-in-dotnet michael.hunhoff@mandiant.com
|
||||||
|
|
||||||
### Bug Fixes
|
### Bug Fixes
|
||||||
|
|
||||||
- extractor: interface of cache modified to prevent extracting file and global features multiple times @stevemk14ebr
|
- extractor: interface of cache modified to prevent extracting file and global features multiple times @stevemk14ebr
|
||||||
- extractor: removed '.dynsym' as the library name for ELF imports #1318 @stevemk14ebr
|
- extractor: removed '.dynsym' as the library name for ELF imports #1318 @stevemk14ebr
|
||||||
- extractor: fix vivisect loop detection corner case #1310 @mr-tz
|
- extractor: fix vivisect loop detection corner case #1310 @mr-tz
|
||||||
@@ -201,16 +587,18 @@ Thanks for all the support, especially to @xusheng6, @captainGeech42, @ggold7046
|
|||||||
- extractor: fix IDA and vivisect string and bytes features overlap and tests #1327 #1336 @xusheng6
|
- extractor: fix IDA and vivisect string and bytes features overlap and tests #1327 #1336 @xusheng6
|
||||||
|
|
||||||
### capa explorer IDA Pro plugin
|
### capa explorer IDA Pro plugin
|
||||||
|
|
||||||
- rule generator plugin now loads faster when jumping between functions @stevemk14ebr
|
- rule generator plugin now loads faster when jumping between functions @stevemk14ebr
|
||||||
- fix exception when plugin loaded in IDA hosted under idat #1341 @mike-hunhoff
|
- fix exception when plugin loaded in IDA hosted under idat #1341 @mike-hunhoff
|
||||||
- improve embedded PE detection performance and reduce FP potential #1344 @mike-hunhoff
|
- improve embedded PE detection performance and reduce FP potential #1344 @mike-hunhoff
|
||||||
|
|
||||||
### Raw diffs
|
### Raw diffs
|
||||||
|
|
||||||
- [capa v5.0.0...v5.1.0](https://github.com/mandiant/capa/compare/v5.0.0...v5.1.0)
|
- [capa v5.0.0...v5.1.0](https://github.com/mandiant/capa/compare/v5.0.0...v5.1.0)
|
||||||
- [capa-rules v5.0.0...v5.1.0](https://github.com/mandiant/capa-rules/compare/v5.0.0...v5.1.0)
|
- [capa-rules v5.0.0...v5.1.0](https://github.com/mandiant/capa-rules/compare/v5.0.0...v5.1.0)
|
||||||
|
|
||||||
|
|
||||||
## v5.0.0 (2023-02-08)
|
## v5.0.0 (2023-02-08)
|
||||||
|
|
||||||
This capa version comes with major improvements and additions to better handle .NET binaries. To showcase this we've updated and added over 30 .NET rules.
|
This capa version comes with major improvements and additions to better handle .NET binaries. To showcase this we've updated and added over 30 .NET rules.
|
||||||
|
|
||||||
Additionally, capa now caches its rule set for better performance. The capa explorer also caches its analysis results, so that multiple IDA Pro or plugin invocations don't need to repeat the same analysis.
|
Additionally, capa now caches its rule set for better performance. The capa explorer also caches its analysis results, so that multiple IDA Pro or plugin invocations don't need to repeat the same analysis.
|
||||||
@@ -222,6 +610,7 @@ Other improvements to highlight include better ELF OS detection, various renderi
|
|||||||
Thanks for all the support, especially to @jsoref, @bkojusner, @edeca, @richardweiss80, @joren485, @ryantxu1, @mwilliams31, @anushkavirgaonkar, @MalwareMechanic, @Still34, @dzbeck, @johnk3r, and everyone else who submitted bugs and provided feedback!
|
Thanks for all the support, especially to @jsoref, @bkojusner, @edeca, @richardweiss80, @joren485, @ryantxu1, @mwilliams31, @anushkavirgaonkar, @MalwareMechanic, @Still34, @dzbeck, @johnk3r, and everyone else who submitted bugs and provided feedback!
|
||||||
|
|
||||||
### New Features
|
### New Features
|
||||||
|
|
||||||
- verify rule metadata format on load #1160 @mr-tz
|
- verify rule metadata format on load #1160 @mr-tz
|
||||||
- dotnet: emit property features #1168 @anushkavirgaonkar
|
- dotnet: emit property features #1168 @anushkavirgaonkar
|
||||||
- dotnet: emit API features for objects created via the newobj instruction #1186 @mike-hunhoff
|
- dotnet: emit API features for objects created via the newobj instruction #1186 @mike-hunhoff
|
||||||
@@ -236,6 +625,7 @@ Thanks for all the support, especially to @jsoref, @bkojusner, @edeca, @richardw
|
|||||||
- update ATT&CK/MBC data for linting #1297 @mr-tz
|
- update ATT&CK/MBC data for linting #1297 @mr-tz
|
||||||
|
|
||||||
### Breaking Changes
|
### Breaking Changes
|
||||||
|
|
||||||
- remove SMDA backend #1062 @williballenthin
|
- remove SMDA backend #1062 @williballenthin
|
||||||
- error return codes are now positive numbers #1269 @mr-tz
|
- error return codes are now positive numbers #1269 @mr-tz
|
||||||
|
|
||||||
@@ -315,6 +705,7 @@ Thanks for all the support, especially to @jsoref, @bkojusner, @edeca, @richardw
|
|||||||
- nursery/unmanaged-call-via-dynamic-pinvoke-in-dotnet michael.hunhoff@mandiant.com
|
- nursery/unmanaged-call-via-dynamic-pinvoke-in-dotnet michael.hunhoff@mandiant.com
|
||||||
|
|
||||||
### Bug Fixes
|
### Bug Fixes
|
||||||
|
|
||||||
- render: convert feature attributes to aliased dictionary for vverbose #1152 @mike-hunhoff
|
- render: convert feature attributes to aliased dictionary for vverbose #1152 @mike-hunhoff
|
||||||
- decouple Token dependency / extractor and features #1139 @mr-tz
|
- decouple Token dependency / extractor and features #1139 @mr-tz
|
||||||
- update pydantic model to guarantee type coercion #1176 @mike-hunhoff
|
- update pydantic model to guarantee type coercion #1176 @mike-hunhoff
|
||||||
@@ -333,6 +724,7 @@ Thanks for all the support, especially to @jsoref, @bkojusner, @edeca, @richardw
|
|||||||
- extractor: don't extract byte features for strings #1293 @mr-tz
|
- extractor: don't extract byte features for strings #1293 @mr-tz
|
||||||
|
|
||||||
### capa explorer IDA Pro plugin
|
### capa explorer IDA Pro plugin
|
||||||
|
|
||||||
- fix: display instruction items #1154 @mr-tz
|
- fix: display instruction items #1154 @mr-tz
|
||||||
- fix: accept only plaintext pasted content #1194 @williballenthin
|
- fix: accept only plaintext pasted content #1194 @williballenthin
|
||||||
- fix: UnboundLocalError #1217 @williballenthin
|
- fix: UnboundLocalError #1217 @williballenthin
|
||||||
@@ -347,27 +739,30 @@ Thanks for all the support, especially to @jsoref, @bkojusner, @edeca, @richardw
|
|||||||
- cache capa results across IDA sessions #1279 @mr-tz
|
- cache capa results across IDA sessions #1279 @mr-tz
|
||||||
|
|
||||||
### Raw diffs
|
### Raw diffs
|
||||||
|
|
||||||
- [capa v4.0.1...v5.0.0](https://github.com/mandiant/capa/compare/v4.0.1...v5.0.0)
|
- [capa v4.0.1...v5.0.0](https://github.com/mandiant/capa/compare/v4.0.1...v5.0.0)
|
||||||
- [capa-rules v4.0.1...v5.0.0](https://github.com/mandiant/capa-rules/compare/v4.0.1...v5.0.0)
|
- [capa-rules v4.0.1...v5.0.0](https://github.com/mandiant/capa-rules/compare/v4.0.1...v5.0.0)
|
||||||
|
|
||||||
|
|
||||||
## v4.0.1 (2022-08-15)
|
## v4.0.1 (2022-08-15)
|
||||||
|
|
||||||
Some rules contained invalid metadata fields that caused an error when rendering rule hits. We've updated all rules and enhanced the rule linter to catch such issues.
|
Some rules contained invalid metadata fields that caused an error when rendering rule hits. We've updated all rules and enhanced the rule linter to catch such issues.
|
||||||
|
|
||||||
### New Rules (1)
|
### New Rules (1)
|
||||||
|
|
||||||
- anti-analysis/obfuscation/obfuscated-with-vs-obfuscation jakub.jozwiak@mandiant.com
|
- anti-analysis/obfuscation/obfuscated-with-vs-obfuscation jakub.jozwiak@mandiant.com
|
||||||
|
|
||||||
|
|
||||||
### Bug Fixes
|
### Bug Fixes
|
||||||
|
|
||||||
- linter: use pydantic to validate rule metadata #1141 @mike-hunhoff
|
- linter: use pydantic to validate rule metadata #1141 @mike-hunhoff
|
||||||
- build binaries using PyInstaller no longer overwrites functions in version.py #1136 @mr-tz
|
- build binaries using PyInstaller no longer overwrites functions in version.py #1136 @mr-tz
|
||||||
|
|
||||||
### Raw diffs
|
### Raw diffs
|
||||||
|
|
||||||
- [capa v4.0.0...v4.0.1](https://github.com/mandiant/capa/compare/v4.0.0...v4.0.1)
|
- [capa v4.0.0...v4.0.1](https://github.com/mandiant/capa/compare/v4.0.0...v4.0.1)
|
||||||
- [capa-rules v4.0.0...v4.0.1](https://github.com/mandiant/capa-rules/compare/v4.0.0...v4.0.1)
|
- [capa-rules v4.0.0...v4.0.1](https://github.com/mandiant/capa-rules/compare/v4.0.0...v4.0.1)
|
||||||
|
|
||||||
## v4.0.0 (2022-08-10)
|
## v4.0.0 (2022-08-10)
|
||||||
|
|
||||||
Version 4 adds support for analyzing .NET executables. capa will autodetect .NET modules, or you can explicitly invoke the new feature extractor via `--format dotnet`. We've also extended the rule syntax for .NET features including `namespace` and `class`.
|
Version 4 adds support for analyzing .NET executables. capa will autodetect .NET modules, or you can explicitly invoke the new feature extractor via `--format dotnet`. We've also extended the rule syntax for .NET features including `namespace` and `class`.
|
||||||
|
|
||||||
Additionally, new `instruction` scope and `operand` features enable users to create more explicit rules. These features are not backwards compatible. We removed the previously used `/x32` and `/x64` flavors of number and operand features.
|
Additionally, new `instruction` scope and `operand` features enable users to create more explicit rules. These features are not backwards compatible. We removed the previously used `/x32` and `/x64` flavors of number and operand features.
|
||||||
@@ -376,9 +771,9 @@ We updated 49 existing rules and added 22 new rules leveraging these new feature
|
|||||||
|
|
||||||
More breaking changes include updates to the JSON results document, freeze file format schema (now format version v2), and the internal handling of addresses.
|
More breaking changes include updates to the JSON results document, freeze file format schema (now format version v2), and the internal handling of addresses.
|
||||||
|
|
||||||
Thanks for all the support, especially to @htnhan, @jtothej, @sara-rn, @anushkavirgaonkar, and @_re_fox!
|
Thanks for all the support, especially to @htnhan, @jtothej, @sara-rn, @anushkavirgaonkar, and @\_re_fox!
|
||||||
|
|
||||||
*Deprecation warning: v4.0 will be the last capa version to support the SMDA backend.*
|
_Deprecation warning: v4.0 will be the last capa version to support the SMDA backend._
|
||||||
|
|
||||||
### New Features
|
### New Features
|
||||||
|
|
||||||
@@ -419,11 +814,11 @@ Deprecation notice: as described in [#937](https://github.com/mandiant/capa/issu
|
|||||||
- anti-analysis/packer/huan/packed-with-huan jakub.jozwiak@mandiant.com
|
- anti-analysis/packer/huan/packed-with-huan jakub.jozwiak@mandiant.com
|
||||||
- nursery/execute-dotnet-assembly anushka.virgaonkar@mandiant.com
|
- nursery/execute-dotnet-assembly anushka.virgaonkar@mandiant.com
|
||||||
- nursery/invoke-dotnet-assembly-method anushka.virgaonkar@mandiant.com
|
- nursery/invoke-dotnet-assembly-method anushka.virgaonkar@mandiant.com
|
||||||
- collection/screenshot/capture-screenshot-via-keybd-event @_re_fox
|
- collection/screenshot/capture-screenshot-via-keybd-event @\_re_fox
|
||||||
- collection/browser/gather-chrome-based-browser-login-information @_re_fox
|
- collection/browser/gather-chrome-based-browser-login-information @\_re_fox
|
||||||
- nursery/power-down-monitor michael.hunhoff@mandiant.com
|
- nursery/power-down-monitor michael.hunhoff@mandiant.com
|
||||||
- nursery/hash-data-using-aphash @_re_fox
|
- nursery/hash-data-using-aphash @\_re_fox
|
||||||
- nursery/hash-data-using-jshash @_re_fox
|
- nursery/hash-data-using-jshash @\_re_fox
|
||||||
- host-interaction/file-system/files/list/enumerate-files-on-windows moritz.raabe@mandiant.com anushka.virgaonkar@mandiant.com
|
- host-interaction/file-system/files/list/enumerate-files-on-windows moritz.raabe@mandiant.com anushka.virgaonkar@mandiant.com
|
||||||
- nursery/check-clipboard-data anushka.virgaonkar@mandiant.com
|
- nursery/check-clipboard-data anushka.virgaonkar@mandiant.com
|
||||||
- nursery/clear-clipboard-data anushka.virgaonkar@mandiant.com
|
- nursery/clear-clipboard-data anushka.virgaonkar@mandiant.com
|
||||||
@@ -435,16 +830,18 @@ Deprecation notice: as described in [#937](https://github.com/mandiant/capa/issu
|
|||||||
- nursery/send-keystrokes anushka.virgaonkar@mandiant.com
|
- nursery/send-keystrokes anushka.virgaonkar@mandiant.com
|
||||||
- nursery/send-request-in-dotnet anushka.virgaonakr@mandiant.com
|
- nursery/send-request-in-dotnet anushka.virgaonakr@mandiant.com
|
||||||
- nursery/terminate-process-by-name-in-dotnet anushka.virgaonkar@mandiant.com
|
- nursery/terminate-process-by-name-in-dotnet anushka.virgaonkar@mandiant.com
|
||||||
- nursery/hash-data-using-rshash @_re_fox
|
- nursery/hash-data-using-rshash @\_re_fox
|
||||||
- persistence/authentication-process/act-as-credential-manager-dll jakub.jozwiak@mandiant.com
|
- persistence/authentication-process/act-as-credential-manager-dll jakub.jozwiak@mandiant.com
|
||||||
- persistence/authentication-process/act-as-password-filter-dll jakub.jozwiak@mandiant.com
|
- persistence/authentication-process/act-as-password-filter-dll jakub.jozwiak@mandiant.com
|
||||||
|
|
||||||
### Bug Fixes
|
### Bug Fixes
|
||||||
- improve handling _ prefix compile/link artifact #924 @mike-hunhoff
|
|
||||||
|
- improve handling \_ prefix compile/link artifact #924 @mike-hunhoff
|
||||||
- better detect OS in ELF samples #988 @williballenthin
|
- better detect OS in ELF samples #988 @williballenthin
|
||||||
- display number feature zero in vverbose #1097 @mike-hunhoff
|
- display number feature zero in vverbose #1097 @mike-hunhoff
|
||||||
|
|
||||||
### capa explorer IDA Pro plugin
|
### capa explorer IDA Pro plugin
|
||||||
|
|
||||||
- improve file format extraction #918 @mike-hunhoff
|
- improve file format extraction #918 @mike-hunhoff
|
||||||
- remove decorators added by IDA to ELF imports #919 @mike-hunhoff
|
- remove decorators added by IDA to ELF imports #919 @mike-hunhoff
|
||||||
- bug fixes for Address abstraction #1091 @mike-hunhoff
|
- bug fixes for Address abstraction #1091 @mike-hunhoff
|
||||||
@@ -452,10 +849,12 @@ Deprecation notice: as described in [#937](https://github.com/mandiant/capa/issu
|
|||||||
### Development
|
### Development
|
||||||
|
|
||||||
### Raw diffs
|
### Raw diffs
|
||||||
|
|
||||||
- [capa v3.2.0...v4.0.0](https://github.com/mandiant/capa/compare/v3.2.0...master)
|
- [capa v3.2.0...v4.0.0](https://github.com/mandiant/capa/compare/v3.2.0...master)
|
||||||
- [capa-rules v3.2.0...v4.0.0](https://github.com/mandiant/capa-rules/compare/v3.2.0...master)
|
- [capa-rules v3.2.0...v4.0.0](https://github.com/mandiant/capa-rules/compare/v3.2.0...master)
|
||||||
|
|
||||||
## v3.2.1 (2022-06-06)
|
## v3.2.1 (2022-06-06)
|
||||||
|
|
||||||
This out-of-band release bumps the SMDA dependency version to enable installation on Python 3.10.
|
This out-of-band release bumps the SMDA dependency version to enable installation on Python 3.10.
|
||||||
|
|
||||||
### Bug Fixes
|
### Bug Fixes
|
||||||
@@ -463,10 +862,12 @@ This out-of-band release bumps the SMDA dependency version to enable installatio
|
|||||||
- update SMDA dependency @mike-hunhoff #922
|
- update SMDA dependency @mike-hunhoff #922
|
||||||
|
|
||||||
### Raw diffs
|
### Raw diffs
|
||||||
|
|
||||||
- [capa v3.2.0...v3.2.1](https://github.com/mandiant/capa/compare/v3.2.0...v3.2.1)
|
- [capa v3.2.0...v3.2.1](https://github.com/mandiant/capa/compare/v3.2.0...v3.2.1)
|
||||||
- [capa-rules v3.2.0...v3.2.1](https://github.com/mandiant/capa-rules/compare/v3.2.0...v3.2.1)
|
- [capa-rules v3.2.0...v3.2.1](https://github.com/mandiant/capa-rules/compare/v3.2.0...v3.2.1)
|
||||||
|
|
||||||
## v3.2.0 (2022-03-03)
|
## v3.2.0 (2022-03-03)
|
||||||
|
|
||||||
This release adds a new characteristic `characteristic: call $+5` enabling users to create more explicit rules. The linter now also validates ATT&CK and MBC categories. Additionally, many dependencies, including the vivisect backend, have been updated.
|
This release adds a new characteristic `characteristic: call $+5` enabling users to create more explicit rules. The linter now also validates ATT&CK and MBC categories. Additionally, many dependencies, including the vivisect backend, have been updated.
|
||||||
|
|
||||||
One rule has been added and many more have been improved.
|
One rule has been added and many more have been improved.
|
||||||
@@ -488,10 +889,12 @@ Thanks for all the support, especially to @kn0wl3dge and first time contributor
|
|||||||
- elf: fix OS detection for Linux kernel modules #867 @williballenthin
|
- elf: fix OS detection for Linux kernel modules #867 @williballenthin
|
||||||
|
|
||||||
### Raw diffs
|
### Raw diffs
|
||||||
|
|
||||||
- [capa v3.1.0...v3.2.0](https://github.com/mandiant/capa/compare/v3.1.0...v3.2.0)
|
- [capa v3.1.0...v3.2.0](https://github.com/mandiant/capa/compare/v3.1.0...v3.2.0)
|
||||||
- [capa-rules v3.1.0...v3.2.0](https://github.com/mandiant/capa-rules/compare/v3.1.0...v3.2.0)
|
- [capa-rules v3.1.0...v3.2.0](https://github.com/mandiant/capa-rules/compare/v3.1.0...v3.2.0)
|
||||||
|
|
||||||
## v3.1.0 (2022-01-10)
|
## v3.1.0 (2022-01-10)
|
||||||
|
|
||||||
This release improves the performance of capa while also adding 23 new rules and many code quality enhancements. We profiled capa's CPU usage and optimized the way that it matches rules, such as by short circuiting when appropriate. According to our testing, the matching phase is approximately 66% faster than v3.0.3! We also added support for Python 3.10, aarch64 builds, and additional MAEC metadata in the rule headers.
|
This release improves the performance of capa while also adding 23 new rules and many code quality enhancements. We profiled capa's CPU usage and optimized the way that it matches rules, such as by short circuiting when appropriate. According to our testing, the matching phase is approximately 66% faster than v3.0.3! We also added support for Python 3.10, aarch64 builds, and additional MAEC metadata in the rule headers.
|
||||||
|
|
||||||
This release adds 23 new rules, including nine by Jakub Jozwiak of Mandiant. @ryantxu1 and @dzbeck updated the ATT&CK and MBC mappings for many rules. Thank you!
|
This release adds 23 new rules, including nine by Jakub Jozwiak of Mandiant. @ryantxu1 and @dzbeck updated the ATT&CK and MBC mappings for many rules. Thank you!
|
||||||
@@ -502,7 +905,6 @@ And as always, welcome first time contributors!
|
|||||||
- @jtothej
|
- @jtothej
|
||||||
- @cl30
|
- @cl30
|
||||||
|
|
||||||
|
|
||||||
### New Features
|
### New Features
|
||||||
|
|
||||||
- engine: short circuit logic nodes for better performance #824 @williballenthin
|
- engine: short circuit logic nodes for better performance #824 @williballenthin
|
||||||
@@ -561,23 +963,24 @@ And as always, welcome first time contributors!
|
|||||||
- show features script: add backend flag #430 @kn0wl3dge
|
- show features script: add backend flag #430 @kn0wl3dge
|
||||||
|
|
||||||
### Raw diffs
|
### Raw diffs
|
||||||
|
|
||||||
- [capa v3.0.3...v3.1.0](https://github.com/mandiant/capa/compare/v3.0.3...v3.1.0)
|
- [capa v3.0.3...v3.1.0](https://github.com/mandiant/capa/compare/v3.0.3...v3.1.0)
|
||||||
- [capa-rules v3.0.3...v3.1.0](https://github.com/mandiant/capa-rules/compare/v3.0.3...v3.1.0)
|
- [capa-rules v3.0.3...v3.1.0](https://github.com/mandiant/capa-rules/compare/v3.0.3...v3.1.0)
|
||||||
|
|
||||||
|
|
||||||
## v3.0.3 (2021-10-27)
|
## v3.0.3 (2021-10-27)
|
||||||
|
|
||||||
This is primarily a rule maintenance release:
|
This is primarily a rule maintenance release:
|
||||||
|
|
||||||
- eight new rules, including all relevant techniques from [ATT&CK v10](https://medium.com/mitre-attack/introducing-attack-v10-7743870b37e3), and
|
- eight new rules, including all relevant techniques from [ATT&CK v10](https://medium.com/mitre-attack/introducing-attack-v10-7743870b37e3), and
|
||||||
- two rules removed, due to the prevalence of false positives
|
- two rules removed, due to the prevalence of false positives
|
||||||
|
|
||||||
We've also tweaked the status codes returned by capa.exe to be more specific and added a bit more metadata to the JSON output format.
|
We've also tweaked the status codes returned by capa.exe to be more specific and added a bit more metadata to the JSON output format.
|
||||||
|
|
||||||
As always, welcome first time contributors!
|
As always, welcome first time contributors!
|
||||||
|
|
||||||
- still@teamt5.org
|
- still@teamt5.org
|
||||||
- zander.work@mandiant.com
|
- zander.work@mandiant.com
|
||||||
|
|
||||||
|
|
||||||
### New Features
|
### New Features
|
||||||
|
|
||||||
- show in which function a BB match is #130 @williballenthin
|
- show in which function a BB match is #130 @williballenthin
|
||||||
@@ -595,6 +998,7 @@ As always, welcome first time contributors!
|
|||||||
- targeting/language/identify-system-language-via-api william.ballenthin@mandiant.com
|
- targeting/language/identify-system-language-via-api william.ballenthin@mandiant.com
|
||||||
|
|
||||||
## Removed rules (2)
|
## Removed rules (2)
|
||||||
|
|
||||||
- load-code/pe/parse-pe-exports: too many false positives in unrelated structure accesses
|
- load-code/pe/parse-pe-exports: too many false positives in unrelated structure accesses
|
||||||
- anti-analysis/anti-vm/vm-detection/execute-anti-vm-instructions: too many false positives in junk code
|
- anti-analysis/anti-vm/vm-detection/execute-anti-vm-instructions: too many false positives in junk code
|
||||||
|
|
||||||
@@ -603,6 +1007,7 @@ As always, welcome first time contributors!
|
|||||||
- update references from FireEye to Mandiant
|
- update references from FireEye to Mandiant
|
||||||
|
|
||||||
### Raw diffs
|
### Raw diffs
|
||||||
|
|
||||||
- [capa v3.0.2...v3.0.3](https://github.com/fireeye/capa/compare/v3.0.2...v3.0.3)
|
- [capa v3.0.2...v3.0.3](https://github.com/fireeye/capa/compare/v3.0.2...v3.0.3)
|
||||||
- [capa-rules v3.0.2...v3.0.3](https://github.com/fireeye/capa-rules/compare/v3.0.2...v3.0.3)
|
- [capa-rules v3.0.2...v3.0.3](https://github.com/fireeye/capa-rules/compare/v3.0.2...v3.0.3)
|
||||||
|
|
||||||
@@ -615,6 +1020,7 @@ This release fixes an issue with the standalone executables built with PyInstall
|
|||||||
- fix bug in PyInstaller config preventing ELF analysis #795 @mr-tz
|
- fix bug in PyInstaller config preventing ELF analysis #795 @mr-tz
|
||||||
|
|
||||||
### Raw diffs
|
### Raw diffs
|
||||||
|
|
||||||
- [capa v3.0.1...v3.0.2](https://github.com/fireeye/capa/compare/v3.0.1...v3.0.2)
|
- [capa v3.0.1...v3.0.2](https://github.com/fireeye/capa/compare/v3.0.1...v3.0.2)
|
||||||
- [capa-rules v3.0.1...v3.0.2](https://github.com/fireeye/capa-rules/compare/v3.0.1...v3.0.2)
|
- [capa-rules v3.0.1...v3.0.2](https://github.com/fireeye/capa-rules/compare/v3.0.1...v3.0.2)
|
||||||
|
|
||||||
@@ -629,6 +1035,7 @@ Thanks to the community for highlighting issues and analysis misses. Your feedba
|
|||||||
- fix many underlying bugs in vivisect analysis and update to version v1.0.5 #786 @williballenthin
|
- fix many underlying bugs in vivisect analysis and update to version v1.0.5 #786 @williballenthin
|
||||||
|
|
||||||
### Raw diffs
|
### Raw diffs
|
||||||
|
|
||||||
- [capa v3.0.0...v3.0.1](https://github.com/fireeye/capa/compare/v3.0.0...v3.0.1)
|
- [capa v3.0.0...v3.0.1](https://github.com/fireeye/capa/compare/v3.0.0...v3.0.1)
|
||||||
- [capa-rules v3.0.0...v3.0.1](https://github.com/fireeye/capa-rules/compare/v3.0.0...v3.0.1)
|
- [capa-rules v3.0.0...v3.0.1](https://github.com/fireeye/capa-rules/compare/v3.0.0...v3.0.1)
|
||||||
|
|
||||||
@@ -637,6 +1044,7 @@ Thanks to the community for highlighting issues and analysis misses. Your feedba
|
|||||||
We are excited to announce version 3.0! :tada:
|
We are excited to announce version 3.0! :tada:
|
||||||
|
|
||||||
capa 3.0:
|
capa 3.0:
|
||||||
|
|
||||||
- adds support for ELF files targeting Linux thanks to [Intezer](https://www.intezer.com/)
|
- adds support for ELF files targeting Linux thanks to [Intezer](https://www.intezer.com/)
|
||||||
- adds new features to specify OS, CPU architecture, and file format
|
- adds new features to specify OS, CPU architecture, and file format
|
||||||
- fixes a few bugs that may have led to false negatives (missed capabilities) in older versions
|
- fixes a few bugs that may have led to false negatives (missed capabilities) in older versions
|
||||||
@@ -645,6 +1053,7 @@ capa 3.0:
|
|||||||
A huge thanks to everyone who submitted issues, provided feedback, and contributed code and rules.
|
A huge thanks to everyone who submitted issues, provided feedback, and contributed code and rules.
|
||||||
Special acknowledgement to @Adir-Shemesh and @TcM1911 of [Intezer](https://www.intezer.com/) for contributing the code to enable ELF support.
|
Special acknowledgement to @Adir-Shemesh and @TcM1911 of [Intezer](https://www.intezer.com/) for contributing the code to enable ELF support.
|
||||||
Also, welcome first time contributors:
|
Also, welcome first time contributors:
|
||||||
|
|
||||||
- @jaredscottwilson
|
- @jaredscottwilson
|
||||||
- @cdong1012
|
- @cdong1012
|
||||||
- @jlepore-fe
|
- @jlepore-fe
|
||||||
@@ -752,14 +1161,15 @@ Also, welcome first time contributors:
|
|||||||
### Development
|
### Development
|
||||||
|
|
||||||
### Raw diffs
|
### Raw diffs
|
||||||
|
|
||||||
- [capa v2.0.0...v3.0.0](https://github.com/mandiant/capa/compare/v2.0.0...v3.0.0)
|
- [capa v2.0.0...v3.0.0](https://github.com/mandiant/capa/compare/v2.0.0...v3.0.0)
|
||||||
- [capa-rules v2.0.0...v3.0.0](https://github.com/mandiant/capa-rules/compare/v2.0.0...v3.0.0)
|
- [capa-rules v2.0.0...v3.0.0](https://github.com/mandiant/capa-rules/compare/v2.0.0...v3.0.0)
|
||||||
|
|
||||||
|
|
||||||
## v2.0.0 (2021-07-19)
|
## v2.0.0 (2021-07-19)
|
||||||
|
|
||||||
We are excited to announce version 2.0! :tada:
|
We are excited to announce version 2.0! :tada:
|
||||||
capa 2.0:
|
capa 2.0:
|
||||||
|
|
||||||
- enables anyone to contribute rules more easily
|
- enables anyone to contribute rules more easily
|
||||||
- is the first Python 3 ONLY version
|
- is the first Python 3 ONLY version
|
||||||
- provides more concise and relevant result via identification of library functions using FLIRT
|
- provides more concise and relevant result via identification of library functions using FLIRT
|
||||||
@@ -769,7 +1179,6 @@ capa 2.0:
|
|||||||
|
|
||||||
A huge thanks to everyone who submitted issues, provided feedback, and contributed code and rules. Many colleagues across dozens of organizations have volunteered their experience to improve this tool! :heart:
|
A huge thanks to everyone who submitted issues, provided feedback, and contributed code and rules. Many colleagues across dozens of organizations have volunteered their experience to improve this tool! :heart:
|
||||||
|
|
||||||
|
|
||||||
### New Features
|
### New Features
|
||||||
|
|
||||||
- rules: update ATT&CK and MBC mappings https://github.com/mandiant/capa-rules/pull/317 @williballenthin
|
- rules: update ATT&CK and MBC mappings https://github.com/mandiant/capa-rules/pull/317 @williballenthin
|
||||||
@@ -896,6 +1305,7 @@ A huge thanks to everyone who submitted issues, provided feedback, and contribut
|
|||||||
- main: do not process non-PE files even when --format explicitly provided #664 @mr-tz
|
- main: do not process non-PE files even when --format explicitly provided #664 @mr-tz
|
||||||
|
|
||||||
### capa explorer IDA Pro plugin
|
### capa explorer IDA Pro plugin
|
||||||
|
|
||||||
- explorer: IDA 7.6 support #497 @williballenthin
|
- explorer: IDA 7.6 support #497 @williballenthin
|
||||||
- explorer: explain how to install IDA 7.6 patch to enable the plugin #528 @williballenthin
|
- explorer: explain how to install IDA 7.6 patch to enable the plugin #528 @williballenthin
|
||||||
- explorer: document IDA 7.6sp1 as alternative to the patch #536 @Ana06
|
- explorer: document IDA 7.6sp1 as alternative to the patch #536 @Ana06
|
||||||
@@ -916,10 +1326,10 @@ A huge thanks to everyone who submitted issues, provided feedback, and contribut
|
|||||||
### Raw diffs
|
### Raw diffs
|
||||||
|
|
||||||
<!-- The diff uses v1.6.1 because master doesn't include v1.6.2 and v1.6.3 -->
|
<!-- The diff uses v1.6.1 because master doesn't include v1.6.2 and v1.6.3 -->
|
||||||
|
|
||||||
- [capa v1.6.1...v2.0.0](https://github.com/mandiant/capa/compare/v1.6.1...v2.0.0)
|
- [capa v1.6.1...v2.0.0](https://github.com/mandiant/capa/compare/v1.6.1...v2.0.0)
|
||||||
- [capa-rules v1.6.1...v2.0.0](https://github.com/mandiant/capa-rules/compare/v1.6.1...v2.0.0)
|
- [capa-rules v1.6.1...v2.0.0](https://github.com/mandiant/capa-rules/compare/v1.6.1...v2.0.0)
|
||||||
|
|
||||||
|
|
||||||
## v1.6.3 (2021-04-29)
|
## v1.6.3 (2021-04-29)
|
||||||
|
|
||||||
This release adds IDA 7.6 support to capa.
|
This release adds IDA 7.6 support to capa.
|
||||||
@@ -932,7 +1342,6 @@ This release adds IDA 7.6 support to capa.
|
|||||||
|
|
||||||
- [capa v1.6.2...v1.6.3](https://github.com/mandiant/capa/compare/v1.6.2...v1.6.3)
|
- [capa v1.6.2...v1.6.3](https://github.com/mandiant/capa/compare/v1.6.2...v1.6.3)
|
||||||
|
|
||||||
|
|
||||||
## v1.6.2 (2021-04-13)
|
## v1.6.2 (2021-04-13)
|
||||||
|
|
||||||
This release backports a fix to capa 1.6: The Windows binary was built with Python 3.9 which doesn't support Windows 7.
|
This release backports a fix to capa 1.6: The Windows binary was built with Python 3.9 which doesn't support Windows 7.
|
||||||
@@ -945,7 +1354,6 @@ This release backports a fix to capa 1.6: The Windows binary was built with Pyth
|
|||||||
|
|
||||||
- [capa v1.6.1...v1.6.2](https://github.com/mandiant/capa/compare/v1.6.1...v1.6.2)
|
- [capa v1.6.1...v1.6.2](https://github.com/mandiant/capa/compare/v1.6.1...v1.6.2)
|
||||||
|
|
||||||
|
|
||||||
## v1.6.1 (2021-04-07)
|
## v1.6.1 (2021-04-07)
|
||||||
|
|
||||||
This release includes several bug fixes, such as a vivisect issue that prevented capa from working on Windows with Python 3. It also adds 17 new rules and a bunch of improvements in the rules and IDA rule generator. We appreciate everyone who opened issues, provided feedback, and contributed code and rules.
|
This release includes several bug fixes, such as a vivisect issue that prevented capa from working on Windows with Python 3. It also adds 17 new rules and a bunch of improvements in the rules and IDA rule generator. We appreciate everyone who opened issues, provided feedback, and contributed code and rules.
|
||||||
@@ -1014,7 +1422,6 @@ This release includes several bug fixes, such as a vivisect issue that prevented
|
|||||||
- [capa v1.6.0...v1.6.1](https://github.com/mandiant/capa/compare/v1.6.0...v1.6.1)
|
- [capa v1.6.0...v1.6.1](https://github.com/mandiant/capa/compare/v1.6.0...v1.6.1)
|
||||||
- [capa-rules v1.6.0...v1.6.1](https://github.com/mandiant/capa-rules/compare/v1.6.0...v1.6.1)
|
- [capa-rules v1.6.0...v1.6.1](https://github.com/mandiant/capa-rules/compare/v1.6.0...v1.6.1)
|
||||||
|
|
||||||
|
|
||||||
## v1.6.0 (2021-03-09)
|
## v1.6.0 (2021-03-09)
|
||||||
|
|
||||||
This release adds the capa explorer rule generator plugin for IDA Pro, vivisect support for Python 3 and 12 new rules. We appreciate everyone who opened issues, provided feedback, and contributed code and rules. Thank you also to the vivisect development team (@rakuy0, @atlas0fd00m) for the Python 3 support (`vivisect==1.0.0`) and the fixes for Python 2 (`vivisect==0.2.1`).
|
This release adds the capa explorer rule generator plugin for IDA Pro, vivisect support for Python 3 and 12 new rules. We appreciate everyone who opened issues, provided feedback, and contributed code and rules. Thank you also to the vivisect development team (@rakuy0, @atlas0fd00m) for the Python 3 support (`vivisect==1.0.0`) and the fixes for Python 2 (`vivisect==0.2.1`).
|
||||||
@@ -1030,6 +1437,7 @@ The capa explorer IDA plugin now helps you quickly build new capa rules using fe
|
|||||||
This version of capa adds Python 3 support in vivisect. Note that `.viv` files (generated by vivisect) are not compatible between Python 2 and Python 3. When updating to Python 3 you need to delete all the `.viv` files for capa to work.
|
This version of capa adds Python 3 support in vivisect. Note that `.viv` files (generated by vivisect) are not compatible between Python 2 and Python 3. When updating to Python 3 you need to delete all the `.viv` files for capa to work.
|
||||||
|
|
||||||
If you get the following error (or a similar one), you most likely need to delete `.viv` files:
|
If you get the following error (or a similar one), you most likely need to delete `.viv` files:
|
||||||
|
|
||||||
```
|
```
|
||||||
UnicodeDecodeError: 'ascii' codec can't decode byte 0x90 in position 2: ordinal not in range(128)
|
UnicodeDecodeError: 'ascii' codec can't decode byte 0x90 in position 2: ordinal not in range(128)
|
||||||
```
|
```
|
||||||
@@ -1086,7 +1494,6 @@ If you have workflows that rely on the Python 2 version and need future maintena
|
|||||||
- [capa v1.5.1...v1.6.0](https://github.com/mandiant/capa/compare/v1.5.1...v1.6.0)
|
- [capa v1.5.1...v1.6.0](https://github.com/mandiant/capa/compare/v1.5.1...v1.6.0)
|
||||||
- [capa-rules v1.5.1...v1.6.0](https://github.com/mandiant/capa-rules/compare/v1.5.1...v1.6.0)
|
- [capa-rules v1.5.1...v1.6.0](https://github.com/mandiant/capa-rules/compare/v1.5.1...v1.6.0)
|
||||||
|
|
||||||
|
|
||||||
## v1.5.1 (2021-02-09)
|
## v1.5.1 (2021-02-09)
|
||||||
|
|
||||||
This release fixes the version number that we forgot to update for v1.5.0 (therefore, v1.5.0 was not published to pypi). It also includes 1 new rule and some rule improvements.
|
This release fixes the version number that we forgot to update for v1.5.0 (therefore, v1.5.0 was not published to pypi). It also includes 1 new rule and some rule improvements.
|
||||||
@@ -1100,7 +1507,6 @@ This release fixes the version number that we forgot to update for v1.5.0 (there
|
|||||||
- [capa v1.5.0...v1.5.1](https://github.com/mandiant/capa/compare/v1.5.1...v1.6.0)
|
- [capa v1.5.0...v1.5.1](https://github.com/mandiant/capa/compare/v1.5.1...v1.6.0)
|
||||||
- [capa-rules v1.5.0...v1.5.1](https://github.com/mandiant/capa-rules/compare/v1.5.1...v1.6.0)
|
- [capa-rules v1.5.0...v1.5.1](https://github.com/mandiant/capa-rules/compare/v1.5.1...v1.6.0)
|
||||||
|
|
||||||
|
|
||||||
## v1.5.0 (2021-02-05)
|
## v1.5.0 (2021-02-05)
|
||||||
|
|
||||||
This release brings support for running capa under Python 3 via [SMDA](https://github.com/danielplohmann/smda), more thorough CI testing and linting, better extraction of strings and byte features, and 50 (!) new rules. We appreciate everyone who opened issues, provided feedback, and contributed code and rules. A special shout out to the following new project contributors:
|
This release brings support for running capa under Python 3 via [SMDA](https://github.com/danielplohmann/smda), more thorough CI testing and linting, better extraction of strings and byte features, and 50 (!) new rules. We appreciate everyone who opened issues, provided feedback, and contributed code and rules. A special shout out to the following new project contributors:
|
||||||
@@ -1115,7 +1521,6 @@ This release brings support for running capa under Python 3 via [SMDA](https://g
|
|||||||
|
|
||||||
Download a standalone binary below and checkout the readme [here on GitHub](https://github.com/mandiant/capa/). Report issues on our [issue tracker](https://github.com/mandiant/capa/issues) and contribute new rules at [capa-rules](https://github.com/mandiant/capa-rules/).
|
Download a standalone binary below and checkout the readme [here on GitHub](https://github.com/mandiant/capa/). Report issues on our [issue tracker](https://github.com/mandiant/capa/issues) and contribute new rules at [capa-rules](https://github.com/mandiant/capa-rules/).
|
||||||
|
|
||||||
|
|
||||||
### New Features
|
### New Features
|
||||||
|
|
||||||
- py3 support via SMDA #355 @danielplohmann @jcrussell
|
- py3 support via SMDA #355 @danielplohmann @jcrussell
|
||||||
@@ -1349,7 +1754,7 @@ The IDA Pro integration is now distributed as a real plugin, instead of a script
|
|||||||
- updates distributed PyPI/`pip install --upgrade` without touching your `%IDADIR%`
|
- updates distributed PyPI/`pip install --upgrade` without touching your `%IDADIR%`
|
||||||
- generally doing thing the "right way"
|
- generally doing thing the "right way"
|
||||||
|
|
||||||
How to get this new version? Its easy: download [capa_explorer.py](https://raw.githubusercontent.com/mandiant/capa/master/capa/ida/plugin/capa_explorer.py) to your IDA plugins directory and update your capa installation (incidentally, this is a good opportunity to migrate to `pip install flare-capa` instead of git checkouts). Now you should see the plugin listed in the `Edit > Plugins > FLARE capa explorer` menu in IDA.
|
How to get this new version? It's easy: download [capa_explorer.py](https://raw.githubusercontent.com/mandiant/capa/master/capa/ida/plugin/capa_explorer.py) to your IDA plugins directory and update your capa installation (incidentally, this is a good opportunity to migrate to `pip install flare-capa` instead of git checkouts). Now you should see the plugin listed in the `Edit > Plugins > FLARE capa explorer` menu in IDA.
|
||||||
|
|
||||||
Please refer to the plugin [readme](https://github.com/mandiant/capa/blob/master/capa/ida/plugin/README.md) for additional information on installing and using the IDA Pro plugin.
|
Please refer to the plugin [readme](https://github.com/mandiant/capa/blob/master/capa/ida/plugin/README.md) for additional information on installing and using the IDA Pro plugin.
|
||||||
|
|
||||||
@@ -1426,6 +1831,7 @@ and contribute new rules at [capa-rules](https://github.com/mandiant/capa-rules/
|
|||||||
- core: pin dependency versions #258 @recvfrom
|
- core: pin dependency versions #258 @recvfrom
|
||||||
|
|
||||||
### New rules
|
### New rules
|
||||||
|
|
||||||
- bypass UAC via AppInfo ALPC @agithubuserlol
|
- bypass UAC via AppInfo ALPC @agithubuserlol
|
||||||
- bypass UAC via token manipulation @agithubuserlol
|
- bypass UAC via token manipulation @agithubuserlol
|
||||||
- check for sandbox and av modules @re-fox
|
- check for sandbox and av modules @re-fox
|
||||||
|
|||||||
8
CITATION.cff
Normal file
8
CITATION.cff
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
cff-version: 1.2.0
|
||||||
|
message: "If you use this software, please cite it as below."
|
||||||
|
authors:
|
||||||
|
- name: "The FLARE Team"
|
||||||
|
title: "capa, a tool to identify capabilities in programs and sandbox traces."
|
||||||
|
date-released: 2020-07-16
|
||||||
|
url: "https://github.com/mandiant/capa"
|
||||||
|
|
||||||
@@ -187,7 +187,7 @@
|
|||||||
same "printed page" as the copyright notice for easier
|
same "printed page" as the copyright notice for easier
|
||||||
identification within third-party archives.
|
identification within third-party archives.
|
||||||
|
|
||||||
Copyright (C) 2023 Mandiant, Inc.
|
Copyright (C) 2020 Mandiant, Inc.
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0 (the "License");
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
you may not use this file except in compliance with the License.
|
you may not use this file except in compliance with the License.
|
||||||
|
|||||||
194
README.md
194
README.md
@@ -1,22 +1,40 @@
|
|||||||

|
<br />
|
||||||
|
<div align="center">
|
||||||
|
<a href="https://mandiant.github.io/capa/" target="_blank">
|
||||||
|
<img src="https://github.com/mandiant/capa/blob/master/.github/logo.png">
|
||||||
|
</a>
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://mandiant.github.io/capa/" target="_blank">Website</a>
|
||||||
|
|
|
||||||
|
<a href="https://github.com/mandiant/capa/releases/latest" target="_blank">Download</a>
|
||||||
|
|
|
||||||
|
<a href="https://mandiant.github.io/capa/explorer/" target="_blank">Web Interface</a>
|
||||||
|
</p>
|
||||||
|
<div align="center">
|
||||||
|
|
||||||
[](https://pypi.org/project/flare-capa)
|
[](https://pypi.org/project/flare-capa)
|
||||||
[](https://github.com/mandiant/capa/releases)
|
[](https://github.com/mandiant/capa/releases)
|
||||||
[](https://github.com/mandiant/capa-rules)
|
[](https://github.com/mandiant/capa-rules)
|
||||||
[](https://github.com/mandiant/capa/actions?query=workflow%3ACI+event%3Apush+branch%3Amaster)
|
[](https://github.com/mandiant/capa/actions?query=workflow%3ACI+event%3Apush+branch%3Amaster)
|
||||||
[](https://github.com/mandiant/capa/releases)
|
[](https://github.com/mandiant/capa/releases)
|
||||||
[](LICENSE.txt)
|
[](LICENSE.txt)
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
capa detects capabilities in executable files.
|
capa detects capabilities in executable files.
|
||||||
You run it against a PE, ELF, .NET module, or shellcode file and it tells you what it thinks the program can do.
|
You run it against a PE, ELF, .NET module, shellcode file, or a sandbox report and it tells you what it thinks the program can do.
|
||||||
For example, it might suggest that the file is a backdoor, is capable of installing services, or relies on HTTP to communicate.
|
For example, it might suggest that the file is a backdoor, is capable of installing services, or relies on HTTP to communicate.
|
||||||
|
|
||||||
Check out:
|
To interactively inspect capa results in your browser use the [capa Explorer Web](https://mandiant.github.io/capa/explorer/).
|
||||||
- the overview in our first [capa blog post](https://www.mandiant.com/resources/capa-automatically-identify-malware-capabilities)
|
|
||||||
- the major version 2.0 updates described in our [second blog post](https://www.mandiant.com/resources/capa-2-better-stronger-faster)
|
|
||||||
- the major version 3.0 (ELF support) described in the [third blog post](https://www.mandiant.com/resources/elfant-in-the-room-capa-v3)
|
|
||||||
- the major version 4.0 (.NET support) described in the [fourth blog post](https://www.mandiant.com/resources/blog/capa-v4-casting-wider-net)
|
|
||||||
|
|
||||||
|
If you want to inspect or write capa rules, head on over to the [capa-rules repository](https://github.com/mandiant/capa-rules). Otherwise, keep reading.
|
||||||
|
|
||||||
|
Below you find a list of [our capa blog posts with more details.](#blog-posts)
|
||||||
|
|
||||||
|
# example capa output
|
||||||
```
|
```
|
||||||
$ capa.exe suspicious.exe
|
$ capa.exe suspicious.exe
|
||||||
|
|
||||||
@@ -71,16 +89,23 @@ Download stable releases of the standalone capa binaries [here](https://github.c
|
|||||||
|
|
||||||
To use capa as a library or integrate with another tool, see [doc/installation.md](https://github.com/mandiant/capa/blob/master/doc/installation.md) for further setup instructions.
|
To use capa as a library or integrate with another tool, see [doc/installation.md](https://github.com/mandiant/capa/blob/master/doc/installation.md) for further setup instructions.
|
||||||
|
|
||||||
For more information about how to use capa, see [doc/usage.md](https://github.com/mandiant/capa/blob/master/doc/usage.md).
|
# capa Explorer Web
|
||||||
|
The [capa Explorer Web](https://mandiant.github.io/capa/explorer/) enables you to interactively explore capa results in your web browser. Besides the online version you can download a standalone HTML file for local offline usage.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
More details on the web UI is available in the [capa Explorer Web README](https://github.com/mandiant/capa/blob/master/web/explorer/README.md).
|
||||||
|
|
||||||
# example
|
# example
|
||||||
|
|
||||||
In the above sample output, we ran capa against an unknown binary (`suspicious.exe`),
|
In the above sample output, we run capa against an unknown binary (`suspicious.exe`),
|
||||||
and the tool reported that the program can send HTTP requests, decode data via XOR and Base64,
|
and the tool reports that the program can send HTTP requests, decode data via XOR and Base64,
|
||||||
install services, and spawn new processes.
|
install services, and spawn new processes.
|
||||||
Taken together, this makes us think that `suspicious.exe` could be a persistent backdoor.
|
Taken together, this makes us think that `suspicious.exe` could be a persistent backdoor.
|
||||||
Therefore, our next analysis step might be to run `suspicious.exe` in a sandbox and try to recover the command and control server.
|
Therefore, our next analysis step might be to run `suspicious.exe` in a sandbox and try to recover the command and control server.
|
||||||
|
|
||||||
|
## detailed results
|
||||||
|
|
||||||
By passing the `-vv` flag (for very verbose), capa reports exactly where it found evidence of these capabilities.
|
By passing the `-vv` flag (for very verbose), capa reports exactly where it found evidence of these capabilities.
|
||||||
This is useful for at least two reasons:
|
This is useful for at least two reasons:
|
||||||
|
|
||||||
@@ -125,6 +150,102 @@ function @ 0x4011C0
|
|||||||
...
|
...
|
||||||
```
|
```
|
||||||
|
|
||||||
|
capa also supports dynamic capabilities detection for multiple sandboxes including:
|
||||||
|
* [CAPE](https://github.com/kevoreilly/CAPEv2) (supported report formats: `.json`, `.json_`, `.json.gz`)
|
||||||
|
* [DRAKVUF](https://github.com/CERT-Polska/drakvuf-sandbox/) (supported report formats: `.log`, `.log.gz`)
|
||||||
|
* [VMRay](https://www.vmray.com/) (supported report formats: analysis archive `.zip`)
|
||||||
|
|
||||||
|
|
||||||
|
To use this feature, submit your file to a supported sandbox and then download and run capa against the generated report file. This feature enables capa to match capabilities against dynamic and static features that the sandbox captured during execution.
|
||||||
|
|
||||||
|
Here's an example of running capa against a packed file, and then running capa against the CAPE report generated for the same packed file:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
$ capa 05be49819139a3fdcdbddbdefd298398779521f3d68daa25275cc77508e42310.exe
|
||||||
|
WARNING:capa.capabilities.common:--------------------------------------------------------------------------------
|
||||||
|
WARNING:capa.capabilities.common: This sample appears to be packed.
|
||||||
|
WARNING:capa.capabilities.common:
|
||||||
|
WARNING:capa.capabilities.common: Packed samples have often been obfuscated to hide their logic.
|
||||||
|
WARNING:capa.capabilities.common: capa cannot handle obfuscation well using static analysis. This means the results may be misleading or incomplete.
|
||||||
|
WARNING:capa.capabilities.common: If possible, you should try to unpack this input file before analyzing it with capa.
|
||||||
|
WARNING:capa.capabilities.common: Alternatively, run the sample in a supported sandbox and invoke capa against the report to obtain dynamic analysis results.
|
||||||
|
WARNING:capa.capabilities.common:
|
||||||
|
WARNING:capa.capabilities.common: Identified via rule: (internal) packer file limitation
|
||||||
|
WARNING:capa.capabilities.common:
|
||||||
|
WARNING:capa.capabilities.common: Use -v or -vv if you really want to see the capabilities identified by capa.
|
||||||
|
WARNING:capa.capabilities.common:--------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
$ capa 05be49819139a3fdcdbddbdefd298398779521f3d68daa25275cc77508e42310.json
|
||||||
|
|
||||||
|
┍━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┑
|
||||||
|
│ ATT&CK Tactic │ ATT&CK Technique │
|
||||||
|
┝━━━━━━━━━━━━━━━━━━━━━━━━┿━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┥
|
||||||
|
│ CREDENTIAL ACCESS │ Credentials from Password Stores T1555 │
|
||||||
|
├────────────────────────┼────────────────────────────────────────────────────────────────────────────────────┤
|
||||||
|
│ DEFENSE EVASION │ File and Directory Permissions Modification T1222 │
|
||||||
|
│ │ Modify Registry T1112 │
|
||||||
|
│ │ Obfuscated Files or Information T1027 │
|
||||||
|
│ │ Virtualization/Sandbox Evasion::User Activity Based Checks T1497.002 │
|
||||||
|
├────────────────────────┼────────────────────────────────────────────────────────────────────────────────────┤
|
||||||
|
│ DISCOVERY │ Account Discovery T1087 │
|
||||||
|
│ │ Application Window Discovery T1010 │
|
||||||
|
│ │ File and Directory Discovery T1083 │
|
||||||
|
│ │ Query Registry T1012 │
|
||||||
|
│ │ System Information Discovery T1082 │
|
||||||
|
│ │ System Location Discovery::System Language Discovery T1614.001 │
|
||||||
|
│ │ System Owner/User Discovery T1033 │
|
||||||
|
├────────────────────────┼────────────────────────────────────────────────────────────────────────────────────┤
|
||||||
|
│ EXECUTION │ System Services::Service Execution T1569.002 │
|
||||||
|
├────────────────────────┼────────────────────────────────────────────────────────────────────────────────────┤
|
||||||
|
│ PERSISTENCE │ Boot or Logon Autostart Execution::Registry Run Keys / Startup Folder T1547.001 │
|
||||||
|
│ │ Boot or Logon Autostart Execution::Winlogon Helper DLL T1547.004 │
|
||||||
|
│ │ Create or Modify System Process::Windows Service T1543.003 │
|
||||||
|
┕━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┙
|
||||||
|
|
||||||
|
┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┑
|
||||||
|
│ Capability │ Namespace │
|
||||||
|
┝━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┿━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┥
|
||||||
|
│ check for unmoving mouse cursor (3 matches) │ anti-analysis/anti-vm/vm-detection │
|
||||||
|
│ gather bitkinex information │ collection/file-managers │
|
||||||
|
│ gather classicftp information │ collection/file-managers │
|
||||||
|
│ gather filezilla information │ collection/file-managers │
|
||||||
|
│ gather total-commander information │ collection/file-managers │
|
||||||
|
│ gather ultrafxp information │ collection/file-managers │
|
||||||
|
│ resolve DNS (23 matches) │ communication/dns │
|
||||||
|
│ initialize Winsock library (7 matches) │ communication/socket │
|
||||||
|
│ act as TCP client (3 matches) │ communication/tcp/client │
|
||||||
|
│ create new key via CryptAcquireContext │ data-manipulation/encryption │
|
||||||
|
│ encrypt or decrypt via WinCrypt │ data-manipulation/encryption │
|
||||||
|
│ hash data via WinCrypt │ data-manipulation/hashing │
|
||||||
|
│ initialize hashing via WinCrypt │ data-manipulation/hashing │
|
||||||
|
│ hash data with MD5 │ data-manipulation/hashing/md5 │
|
||||||
|
│ generate random numbers via WinAPI │ data-manipulation/prng │
|
||||||
|
│ extract resource via kernel32 functions (2 matches) │ executable/resource │
|
||||||
|
│ interact with driver via control codes (2 matches) │ host-interaction/driver │
|
||||||
|
│ get Program Files directory (18 matches) │ host-interaction/file-system │
|
||||||
|
│ get common file path (575 matches) │ host-interaction/file-system │
|
||||||
|
│ create directory (2 matches) │ host-interaction/file-system/create │
|
||||||
|
│ delete file │ host-interaction/file-system/delete │
|
||||||
|
│ get file attributes (122 matches) │ host-interaction/file-system/meta │
|
||||||
|
│ set file attributes (8 matches) │ host-interaction/file-system/meta │
|
||||||
|
│ move file │ host-interaction/file-system/move │
|
||||||
|
│ find taskbar (3 matches) │ host-interaction/gui/taskbar/find │
|
||||||
|
│ get keyboard layout (12 matches) │ host-interaction/hardware/keyboard │
|
||||||
|
│ get disk size │ host-interaction/hardware/storage │
|
||||||
|
│ get hostname (4 matches) │ host-interaction/os/hostname │
|
||||||
|
│ allocate or change RWX memory (3 matches) │ host-interaction/process/inject │
|
||||||
|
│ query or enumerate registry key (3 matches) │ host-interaction/registry │
|
||||||
|
│ query or enumerate registry value (8 matches) │ host-interaction/registry │
|
||||||
|
│ delete registry key │ host-interaction/registry/delete │
|
||||||
|
│ start service │ host-interaction/service/start │
|
||||||
|
│ get session user name │ host-interaction/session │
|
||||||
|
│ persist via Run registry key │ persistence/registry/run │
|
||||||
|
│ persist via Winlogon Helper DLL registry key │ persistence/registry/winlogon-helper │
|
||||||
|
│ persist via Windows service (2 matches) │ persistence/service │
|
||||||
|
┕━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┙
|
||||||
|
```
|
||||||
|
|
||||||
|
# capa rules
|
||||||
capa uses a collection of rules to identify capabilities within a program.
|
capa uses a collection of rules to identify capabilities within a program.
|
||||||
These rules are easy to write, even for those new to reverse engineering.
|
These rules are easy to write, even for those new to reverse engineering.
|
||||||
By authoring rules, you can extend the capabilities that capa recognizes.
|
By authoring rules, you can extend the capabilities that capa recognizes.
|
||||||
@@ -135,42 +256,53 @@ Here's an example rule used by capa:
|
|||||||
```yaml
|
```yaml
|
||||||
rule:
|
rule:
|
||||||
meta:
|
meta:
|
||||||
name: hash data with CRC32
|
name: create TCP socket
|
||||||
namespace: data-manipulation/checksum/crc32
|
namespace: communication/socket/tcp
|
||||||
authors:
|
authors:
|
||||||
- moritz.raabe@mandiant.com
|
- william.ballenthin@mandiant.com
|
||||||
scope: function
|
- joakim@intezer.com
|
||||||
|
- anushka.virgaonkar@mandiant.com
|
||||||
|
scopes:
|
||||||
|
static: basic block
|
||||||
|
dynamic: call
|
||||||
mbc:
|
mbc:
|
||||||
- Data::Checksum::CRC32 [C0032.001]
|
- Communication::Socket Communication::Create TCP Socket [C0001.011]
|
||||||
examples:
|
examples:
|
||||||
- 2D3EDC218A90F03089CC01715A9F047F:0x403CBD
|
- Practical Malware Analysis Lab 01-01.dll_:0x10001010
|
||||||
- 7D28CB106CB54876B2A5C111724A07CD:0x402350 # RtlComputeCrc32
|
|
||||||
- 7EFF498DE13CC734262F87E6B3EF38AB:0x100084A6
|
|
||||||
features:
|
features:
|
||||||
- or:
|
- or:
|
||||||
- and:
|
- and:
|
||||||
- mnemonic: shr
|
- number: 6 = IPPROTO_TCP
|
||||||
|
- number: 1 = SOCK_STREAM
|
||||||
|
- number: 2 = AF_INET
|
||||||
- or:
|
- or:
|
||||||
- number: 0xEDB88320
|
- api: ws2_32.socket
|
||||||
- bytes: 00 00 00 00 96 30 07 77 2C 61 0E EE BA 51 09 99 19 C4 6D 07 8F F4 6A 70 35 A5 63 E9 A3 95 64 9E = crc32_tab
|
- api: ws2_32.WSASocket
|
||||||
- number: 8
|
- api: socket
|
||||||
- characteristic: nzxor
|
- property/read: System.Net.Sockets.TcpClient::Client
|
||||||
- and:
|
|
||||||
- number: 0x8320
|
|
||||||
- number: 0xEDB8
|
|
||||||
- characteristic: nzxor
|
|
||||||
- api: RtlComputeCrc32
|
|
||||||
```
|
```
|
||||||
|
|
||||||
The [github.com/mandiant/capa-rules](https://github.com/mandiant/capa-rules) repository contains hundreds of standard library rules that are distributed with capa.
|
The [github.com/mandiant/capa-rules](https://github.com/mandiant/capa-rules) repository contains hundreds of standard rules that are distributed with capa.
|
||||||
Please learn to write rules and contribute new entries as you find interesting techniques in malware.
|
Please learn to write rules and contribute new entries as you find interesting techniques in malware.
|
||||||
|
|
||||||
|
# IDA Pro plugin: capa explorer
|
||||||
If you use IDA Pro, then you can use the [capa explorer](https://github.com/mandiant/capa/tree/master/capa/ida/plugin) plugin.
|
If you use IDA Pro, then you can use the [capa explorer](https://github.com/mandiant/capa/tree/master/capa/ida/plugin) plugin.
|
||||||
capa explorer helps you identify interesting areas of a program and build new capa rules using features extracted directly from your IDA Pro database.
|
capa explorer helps you identify interesting areas of a program and build new capa rules using features extracted directly from your IDA Pro database.
|
||||||
|
It also uses your local changes to the .idb to extract better features, such as when you rename a global variable that contains a dynamically resolved API address.
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
If you use Ghidra, you can use the Python 3 [Ghidra feature extractor](/capa/ghidra/). This integration enables capa to extract features directly from your Ghidra database, which can help you identify capabilities in programs that you analyze using Ghidra.
|
# Ghidra integration
|
||||||
|
If you use Ghidra, then you can use the [capa + Ghidra integration](/capa/ghidra/) to run capa's analysis directly on your Ghidra database and render the results in Ghidra's user interface.
|
||||||
|
|
||||||
|
<img src="https://github.com/mandiant/capa/assets/66766340/eeae33f4-99d4-42dc-a5e8-4c1b8c661492" width=300>
|
||||||
|
|
||||||
|
# blog posts
|
||||||
|
- [Dynamic capa: Exploring Executable Run-Time Behavior with the CAPE Sandbox](https://www.mandiant.com/resources/blog/dynamic-capa-executable-behavior-cape-sandbox)
|
||||||
|
- [capa v4: casting a wider .NET](https://www.mandiant.com/resources/blog/capa-v4-casting-wider-net) (.NET support)
|
||||||
|
- [ELFant in the Room – capa v3](https://www.mandiant.com/resources/elfant-in-the-room-capa-v3) (ELF support)
|
||||||
|
- [capa 2.0: Better, Stronger, Faster](https://www.mandiant.com/resources/capa-2-better-stronger-faster)
|
||||||
|
- [capa: Automatically Identify Malware Capabilities](https://www.mandiant.com/resources/capa-automatically-identify-malware-capabilities)
|
||||||
|
|
||||||
# further information
|
# further information
|
||||||
## capa
|
## capa
|
||||||
|
|||||||
164
capa/analysis/flirt.py
Normal file
164
capa/analysis/flirt.py
Normal file
@@ -0,0 +1,164 @@
|
|||||||
|
import io
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import logging
|
||||||
|
import argparse
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import rich
|
||||||
|
from rich.console import Console
|
||||||
|
from rich.logging import RichHandler
|
||||||
|
|
||||||
|
import capa.helpers
|
||||||
|
import capa.features.extractors.ida.idalib as idalib
|
||||||
|
|
||||||
|
if not idalib.has_idalib():
|
||||||
|
raise RuntimeError("cannot find IDA idalib module.")
|
||||||
|
|
||||||
|
if not idalib.load_idalib():
|
||||||
|
raise RuntimeError("failed to load IDA idalib module.")
|
||||||
|
|
||||||
|
import idaapi
|
||||||
|
import idapro
|
||||||
|
import ida_auto
|
||||||
|
import idautils
|
||||||
|
import ida_funcs
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
|
||||||
|
def colorbool(v: bool) -> str:
|
||||||
|
if v:
|
||||||
|
return f"[green]{str(v)}[/green]"
|
||||||
|
else:
|
||||||
|
return f"[red]{str(v)}[/red]"
|
||||||
|
|
||||||
|
|
||||||
|
def colorname(n: str) -> str:
|
||||||
|
if n.startswith("sub_"):
|
||||||
|
return n
|
||||||
|
else:
|
||||||
|
return f"[cyan]{n}[/cyan]"
|
||||||
|
|
||||||
|
|
||||||
|
class FunctionId(BaseModel):
|
||||||
|
address: int
|
||||||
|
is_library: bool
|
||||||
|
is_thunk: bool
|
||||||
|
name: str
|
||||||
|
|
||||||
|
def to_row(self):
|
||||||
|
row = [hex(self.address)]
|
||||||
|
row.append(colorbool(self.is_library))
|
||||||
|
row.append(colorbool(self.is_thunk))
|
||||||
|
row.append(colorname(self.name))
|
||||||
|
return row
|
||||||
|
|
||||||
|
|
||||||
|
def configure_logging(args):
|
||||||
|
if args.quiet:
|
||||||
|
logging.getLogger().setLevel(logging.WARNING)
|
||||||
|
elif args.debug:
|
||||||
|
logging.getLogger().setLevel(logging.DEBUG)
|
||||||
|
else:
|
||||||
|
logging.getLogger().setLevel(logging.INFO)
|
||||||
|
|
||||||
|
# use [/] after the logger name to reset any styling,
|
||||||
|
# and prevent the color from carrying over to the message
|
||||||
|
logformat = "[dim]%(name)s[/]: %(message)s"
|
||||||
|
|
||||||
|
# set markup=True to allow the use of Rich's markup syntax in log messages
|
||||||
|
rich_handler = RichHandler(markup=True, show_time=False, show_path=True, console=capa.helpers.log_console)
|
||||||
|
rich_handler.setFormatter(logging.Formatter(logformat))
|
||||||
|
|
||||||
|
# use RichHandler for root logger
|
||||||
|
logging.getLogger().addHandler(rich_handler)
|
||||||
|
|
||||||
|
if args.debug:
|
||||||
|
logging.getLogger("capa").setLevel(logging.DEBUG)
|
||||||
|
logging.getLogger("viv_utils").setLevel(logging.DEBUG)
|
||||||
|
else:
|
||||||
|
logging.getLogger("capa").setLevel(logging.ERROR)
|
||||||
|
logging.getLogger("viv_utils").setLevel(logging.ERROR)
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv=None):
|
||||||
|
if argv is None:
|
||||||
|
argv = sys.argv[1:]
|
||||||
|
|
||||||
|
parser = argparse.ArgumentParser(description="Identify library functions using FLIRT.")
|
||||||
|
parser.add_argument(
|
||||||
|
"input_file",
|
||||||
|
type=Path,
|
||||||
|
help="path to file to analyze",
|
||||||
|
)
|
||||||
|
parser.add_argument("-d", "--debug", action="store_true", help="enable debugging output on STDERR")
|
||||||
|
parser.add_argument("-q", "--quiet", action="store_true", help="disable all output but errors")
|
||||||
|
args = parser.parse_args(args=argv)
|
||||||
|
|
||||||
|
configure_logging(args)
|
||||||
|
|
||||||
|
time0 = time.time()
|
||||||
|
|
||||||
|
# stderr=True is used here to redirect the spinner banner to stderr, so that users can redirect capa's output.
|
||||||
|
console = Console(stderr=True, quiet=False)
|
||||||
|
|
||||||
|
logger.debug("idalib: opening database...")
|
||||||
|
# idalib writes to stdout (ugh), so we have to capture that
|
||||||
|
# so as not to screw up structured output.
|
||||||
|
with capa.helpers.stdout_redirector(io.BytesIO()):
|
||||||
|
with console.status("analyzing program...", spinner="dots"):
|
||||||
|
if idapro.open_database(str(args.input_file), run_auto_analysis=True):
|
||||||
|
raise RuntimeError("failed to analyze input file")
|
||||||
|
|
||||||
|
logger.debug("idalib: waiting for analysis...")
|
||||||
|
|
||||||
|
# TODO: add more signature (files)
|
||||||
|
# TOOD: apply more signatures
|
||||||
|
|
||||||
|
ida_auto.auto_wait()
|
||||||
|
logger.debug("idalib: opened database.")
|
||||||
|
|
||||||
|
table = rich.table.Table()
|
||||||
|
table.add_column("FVA")
|
||||||
|
table.add_column("library?")
|
||||||
|
table.add_column("thunk?")
|
||||||
|
table.add_column("name")
|
||||||
|
|
||||||
|
LIBONLY = True
|
||||||
|
count = 0
|
||||||
|
|
||||||
|
for ea in idautils.Functions(start=None, end=None):
|
||||||
|
f = idaapi.get_func(ea)
|
||||||
|
is_thunk = bool(f.flags & idaapi.FUNC_THUNK)
|
||||||
|
is_lib = bool(f.flags & idaapi.FUNC_LIB)
|
||||||
|
fname = idaapi.get_func_name(ea)
|
||||||
|
|
||||||
|
if LIBONLY and not is_lib:
|
||||||
|
continue
|
||||||
|
|
||||||
|
fid = FunctionId(address=ea, is_library=is_lib, is_thunk=is_thunk, name=fname)
|
||||||
|
table.add_row(*fid.to_row())
|
||||||
|
|
||||||
|
count += 1
|
||||||
|
if count > 50:
|
||||||
|
break
|
||||||
|
|
||||||
|
rich.print(table)
|
||||||
|
|
||||||
|
# TODO can we include which signature matched per function?
|
||||||
|
for index in range(0, ida_funcs.get_idasgn_qty()):
|
||||||
|
signame, optlibs, nmatches = ida_funcs.get_idasgn_desc_with_matches(index)
|
||||||
|
rich.print(signame, optlibs, nmatches)
|
||||||
|
|
||||||
|
idapro.close_database()
|
||||||
|
|
||||||
|
min, sec = divmod(time.time() - time0, 60)
|
||||||
|
logger.debug("FLIRT-based library identification ran for ~ %02d:%02dm", min, sec)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
0
capa/capabilities/__init__.py
Normal file
0
capa/capabilities/__init__.py
Normal file
79
capa/capabilities/common.py
Normal file
79
capa/capabilities/common.py
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
import logging
|
||||||
|
import itertools
|
||||||
|
import collections
|
||||||
|
from typing import Any, Tuple
|
||||||
|
|
||||||
|
from capa.rules import Scope, RuleSet
|
||||||
|
from capa.engine import FeatureSet, MatchResults
|
||||||
|
from capa.features.address import NO_ADDRESS
|
||||||
|
from capa.features.extractors.base_extractor import FeatureExtractor, StaticFeatureExtractor, DynamicFeatureExtractor
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def find_file_capabilities(ruleset: RuleSet, extractor: FeatureExtractor, function_features: FeatureSet):
|
||||||
|
file_features: FeatureSet = collections.defaultdict(set)
|
||||||
|
|
||||||
|
for feature, va in itertools.chain(extractor.extract_file_features(), extractor.extract_global_features()):
|
||||||
|
# not all file features may have virtual addresses.
|
||||||
|
# if not, then at least ensure the feature shows up in the index.
|
||||||
|
# the set of addresses will still be empty.
|
||||||
|
if va:
|
||||||
|
file_features[feature].add(va)
|
||||||
|
else:
|
||||||
|
if feature not in file_features:
|
||||||
|
file_features[feature] = set()
|
||||||
|
|
||||||
|
logger.debug("analyzed file and extracted %d features", len(file_features))
|
||||||
|
|
||||||
|
file_features.update(function_features)
|
||||||
|
|
||||||
|
_, matches = ruleset.match(Scope.FILE, file_features, NO_ADDRESS)
|
||||||
|
return matches, len(file_features)
|
||||||
|
|
||||||
|
|
||||||
|
def has_file_limitation(rules: RuleSet, capabilities: MatchResults, is_standalone=True) -> bool:
|
||||||
|
file_limitation_rules = list(filter(lambda r: r.is_file_limitation_rule(), rules.rules.values()))
|
||||||
|
|
||||||
|
for file_limitation_rule in file_limitation_rules:
|
||||||
|
if file_limitation_rule.name not in capabilities:
|
||||||
|
continue
|
||||||
|
|
||||||
|
logger.warning("-" * 80)
|
||||||
|
for line in file_limitation_rule.meta.get("description", "").split("\n"):
|
||||||
|
logger.warning(" %s", line)
|
||||||
|
logger.warning(" Identified via rule: %s", file_limitation_rule.name)
|
||||||
|
if is_standalone:
|
||||||
|
logger.warning(" ")
|
||||||
|
logger.warning(" Use -v or -vv if you really want to see the capabilities identified by capa.")
|
||||||
|
logger.warning("-" * 80)
|
||||||
|
|
||||||
|
# bail on first file limitation
|
||||||
|
return True
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def find_capabilities(
|
||||||
|
ruleset: RuleSet, extractor: FeatureExtractor, disable_progress=None, **kwargs
|
||||||
|
) -> Tuple[MatchResults, Any]:
|
||||||
|
from capa.capabilities.static import find_static_capabilities
|
||||||
|
from capa.capabilities.dynamic import find_dynamic_capabilities
|
||||||
|
|
||||||
|
if isinstance(extractor, StaticFeatureExtractor):
|
||||||
|
# for the time being, extractors are either static or dynamic.
|
||||||
|
# Remove this assertion once that has changed
|
||||||
|
assert not isinstance(extractor, DynamicFeatureExtractor)
|
||||||
|
return find_static_capabilities(ruleset, extractor, disable_progress=disable_progress, **kwargs)
|
||||||
|
if isinstance(extractor, DynamicFeatureExtractor):
|
||||||
|
return find_dynamic_capabilities(ruleset, extractor, disable_progress=disable_progress, **kwargs)
|
||||||
|
|
||||||
|
raise ValueError(f"unexpected extractor type: {extractor.__class__.__name__}")
|
||||||
192
capa/capabilities/dynamic.py
Normal file
192
capa/capabilities/dynamic.py
Normal file
@@ -0,0 +1,192 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
import logging
|
||||||
|
import itertools
|
||||||
|
import collections
|
||||||
|
from typing import Any, List, Tuple
|
||||||
|
|
||||||
|
import capa.perf
|
||||||
|
import capa.features.freeze as frz
|
||||||
|
import capa.render.result_document as rdoc
|
||||||
|
from capa.rules import Scope, RuleSet
|
||||||
|
from capa.engine import FeatureSet, MatchResults
|
||||||
|
from capa.capabilities.common import find_file_capabilities
|
||||||
|
from capa.features.extractors.base_extractor import CallHandle, ThreadHandle, ProcessHandle, DynamicFeatureExtractor
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def find_call_capabilities(
|
||||||
|
ruleset: RuleSet, extractor: DynamicFeatureExtractor, ph: ProcessHandle, th: ThreadHandle, ch: CallHandle
|
||||||
|
) -> Tuple[FeatureSet, MatchResults]:
|
||||||
|
"""
|
||||||
|
find matches for the given rules for the given call.
|
||||||
|
|
||||||
|
returns: tuple containing (features for call, match results for call)
|
||||||
|
"""
|
||||||
|
# all features found for the call.
|
||||||
|
features: FeatureSet = collections.defaultdict(set)
|
||||||
|
|
||||||
|
for feature, addr in itertools.chain(
|
||||||
|
extractor.extract_call_features(ph, th, ch), extractor.extract_global_features()
|
||||||
|
):
|
||||||
|
features[feature].add(addr)
|
||||||
|
|
||||||
|
# matches found at this thread.
|
||||||
|
_, matches = ruleset.match(Scope.CALL, features, ch.address)
|
||||||
|
|
||||||
|
for rule_name, res in matches.items():
|
||||||
|
rule = ruleset[rule_name]
|
||||||
|
for addr, _ in res:
|
||||||
|
capa.engine.index_rule_matches(features, rule, [addr])
|
||||||
|
|
||||||
|
return features, matches
|
||||||
|
|
||||||
|
|
||||||
|
def find_thread_capabilities(
|
||||||
|
ruleset: RuleSet, extractor: DynamicFeatureExtractor, ph: ProcessHandle, th: ThreadHandle
|
||||||
|
) -> Tuple[FeatureSet, MatchResults, MatchResults]:
|
||||||
|
"""
|
||||||
|
find matches for the given rules within the given thread.
|
||||||
|
|
||||||
|
returns: tuple containing (features for thread, match results for thread, match results for calls)
|
||||||
|
"""
|
||||||
|
# all features found within this thread,
|
||||||
|
# includes features found within calls.
|
||||||
|
features: FeatureSet = collections.defaultdict(set)
|
||||||
|
|
||||||
|
# matches found at the call scope.
|
||||||
|
# might be found at different calls, that's ok.
|
||||||
|
call_matches: MatchResults = collections.defaultdict(list)
|
||||||
|
|
||||||
|
for ch in extractor.get_calls(ph, th):
|
||||||
|
ifeatures, imatches = find_call_capabilities(ruleset, extractor, ph, th, ch)
|
||||||
|
for feature, vas in ifeatures.items():
|
||||||
|
features[feature].update(vas)
|
||||||
|
|
||||||
|
for rule_name, res in imatches.items():
|
||||||
|
call_matches[rule_name].extend(res)
|
||||||
|
|
||||||
|
for feature, va in itertools.chain(extractor.extract_thread_features(ph, th), extractor.extract_global_features()):
|
||||||
|
features[feature].add(va)
|
||||||
|
|
||||||
|
# matches found within this thread.
|
||||||
|
_, matches = ruleset.match(Scope.THREAD, features, th.address)
|
||||||
|
|
||||||
|
for rule_name, res in matches.items():
|
||||||
|
rule = ruleset[rule_name]
|
||||||
|
for va, _ in res:
|
||||||
|
capa.engine.index_rule_matches(features, rule, [va])
|
||||||
|
|
||||||
|
return features, matches, call_matches
|
||||||
|
|
||||||
|
|
||||||
|
def find_process_capabilities(
|
||||||
|
ruleset: RuleSet, extractor: DynamicFeatureExtractor, ph: ProcessHandle
|
||||||
|
) -> Tuple[MatchResults, MatchResults, MatchResults, int]:
|
||||||
|
"""
|
||||||
|
find matches for the given rules within the given process.
|
||||||
|
|
||||||
|
returns: tuple containing (match results for process, match results for threads, match results for calls, number of features)
|
||||||
|
"""
|
||||||
|
# all features found within this process,
|
||||||
|
# includes features found within threads (and calls).
|
||||||
|
process_features: FeatureSet = collections.defaultdict(set)
|
||||||
|
|
||||||
|
# matches found at the basic threads.
|
||||||
|
# might be found at different threads, that's ok.
|
||||||
|
thread_matches: MatchResults = collections.defaultdict(list)
|
||||||
|
|
||||||
|
# matches found at the call scope.
|
||||||
|
# might be found at different calls, that's ok.
|
||||||
|
call_matches: MatchResults = collections.defaultdict(list)
|
||||||
|
|
||||||
|
for th in extractor.get_threads(ph):
|
||||||
|
features, tmatches, cmatches = find_thread_capabilities(ruleset, extractor, ph, th)
|
||||||
|
for feature, vas in features.items():
|
||||||
|
process_features[feature].update(vas)
|
||||||
|
|
||||||
|
for rule_name, res in tmatches.items():
|
||||||
|
thread_matches[rule_name].extend(res)
|
||||||
|
|
||||||
|
for rule_name, res in cmatches.items():
|
||||||
|
call_matches[rule_name].extend(res)
|
||||||
|
|
||||||
|
for feature, va in itertools.chain(extractor.extract_process_features(ph), extractor.extract_global_features()):
|
||||||
|
process_features[feature].add(va)
|
||||||
|
|
||||||
|
_, process_matches = ruleset.match(Scope.PROCESS, process_features, ph.address)
|
||||||
|
return process_matches, thread_matches, call_matches, len(process_features)
|
||||||
|
|
||||||
|
|
||||||
|
def find_dynamic_capabilities(
|
||||||
|
ruleset: RuleSet, extractor: DynamicFeatureExtractor, disable_progress=None
|
||||||
|
) -> Tuple[MatchResults, Any]:
|
||||||
|
all_process_matches: MatchResults = collections.defaultdict(list)
|
||||||
|
all_thread_matches: MatchResults = collections.defaultdict(list)
|
||||||
|
all_call_matches: MatchResults = collections.defaultdict(list)
|
||||||
|
|
||||||
|
feature_counts = rdoc.DynamicFeatureCounts(file=0, processes=())
|
||||||
|
|
||||||
|
assert isinstance(extractor, DynamicFeatureExtractor)
|
||||||
|
processes: List[ProcessHandle] = list(extractor.get_processes())
|
||||||
|
n_processes: int = len(processes)
|
||||||
|
|
||||||
|
with capa.helpers.CapaProgressBar(
|
||||||
|
console=capa.helpers.log_console, transient=True, disable=disable_progress
|
||||||
|
) as pbar:
|
||||||
|
task = pbar.add_task("matching", total=n_processes, unit="processes")
|
||||||
|
for p in processes:
|
||||||
|
process_matches, thread_matches, call_matches, feature_count = find_process_capabilities(
|
||||||
|
ruleset, extractor, p
|
||||||
|
)
|
||||||
|
feature_counts.processes += (
|
||||||
|
rdoc.ProcessFeatureCount(address=frz.Address.from_capa(p.address), count=feature_count),
|
||||||
|
)
|
||||||
|
logger.debug("analyzed %s and extracted %d features", p.address, feature_count)
|
||||||
|
|
||||||
|
for rule_name, res in process_matches.items():
|
||||||
|
all_process_matches[rule_name].extend(res)
|
||||||
|
for rule_name, res in thread_matches.items():
|
||||||
|
all_thread_matches[rule_name].extend(res)
|
||||||
|
for rule_name, res in call_matches.items():
|
||||||
|
all_call_matches[rule_name].extend(res)
|
||||||
|
|
||||||
|
pbar.advance(task)
|
||||||
|
|
||||||
|
# collection of features that captures the rule matches within process and thread scopes.
|
||||||
|
# mapping from feature (matched rule) to set of addresses at which it matched.
|
||||||
|
process_and_lower_features: FeatureSet = collections.defaultdict(set)
|
||||||
|
for rule_name, results in itertools.chain(
|
||||||
|
all_process_matches.items(), all_thread_matches.items(), all_call_matches.items()
|
||||||
|
):
|
||||||
|
locations = {p[0] for p in results}
|
||||||
|
rule = ruleset[rule_name]
|
||||||
|
capa.engine.index_rule_matches(process_and_lower_features, rule, locations)
|
||||||
|
|
||||||
|
all_file_matches, feature_count = find_file_capabilities(ruleset, extractor, process_and_lower_features)
|
||||||
|
feature_counts.file = feature_count
|
||||||
|
|
||||||
|
matches = dict(
|
||||||
|
itertools.chain(
|
||||||
|
# each rule exists in exactly one scope,
|
||||||
|
# so there won't be any overlap among these following MatchResults,
|
||||||
|
# and we can merge the dictionaries naively.
|
||||||
|
all_thread_matches.items(),
|
||||||
|
all_process_matches.items(),
|
||||||
|
all_call_matches.items(),
|
||||||
|
all_file_matches.items(),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
meta = {
|
||||||
|
"feature_counts": feature_counts,
|
||||||
|
}
|
||||||
|
|
||||||
|
return matches, meta
|
||||||
226
capa/capabilities/static.py
Normal file
226
capa/capabilities/static.py
Normal file
@@ -0,0 +1,226 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
import time
|
||||||
|
import logging
|
||||||
|
import itertools
|
||||||
|
import collections
|
||||||
|
from typing import Any, List, Tuple
|
||||||
|
|
||||||
|
import capa.perf
|
||||||
|
import capa.helpers
|
||||||
|
import capa.features.freeze as frz
|
||||||
|
import capa.render.result_document as rdoc
|
||||||
|
from capa.rules import Scope, RuleSet
|
||||||
|
from capa.engine import FeatureSet, MatchResults
|
||||||
|
from capa.capabilities.common import find_file_capabilities
|
||||||
|
from capa.features.extractors.base_extractor import BBHandle, InsnHandle, FunctionHandle, StaticFeatureExtractor
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def find_instruction_capabilities(
|
||||||
|
ruleset: RuleSet, extractor: StaticFeatureExtractor, f: FunctionHandle, bb: BBHandle, insn: InsnHandle
|
||||||
|
) -> Tuple[FeatureSet, MatchResults]:
|
||||||
|
"""
|
||||||
|
find matches for the given rules for the given instruction.
|
||||||
|
|
||||||
|
returns: tuple containing (features for instruction, match results for instruction)
|
||||||
|
"""
|
||||||
|
# all features found for the instruction.
|
||||||
|
features: FeatureSet = collections.defaultdict(set)
|
||||||
|
|
||||||
|
for feature, addr in itertools.chain(
|
||||||
|
extractor.extract_insn_features(f, bb, insn), extractor.extract_global_features()
|
||||||
|
):
|
||||||
|
features[feature].add(addr)
|
||||||
|
|
||||||
|
# matches found at this instruction.
|
||||||
|
_, matches = ruleset.match(Scope.INSTRUCTION, features, insn.address)
|
||||||
|
|
||||||
|
for rule_name, res in matches.items():
|
||||||
|
rule = ruleset[rule_name]
|
||||||
|
for addr, _ in res:
|
||||||
|
capa.engine.index_rule_matches(features, rule, [addr])
|
||||||
|
|
||||||
|
return features, matches
|
||||||
|
|
||||||
|
|
||||||
|
def find_basic_block_capabilities(
|
||||||
|
ruleset: RuleSet, extractor: StaticFeatureExtractor, f: FunctionHandle, bb: BBHandle
|
||||||
|
) -> Tuple[FeatureSet, MatchResults, MatchResults]:
|
||||||
|
"""
|
||||||
|
find matches for the given rules within the given basic block.
|
||||||
|
|
||||||
|
returns: tuple containing (features for basic block, match results for basic block, match results for instructions)
|
||||||
|
"""
|
||||||
|
# all features found within this basic block,
|
||||||
|
# includes features found within instructions.
|
||||||
|
features: FeatureSet = collections.defaultdict(set)
|
||||||
|
|
||||||
|
# matches found at the instruction scope.
|
||||||
|
# might be found at different instructions, that's ok.
|
||||||
|
insn_matches: MatchResults = collections.defaultdict(list)
|
||||||
|
|
||||||
|
for insn in extractor.get_instructions(f, bb):
|
||||||
|
ifeatures, imatches = find_instruction_capabilities(ruleset, extractor, f, bb, insn)
|
||||||
|
for feature, vas in ifeatures.items():
|
||||||
|
features[feature].update(vas)
|
||||||
|
|
||||||
|
for rule_name, res in imatches.items():
|
||||||
|
insn_matches[rule_name].extend(res)
|
||||||
|
|
||||||
|
for feature, va in itertools.chain(
|
||||||
|
extractor.extract_basic_block_features(f, bb), extractor.extract_global_features()
|
||||||
|
):
|
||||||
|
features[feature].add(va)
|
||||||
|
|
||||||
|
# matches found within this basic block.
|
||||||
|
_, matches = ruleset.match(Scope.BASIC_BLOCK, features, bb.address)
|
||||||
|
|
||||||
|
for rule_name, res in matches.items():
|
||||||
|
rule = ruleset[rule_name]
|
||||||
|
for va, _ in res:
|
||||||
|
capa.engine.index_rule_matches(features, rule, [va])
|
||||||
|
|
||||||
|
return features, matches, insn_matches
|
||||||
|
|
||||||
|
|
||||||
|
def find_code_capabilities(
|
||||||
|
ruleset: RuleSet, extractor: StaticFeatureExtractor, fh: FunctionHandle
|
||||||
|
) -> Tuple[MatchResults, MatchResults, MatchResults, int]:
|
||||||
|
"""
|
||||||
|
find matches for the given rules within the given function.
|
||||||
|
|
||||||
|
returns: tuple containing (match results for function, match results for basic blocks, match results for instructions, number of features)
|
||||||
|
"""
|
||||||
|
# all features found within this function,
|
||||||
|
# includes features found within basic blocks (and instructions).
|
||||||
|
function_features: FeatureSet = collections.defaultdict(set)
|
||||||
|
|
||||||
|
# matches found at the basic block scope.
|
||||||
|
# might be found at different basic blocks, that's ok.
|
||||||
|
bb_matches: MatchResults = collections.defaultdict(list)
|
||||||
|
|
||||||
|
# matches found at the instruction scope.
|
||||||
|
# might be found at different instructions, that's ok.
|
||||||
|
insn_matches: MatchResults = collections.defaultdict(list)
|
||||||
|
|
||||||
|
for bb in extractor.get_basic_blocks(fh):
|
||||||
|
features, bmatches, imatches = find_basic_block_capabilities(ruleset, extractor, fh, bb)
|
||||||
|
for feature, vas in features.items():
|
||||||
|
function_features[feature].update(vas)
|
||||||
|
|
||||||
|
for rule_name, res in bmatches.items():
|
||||||
|
bb_matches[rule_name].extend(res)
|
||||||
|
|
||||||
|
for rule_name, res in imatches.items():
|
||||||
|
insn_matches[rule_name].extend(res)
|
||||||
|
|
||||||
|
for feature, va in itertools.chain(extractor.extract_function_features(fh), extractor.extract_global_features()):
|
||||||
|
function_features[feature].add(va)
|
||||||
|
|
||||||
|
_, function_matches = ruleset.match(Scope.FUNCTION, function_features, fh.address)
|
||||||
|
return function_matches, bb_matches, insn_matches, len(function_features)
|
||||||
|
|
||||||
|
|
||||||
|
def find_static_capabilities(
|
||||||
|
ruleset: RuleSet, extractor: StaticFeatureExtractor, disable_progress=None
|
||||||
|
) -> Tuple[MatchResults, Any]:
|
||||||
|
all_function_matches: MatchResults = collections.defaultdict(list)
|
||||||
|
all_bb_matches: MatchResults = collections.defaultdict(list)
|
||||||
|
all_insn_matches: MatchResults = collections.defaultdict(list)
|
||||||
|
|
||||||
|
feature_counts = rdoc.StaticFeatureCounts(file=0, functions=())
|
||||||
|
library_functions: Tuple[rdoc.LibraryFunction, ...] = ()
|
||||||
|
|
||||||
|
assert isinstance(extractor, StaticFeatureExtractor)
|
||||||
|
functions: List[FunctionHandle] = list(extractor.get_functions())
|
||||||
|
n_funcs: int = len(functions)
|
||||||
|
n_libs: int = 0
|
||||||
|
percentage: float = 0
|
||||||
|
|
||||||
|
with capa.helpers.CapaProgressBar(
|
||||||
|
console=capa.helpers.log_console, transient=True, disable=disable_progress
|
||||||
|
) as pbar:
|
||||||
|
task = pbar.add_task(
|
||||||
|
"matching", total=n_funcs, unit="functions", postfix=f"skipped {n_libs} library functions, {percentage}%"
|
||||||
|
)
|
||||||
|
for f in functions:
|
||||||
|
t0 = time.time()
|
||||||
|
if extractor.is_library_function(f.address):
|
||||||
|
function_name = extractor.get_function_name(f.address)
|
||||||
|
logger.debug("skipping library function 0x%x (%s)", f.address, function_name)
|
||||||
|
library_functions += (
|
||||||
|
rdoc.LibraryFunction(address=frz.Address.from_capa(f.address), name=function_name),
|
||||||
|
)
|
||||||
|
n_libs = len(library_functions)
|
||||||
|
percentage = round(100 * (n_libs / n_funcs))
|
||||||
|
pbar.update(task, postfix=f"skipped {n_libs} library functions, {percentage}%")
|
||||||
|
pbar.advance(task)
|
||||||
|
continue
|
||||||
|
|
||||||
|
function_matches, bb_matches, insn_matches, feature_count = find_code_capabilities(ruleset, extractor, f)
|
||||||
|
feature_counts.functions += (
|
||||||
|
rdoc.FunctionFeatureCount(address=frz.Address.from_capa(f.address), count=feature_count),
|
||||||
|
)
|
||||||
|
t1 = time.time()
|
||||||
|
|
||||||
|
match_count = 0
|
||||||
|
for name, matches_ in itertools.chain(function_matches.items(), bb_matches.items(), insn_matches.items()):
|
||||||
|
if not ruleset.rules[name].is_subscope_rule():
|
||||||
|
match_count += len(matches_)
|
||||||
|
|
||||||
|
logger.debug(
|
||||||
|
"analyzed function 0x%x and extracted %d features, %d matches in %0.02fs",
|
||||||
|
f.address,
|
||||||
|
feature_count,
|
||||||
|
match_count,
|
||||||
|
t1 - t0,
|
||||||
|
)
|
||||||
|
|
||||||
|
for rule_name, res in function_matches.items():
|
||||||
|
all_function_matches[rule_name].extend(res)
|
||||||
|
for rule_name, res in bb_matches.items():
|
||||||
|
all_bb_matches[rule_name].extend(res)
|
||||||
|
for rule_name, res in insn_matches.items():
|
||||||
|
all_insn_matches[rule_name].extend(res)
|
||||||
|
|
||||||
|
pbar.advance(task)
|
||||||
|
|
||||||
|
# collection of features that captures the rule matches within function, BB, and instruction scopes.
|
||||||
|
# mapping from feature (matched rule) to set of addresses at which it matched.
|
||||||
|
function_and_lower_features: FeatureSet = collections.defaultdict(set)
|
||||||
|
for rule_name, results in itertools.chain(
|
||||||
|
all_function_matches.items(), all_bb_matches.items(), all_insn_matches.items()
|
||||||
|
):
|
||||||
|
locations = {p[0] for p in results}
|
||||||
|
rule = ruleset[rule_name]
|
||||||
|
capa.engine.index_rule_matches(function_and_lower_features, rule, locations)
|
||||||
|
|
||||||
|
all_file_matches, feature_count = find_file_capabilities(ruleset, extractor, function_and_lower_features)
|
||||||
|
feature_counts.file = feature_count
|
||||||
|
|
||||||
|
matches: MatchResults = dict(
|
||||||
|
itertools.chain(
|
||||||
|
# each rule exists in exactly one scope,
|
||||||
|
# so there won't be any overlap among these following MatchResults,
|
||||||
|
# and we can merge the dictionaries naively.
|
||||||
|
all_insn_matches.items(),
|
||||||
|
all_bb_matches.items(),
|
||||||
|
all_function_matches.items(),
|
||||||
|
all_file_matches.items(),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
meta = {
|
||||||
|
"feature_counts": feature_counts,
|
||||||
|
"library_functions": library_functions,
|
||||||
|
}
|
||||||
|
|
||||||
|
return matches, meta
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
# Copyright (C) 2020 Mandiant, Inc. All Rights Reserved.
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
# you may not use this file except in compliance with the License.
|
# you may not use this file except in compliance with the License.
|
||||||
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
||||||
@@ -102,14 +102,14 @@ class And(Statement):
|
|||||||
super().__init__(description=description)
|
super().__init__(description=description)
|
||||||
self.children = children
|
self.children = children
|
||||||
|
|
||||||
def evaluate(self, ctx, short_circuit=True):
|
def evaluate(self, features: FeatureSet, short_circuit=True):
|
||||||
capa.perf.counters["evaluate.feature"] += 1
|
capa.perf.counters["evaluate.feature"] += 1
|
||||||
capa.perf.counters["evaluate.feature.and"] += 1
|
capa.perf.counters["evaluate.feature.and"] += 1
|
||||||
|
|
||||||
if short_circuit:
|
if short_circuit:
|
||||||
results = []
|
results = []
|
||||||
for child in self.children:
|
for child in self.children:
|
||||||
result = child.evaluate(ctx, short_circuit=short_circuit)
|
result = child.evaluate(features, short_circuit=short_circuit)
|
||||||
results.append(result)
|
results.append(result)
|
||||||
if not result:
|
if not result:
|
||||||
# short circuit
|
# short circuit
|
||||||
@@ -117,7 +117,7 @@ class And(Statement):
|
|||||||
|
|
||||||
return Result(True, self, results)
|
return Result(True, self, results)
|
||||||
else:
|
else:
|
||||||
results = [child.evaluate(ctx, short_circuit=short_circuit) for child in self.children]
|
results = [child.evaluate(features, short_circuit=short_circuit) for child in self.children]
|
||||||
success = all(results)
|
success = all(results)
|
||||||
return Result(success, self, results)
|
return Result(success, self, results)
|
||||||
|
|
||||||
@@ -135,14 +135,14 @@ class Or(Statement):
|
|||||||
super().__init__(description=description)
|
super().__init__(description=description)
|
||||||
self.children = children
|
self.children = children
|
||||||
|
|
||||||
def evaluate(self, ctx, short_circuit=True):
|
def evaluate(self, features: FeatureSet, short_circuit=True):
|
||||||
capa.perf.counters["evaluate.feature"] += 1
|
capa.perf.counters["evaluate.feature"] += 1
|
||||||
capa.perf.counters["evaluate.feature.or"] += 1
|
capa.perf.counters["evaluate.feature.or"] += 1
|
||||||
|
|
||||||
if short_circuit:
|
if short_circuit:
|
||||||
results = []
|
results = []
|
||||||
for child in self.children:
|
for child in self.children:
|
||||||
result = child.evaluate(ctx, short_circuit=short_circuit)
|
result = child.evaluate(features, short_circuit=short_circuit)
|
||||||
results.append(result)
|
results.append(result)
|
||||||
if result:
|
if result:
|
||||||
# short circuit as soon as we hit one match
|
# short circuit as soon as we hit one match
|
||||||
@@ -150,7 +150,7 @@ class Or(Statement):
|
|||||||
|
|
||||||
return Result(False, self, results)
|
return Result(False, self, results)
|
||||||
else:
|
else:
|
||||||
results = [child.evaluate(ctx, short_circuit=short_circuit) for child in self.children]
|
results = [child.evaluate(features, short_circuit=short_circuit) for child in self.children]
|
||||||
success = any(results)
|
success = any(results)
|
||||||
return Result(success, self, results)
|
return Result(success, self, results)
|
||||||
|
|
||||||
@@ -162,11 +162,11 @@ class Not(Statement):
|
|||||||
super().__init__(description=description)
|
super().__init__(description=description)
|
||||||
self.child = child
|
self.child = child
|
||||||
|
|
||||||
def evaluate(self, ctx, short_circuit=True):
|
def evaluate(self, features: FeatureSet, short_circuit=True):
|
||||||
capa.perf.counters["evaluate.feature"] += 1
|
capa.perf.counters["evaluate.feature"] += 1
|
||||||
capa.perf.counters["evaluate.feature.not"] += 1
|
capa.perf.counters["evaluate.feature.not"] += 1
|
||||||
|
|
||||||
results = [self.child.evaluate(ctx, short_circuit=short_circuit)]
|
results = [self.child.evaluate(features, short_circuit=short_circuit)]
|
||||||
success = not results[0]
|
success = not results[0]
|
||||||
return Result(success, self, results)
|
return Result(success, self, results)
|
||||||
|
|
||||||
@@ -185,7 +185,7 @@ class Some(Statement):
|
|||||||
self.count = count
|
self.count = count
|
||||||
self.children = children
|
self.children = children
|
||||||
|
|
||||||
def evaluate(self, ctx, short_circuit=True):
|
def evaluate(self, features: FeatureSet, short_circuit=True):
|
||||||
capa.perf.counters["evaluate.feature"] += 1
|
capa.perf.counters["evaluate.feature"] += 1
|
||||||
capa.perf.counters["evaluate.feature.some"] += 1
|
capa.perf.counters["evaluate.feature.some"] += 1
|
||||||
|
|
||||||
@@ -193,7 +193,7 @@ class Some(Statement):
|
|||||||
results = []
|
results = []
|
||||||
satisfied_children_count = 0
|
satisfied_children_count = 0
|
||||||
for child in self.children:
|
for child in self.children:
|
||||||
result = child.evaluate(ctx, short_circuit=short_circuit)
|
result = child.evaluate(features, short_circuit=short_circuit)
|
||||||
results.append(result)
|
results.append(result)
|
||||||
if result:
|
if result:
|
||||||
satisfied_children_count += 1
|
satisfied_children_count += 1
|
||||||
@@ -204,7 +204,7 @@ class Some(Statement):
|
|||||||
|
|
||||||
return Result(False, self, results)
|
return Result(False, self, results)
|
||||||
else:
|
else:
|
||||||
results = [child.evaluate(ctx, short_circuit=short_circuit) for child in self.children]
|
results = [child.evaluate(features, short_circuit=short_circuit) for child in self.children]
|
||||||
# note that here we cast the child result as a bool
|
# note that here we cast the child result as a bool
|
||||||
# because we've overridden `__bool__` above.
|
# because we've overridden `__bool__` above.
|
||||||
#
|
#
|
||||||
@@ -214,7 +214,7 @@ class Some(Statement):
|
|||||||
|
|
||||||
|
|
||||||
class Range(Statement):
|
class Range(Statement):
|
||||||
"""match if the child is contained in the ctx set with a count in the given range."""
|
"""match if the child is contained in the feature set with a count in the given range."""
|
||||||
|
|
||||||
def __init__(self, child, min=None, max=None, description=None):
|
def __init__(self, child, min=None, max=None, description=None):
|
||||||
super().__init__(description=description)
|
super().__init__(description=description)
|
||||||
@@ -222,15 +222,15 @@ class Range(Statement):
|
|||||||
self.min = min if min is not None else 0
|
self.min = min if min is not None else 0
|
||||||
self.max = max if max is not None else (1 << 64 - 1)
|
self.max = max if max is not None else (1 << 64 - 1)
|
||||||
|
|
||||||
def evaluate(self, ctx, **kwargs):
|
def evaluate(self, features: FeatureSet, short_circuit=True):
|
||||||
capa.perf.counters["evaluate.feature"] += 1
|
capa.perf.counters["evaluate.feature"] += 1
|
||||||
capa.perf.counters["evaluate.feature.range"] += 1
|
capa.perf.counters["evaluate.feature.range"] += 1
|
||||||
|
|
||||||
count = len(ctx.get(self.child, []))
|
count = len(features.get(self.child, []))
|
||||||
if self.min == 0 and count == 0:
|
if self.min == 0 and count == 0:
|
||||||
return Result(True, self, [])
|
return Result(True, self, [])
|
||||||
|
|
||||||
return Result(self.min <= count <= self.max, self, [], locations=ctx.get(self.child))
|
return Result(self.min <= count <= self.max, self, [], locations=features.get(self.child))
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
if self.max == (1 << 64 - 1):
|
if self.max == (1 << 64 - 1):
|
||||||
@@ -250,7 +250,7 @@ class Subscope(Statement):
|
|||||||
self.scope = scope
|
self.scope = scope
|
||||||
self.child = child
|
self.child = child
|
||||||
|
|
||||||
def evaluate(self, ctx, **kwargs):
|
def evaluate(self, features: FeatureSet, short_circuit=True):
|
||||||
raise ValueError("cannot evaluate a subscope directly!")
|
raise ValueError("cannot evaluate a subscope directly!")
|
||||||
|
|
||||||
|
|
||||||
@@ -270,6 +270,14 @@ class Subscope(Statement):
|
|||||||
MatchResults = Mapping[str, List[Tuple[Address, Result]]]
|
MatchResults = Mapping[str, List[Tuple[Address, Result]]]
|
||||||
|
|
||||||
|
|
||||||
|
def get_rule_namespaces(rule: "capa.rules.Rule") -> Iterator[str]:
|
||||||
|
namespace = rule.meta.get("namespace")
|
||||||
|
if namespace:
|
||||||
|
while namespace:
|
||||||
|
yield namespace
|
||||||
|
namespace, _, _ = namespace.rpartition("/")
|
||||||
|
|
||||||
|
|
||||||
def index_rule_matches(features: FeatureSet, rule: "capa.rules.Rule", locations: Iterable[Address]):
|
def index_rule_matches(features: FeatureSet, rule: "capa.rules.Rule", locations: Iterable[Address]):
|
||||||
"""
|
"""
|
||||||
record into the given featureset that the given rule matched at the given locations.
|
record into the given featureset that the given rule matched at the given locations.
|
||||||
@@ -280,11 +288,8 @@ def index_rule_matches(features: FeatureSet, rule: "capa.rules.Rule", locations:
|
|||||||
updates `features` in-place. doesn't modify the remaining arguments.
|
updates `features` in-place. doesn't modify the remaining arguments.
|
||||||
"""
|
"""
|
||||||
features[capa.features.common.MatchedRule(rule.name)].update(locations)
|
features[capa.features.common.MatchedRule(rule.name)].update(locations)
|
||||||
namespace = rule.meta.get("namespace")
|
for namespace in get_rule_namespaces(rule):
|
||||||
if namespace:
|
|
||||||
while namespace:
|
|
||||||
features[capa.features.common.MatchedRule(namespace)].update(locations)
|
features[capa.features.common.MatchedRule(namespace)].update(locations)
|
||||||
namespace, _, _ = namespace.rpartition("/")
|
|
||||||
|
|
||||||
|
|
||||||
def match(rules: List["capa.rules.Rule"], features: FeatureSet, addr: Address) -> Tuple[FeatureSet, MatchResults]:
|
def match(rules: List["capa.rules.Rule"], features: FeatureSet, addr: Address) -> Tuple[FeatureSet, MatchResults]:
|
||||||
@@ -304,7 +309,7 @@ def match(rules: List["capa.rules.Rule"], features: FeatureSet, addr: Address) -
|
|||||||
other strategies can be imagined that match differently; implement these elsewhere.
|
other strategies can be imagined that match differently; implement these elsewhere.
|
||||||
specifically, this routine does "top down" matching of the given rules against the feature set.
|
specifically, this routine does "top down" matching of the given rules against the feature set.
|
||||||
"""
|
"""
|
||||||
results = collections.defaultdict(list) # type: MatchResults
|
results: MatchResults = collections.defaultdict(list)
|
||||||
|
|
||||||
# copy features so that we can modify it
|
# copy features so that we can modify it
|
||||||
# without affecting the caller (keep this function pure)
|
# without affecting the caller (keep this function pure)
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
# Copyright (C) 2022 Mandiant, Inc. All Rights Reserved.
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
# you may not use this file except in compliance with the License.
|
# you may not use this file except in compliance with the License.
|
||||||
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
||||||
@@ -19,3 +19,19 @@ class UnsupportedArchError(ValueError):
|
|||||||
|
|
||||||
class UnsupportedOSError(ValueError):
|
class UnsupportedOSError(ValueError):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class EmptyReportError(ValueError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class InvalidArgument(ValueError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class NonExistantFunctionError(ValueError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class NonExistantProcessError(ValueError):
|
||||||
|
pass
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
# Copyright (C) 2022 Mandiant, Inc. All Rights Reserved.
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
# you may not use this file except in compliance with the License.
|
# you may not use this file except in compliance with the License.
|
||||||
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
||||||
@@ -10,8 +10,7 @@ import abc
|
|||||||
|
|
||||||
class Address(abc.ABC):
|
class Address(abc.ABC):
|
||||||
@abc.abstractmethod
|
@abc.abstractmethod
|
||||||
def __eq__(self, other):
|
def __eq__(self, other): ...
|
||||||
...
|
|
||||||
|
|
||||||
@abc.abstractmethod
|
@abc.abstractmethod
|
||||||
def __lt__(self, other):
|
def __lt__(self, other):
|
||||||
@@ -43,6 +42,79 @@ class AbsoluteVirtualAddress(int, Address):
|
|||||||
return int.__hash__(self)
|
return int.__hash__(self)
|
||||||
|
|
||||||
|
|
||||||
|
class ProcessAddress(Address):
|
||||||
|
"""an address of a process in a dynamic execution trace"""
|
||||||
|
|
||||||
|
def __init__(self, pid: int, ppid: int = 0):
|
||||||
|
assert ppid >= 0
|
||||||
|
assert pid > 0
|
||||||
|
self.ppid = ppid
|
||||||
|
self.pid = pid
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return "process(%s%s)" % (
|
||||||
|
f"ppid: {self.ppid}, " if self.ppid > 0 else "",
|
||||||
|
f"pid: {self.pid}",
|
||||||
|
)
|
||||||
|
|
||||||
|
def __hash__(self):
|
||||||
|
return hash((self.ppid, self.pid))
|
||||||
|
|
||||||
|
def __eq__(self, other):
|
||||||
|
assert isinstance(other, ProcessAddress)
|
||||||
|
return (self.ppid, self.pid) == (other.ppid, other.pid)
|
||||||
|
|
||||||
|
def __lt__(self, other):
|
||||||
|
assert isinstance(other, ProcessAddress)
|
||||||
|
return (self.ppid, self.pid) < (other.ppid, other.pid)
|
||||||
|
|
||||||
|
|
||||||
|
class ThreadAddress(Address):
|
||||||
|
"""addresses a thread in a dynamic execution trace"""
|
||||||
|
|
||||||
|
def __init__(self, process: ProcessAddress, tid: int):
|
||||||
|
assert tid >= 0
|
||||||
|
self.process = process
|
||||||
|
self.tid = tid
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return f"{self.process}, thread(tid: {self.tid})"
|
||||||
|
|
||||||
|
def __hash__(self):
|
||||||
|
return hash((self.process, self.tid))
|
||||||
|
|
||||||
|
def __eq__(self, other):
|
||||||
|
assert isinstance(other, ThreadAddress)
|
||||||
|
return (self.process, self.tid) == (other.process, other.tid)
|
||||||
|
|
||||||
|
def __lt__(self, other):
|
||||||
|
assert isinstance(other, ThreadAddress)
|
||||||
|
return (self.process, self.tid) < (other.process, other.tid)
|
||||||
|
|
||||||
|
|
||||||
|
class DynamicCallAddress(Address):
|
||||||
|
"""addresses a call in a dynamic execution trace"""
|
||||||
|
|
||||||
|
def __init__(self, thread: ThreadAddress, id: int):
|
||||||
|
assert id >= 0
|
||||||
|
self.thread = thread
|
||||||
|
self.id = id
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return f"{self.thread}, call(id: {self.id})"
|
||||||
|
|
||||||
|
def __hash__(self):
|
||||||
|
return hash((self.thread, self.id))
|
||||||
|
|
||||||
|
def __eq__(self, other):
|
||||||
|
assert isinstance(other, DynamicCallAddress)
|
||||||
|
return (self.thread, self.id) == (other.thread, other.id)
|
||||||
|
|
||||||
|
def __lt__(self, other):
|
||||||
|
assert isinstance(other, DynamicCallAddress)
|
||||||
|
return (self.thread, self.id) < (other.thread, other.id)
|
||||||
|
|
||||||
|
|
||||||
class RelativeVirtualAddress(int, Address):
|
class RelativeVirtualAddress(int, Address):
|
||||||
"""a memory address relative to a base address"""
|
"""a memory address relative to a base address"""
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
# Copyright (C) 2020 Mandiant, Inc. All Rights Reserved.
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
# you may not use this file except in compliance with the License.
|
# you may not use this file except in compliance with the License.
|
||||||
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
||||||
|
|||||||
36
capa/features/com/__init__.py
Normal file
36
capa/features/com/__init__.py
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
# Copyright (C) 2024 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
from enum import Enum
|
||||||
|
from typing import Dict, List
|
||||||
|
|
||||||
|
from capa.helpers import assert_never
|
||||||
|
|
||||||
|
|
||||||
|
class ComType(Enum):
|
||||||
|
CLASS = "class"
|
||||||
|
INTERFACE = "interface"
|
||||||
|
|
||||||
|
|
||||||
|
COM_PREFIXES = {
|
||||||
|
ComType.CLASS: "CLSID_",
|
||||||
|
ComType.INTERFACE: "IID_",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def load_com_database(com_type: ComType) -> Dict[str, List[str]]:
|
||||||
|
# lazy load these python files since they are so large.
|
||||||
|
# that is, don't load them unless a COM feature is being handled.
|
||||||
|
import capa.features.com.classes
|
||||||
|
import capa.features.com.interfaces
|
||||||
|
|
||||||
|
if com_type == ComType.CLASS:
|
||||||
|
return capa.features.com.classes.COM_CLASSES
|
||||||
|
elif com_type == ComType.INTERFACE:
|
||||||
|
return capa.features.com.interfaces.COM_INTERFACES
|
||||||
|
else:
|
||||||
|
assert_never(com_type)
|
||||||
3696
capa/features/com/classes.py
Normal file
3696
capa/features/com/classes.py
Normal file
File diff suppressed because it is too large
Load Diff
28231
capa/features/com/interfaces.py
Normal file
28231
capa/features/com/interfaces.py
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,4 +1,4 @@
|
|||||||
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
# Copyright (C) 2021 Mandiant, Inc. All Rights Reserved.
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
# you may not use this file except in compliance with the License.
|
# you may not use this file except in compliance with the License.
|
||||||
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
||||||
@@ -128,7 +128,7 @@ class Feature(abc.ABC): # noqa: B024
|
|||||||
|
|
||||||
def __lt__(self, other):
|
def __lt__(self, other):
|
||||||
# implementing sorting by serializing to JSON is a huge hack.
|
# implementing sorting by serializing to JSON is a huge hack.
|
||||||
# its slow, inelegant, and probably doesn't work intuitively;
|
# it's slow, inelegant, and probably doesn't work intuitively;
|
||||||
# however, we only use it for deterministic output, so it's good enough for now.
|
# however, we only use it for deterministic output, so it's good enough for now.
|
||||||
|
|
||||||
# circular import
|
# circular import
|
||||||
@@ -166,10 +166,10 @@ class Feature(abc.ABC): # noqa: B024
|
|||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
return str(self)
|
return str(self)
|
||||||
|
|
||||||
def evaluate(self, ctx: Dict["Feature", Set[Address]], **kwargs) -> Result:
|
def evaluate(self, features: "capa.engine.FeatureSet", short_circuit=True) -> Result:
|
||||||
capa.perf.counters["evaluate.feature"] += 1
|
capa.perf.counters["evaluate.feature"] += 1
|
||||||
capa.perf.counters["evaluate.feature." + self.name] += 1
|
capa.perf.counters["evaluate.feature." + self.name] += 1
|
||||||
return Result(self in ctx, self, [], locations=ctx.get(self, set()))
|
return Result(self in features, self, [], locations=features.get(self, set()))
|
||||||
|
|
||||||
|
|
||||||
class MatchedRule(Feature):
|
class MatchedRule(Feature):
|
||||||
@@ -207,7 +207,7 @@ class Substring(String):
|
|||||||
super().__init__(value, description=description)
|
super().__init__(value, description=description)
|
||||||
self.value = value
|
self.value = value
|
||||||
|
|
||||||
def evaluate(self, ctx, short_circuit=True):
|
def evaluate(self, features: "capa.engine.FeatureSet", short_circuit=True):
|
||||||
capa.perf.counters["evaluate.feature"] += 1
|
capa.perf.counters["evaluate.feature"] += 1
|
||||||
capa.perf.counters["evaluate.feature.substring"] += 1
|
capa.perf.counters["evaluate.feature.substring"] += 1
|
||||||
|
|
||||||
@@ -216,7 +216,7 @@ class Substring(String):
|
|||||||
matches: typing.DefaultDict[str, Set[Address]] = collections.defaultdict(set)
|
matches: typing.DefaultDict[str, Set[Address]] = collections.defaultdict(set)
|
||||||
|
|
||||||
assert isinstance(self.value, str)
|
assert isinstance(self.value, str)
|
||||||
for feature, locations in ctx.items():
|
for feature, locations in features.items():
|
||||||
if not isinstance(feature, (String,)):
|
if not isinstance(feature, (String,)):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
@@ -227,7 +227,7 @@ class Substring(String):
|
|||||||
if self.value in feature.value:
|
if self.value in feature.value:
|
||||||
matches[feature.value].update(locations)
|
matches[feature.value].update(locations)
|
||||||
if short_circuit:
|
if short_circuit:
|
||||||
# we found one matching string, thats sufficient to match.
|
# we found one matching string, that's sufficient to match.
|
||||||
# don't collect other matching strings in this mode.
|
# don't collect other matching strings in this mode.
|
||||||
break
|
break
|
||||||
|
|
||||||
@@ -299,7 +299,7 @@ class Regex(String):
|
|||||||
f"invalid regular expression: {value} it should use Python syntax, try it at https://pythex.org"
|
f"invalid regular expression: {value} it should use Python syntax, try it at https://pythex.org"
|
||||||
) from exc
|
) from exc
|
||||||
|
|
||||||
def evaluate(self, ctx, short_circuit=True):
|
def evaluate(self, features: "capa.engine.FeatureSet", short_circuit=True):
|
||||||
capa.perf.counters["evaluate.feature"] += 1
|
capa.perf.counters["evaluate.feature"] += 1
|
||||||
capa.perf.counters["evaluate.feature.regex"] += 1
|
capa.perf.counters["evaluate.feature.regex"] += 1
|
||||||
|
|
||||||
@@ -307,7 +307,7 @@ class Regex(String):
|
|||||||
# will unique the locations later on.
|
# will unique the locations later on.
|
||||||
matches: typing.DefaultDict[str, Set[Address]] = collections.defaultdict(set)
|
matches: typing.DefaultDict[str, Set[Address]] = collections.defaultdict(set)
|
||||||
|
|
||||||
for feature, locations in ctx.items():
|
for feature, locations in features.items():
|
||||||
if not isinstance(feature, (String,)):
|
if not isinstance(feature, (String,)):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
@@ -322,7 +322,7 @@ class Regex(String):
|
|||||||
if self.re.search(feature.value):
|
if self.re.search(feature.value):
|
||||||
matches[feature.value].update(locations)
|
matches[feature.value].update(locations)
|
||||||
if short_circuit:
|
if short_circuit:
|
||||||
# we found one matching string, thats sufficient to match.
|
# we found one matching string, that's sufficient to match.
|
||||||
# don't collect other matching strings in this mode.
|
# don't collect other matching strings in this mode.
|
||||||
break
|
break
|
||||||
|
|
||||||
@@ -384,12 +384,14 @@ class Bytes(Feature):
|
|||||||
super().__init__(value, description=description)
|
super().__init__(value, description=description)
|
||||||
self.value = value
|
self.value = value
|
||||||
|
|
||||||
def evaluate(self, ctx, **kwargs):
|
def evaluate(self, features: "capa.engine.FeatureSet", short_circuit=True):
|
||||||
|
assert isinstance(self.value, bytes)
|
||||||
|
|
||||||
capa.perf.counters["evaluate.feature"] += 1
|
capa.perf.counters["evaluate.feature"] += 1
|
||||||
capa.perf.counters["evaluate.feature.bytes"] += 1
|
capa.perf.counters["evaluate.feature.bytes"] += 1
|
||||||
|
capa.perf.counters["evaluate.feature.bytes." + str(len(self.value))] += 1
|
||||||
|
|
||||||
assert isinstance(self.value, bytes)
|
for feature, locations in features.items():
|
||||||
for feature, locations in ctx.items():
|
|
||||||
if not isinstance(feature, (Bytes,)):
|
if not isinstance(feature, (Bytes,)):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
@@ -407,9 +409,10 @@ class Bytes(Feature):
|
|||||||
# other candidates here: https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#machine-types
|
# other candidates here: https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#machine-types
|
||||||
ARCH_I386 = "i386"
|
ARCH_I386 = "i386"
|
||||||
ARCH_AMD64 = "amd64"
|
ARCH_AMD64 = "amd64"
|
||||||
|
ARCH_AARCH64 = "aarch64"
|
||||||
# dotnet
|
# dotnet
|
||||||
ARCH_ANY = "any"
|
ARCH_ANY = "any"
|
||||||
VALID_ARCH = (ARCH_I386, ARCH_AMD64, ARCH_ANY)
|
VALID_ARCH = (ARCH_I386, ARCH_AMD64, ARCH_AARCH64, ARCH_ANY)
|
||||||
|
|
||||||
|
|
||||||
class Arch(Feature):
|
class Arch(Feature):
|
||||||
@@ -421,10 +424,11 @@ class Arch(Feature):
|
|||||||
OS_WINDOWS = "windows"
|
OS_WINDOWS = "windows"
|
||||||
OS_LINUX = "linux"
|
OS_LINUX = "linux"
|
||||||
OS_MACOS = "macos"
|
OS_MACOS = "macos"
|
||||||
|
OS_ANDROID = "android"
|
||||||
# dotnet
|
# dotnet
|
||||||
OS_ANY = "any"
|
OS_ANY = "any"
|
||||||
VALID_OS = {os.value for os in capa.features.extractors.elf.OS}
|
VALID_OS = {os.value for os in capa.features.extractors.elf.OS}
|
||||||
VALID_OS.update({OS_WINDOWS, OS_LINUX, OS_MACOS, OS_ANY})
|
VALID_OS.update({OS_WINDOWS, OS_LINUX, OS_MACOS, OS_ANY, OS_ANDROID})
|
||||||
# internal only, not to be used in rules
|
# internal only, not to be used in rules
|
||||||
OS_AUTO = "auto"
|
OS_AUTO = "auto"
|
||||||
|
|
||||||
@@ -434,11 +438,11 @@ class OS(Feature):
|
|||||||
super().__init__(value, description=description)
|
super().__init__(value, description=description)
|
||||||
self.name = "os"
|
self.name = "os"
|
||||||
|
|
||||||
def evaluate(self, ctx, **kwargs):
|
def evaluate(self, features: "capa.engine.FeatureSet", short_circuit=True):
|
||||||
capa.perf.counters["evaluate.feature"] += 1
|
capa.perf.counters["evaluate.feature"] += 1
|
||||||
capa.perf.counters["evaluate.feature." + self.name] += 1
|
capa.perf.counters["evaluate.feature." + self.name] += 1
|
||||||
|
|
||||||
for feature, locations in ctx.items():
|
for feature, locations in features.items():
|
||||||
if not isinstance(feature, (OS,)):
|
if not isinstance(feature, (OS,)):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
@@ -457,8 +461,29 @@ VALID_FORMAT = (FORMAT_PE, FORMAT_ELF, FORMAT_DOTNET)
|
|||||||
FORMAT_AUTO = "auto"
|
FORMAT_AUTO = "auto"
|
||||||
FORMAT_SC32 = "sc32"
|
FORMAT_SC32 = "sc32"
|
||||||
FORMAT_SC64 = "sc64"
|
FORMAT_SC64 = "sc64"
|
||||||
|
FORMAT_CAPE = "cape"
|
||||||
|
FORMAT_DRAKVUF = "drakvuf"
|
||||||
|
FORMAT_VMRAY = "vmray"
|
||||||
|
FORMAT_BINEXPORT2 = "binexport2"
|
||||||
FORMAT_FREEZE = "freeze"
|
FORMAT_FREEZE = "freeze"
|
||||||
FORMAT_RESULT = "result"
|
FORMAT_RESULT = "result"
|
||||||
|
STATIC_FORMATS = {
|
||||||
|
FORMAT_SC32,
|
||||||
|
FORMAT_SC64,
|
||||||
|
FORMAT_PE,
|
||||||
|
FORMAT_ELF,
|
||||||
|
FORMAT_DOTNET,
|
||||||
|
FORMAT_FREEZE,
|
||||||
|
FORMAT_RESULT,
|
||||||
|
FORMAT_BINEXPORT2,
|
||||||
|
}
|
||||||
|
DYNAMIC_FORMATS = {
|
||||||
|
FORMAT_CAPE,
|
||||||
|
FORMAT_DRAKVUF,
|
||||||
|
FORMAT_VMRAY,
|
||||||
|
FORMAT_FREEZE,
|
||||||
|
FORMAT_RESULT,
|
||||||
|
}
|
||||||
FORMAT_UNKNOWN = "unknown"
|
FORMAT_UNKNOWN = "unknown"
|
||||||
|
|
||||||
|
|
||||||
@@ -471,6 +496,6 @@ class Format(Feature):
|
|||||||
def is_global_feature(feature):
|
def is_global_feature(feature):
|
||||||
"""
|
"""
|
||||||
is this a feature that is extracted at every scope?
|
is this a feature that is extracted at every scope?
|
||||||
today, these are OS and arch features.
|
today, these are OS, arch, and format features.
|
||||||
"""
|
"""
|
||||||
return isinstance(feature, (OS, Arch))
|
return isinstance(feature, (OS, Arch, Format))
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
# Copyright (C) 2021 Mandiant, Inc. All Rights Reserved.
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
# you may not use this file except in compliance with the License.
|
# you may not use this file except in compliance with the License.
|
||||||
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
||||||
@@ -7,13 +7,20 @@
|
|||||||
# See the License for the specific language governing permissions and limitations under the License.
|
# See the License for the specific language governing permissions and limitations under the License.
|
||||||
|
|
||||||
import abc
|
import abc
|
||||||
|
import hashlib
|
||||||
import dataclasses
|
import dataclasses
|
||||||
from typing import Any, Dict, Tuple, Union, Iterator
|
from copy import copy
|
||||||
|
from types import MethodType
|
||||||
|
from typing import Any, Set, Dict, Tuple, Union, Iterator
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
# TODO(williballenthin): use typing.TypeAlias directly when Python 3.9 is deprecated
|
||||||
|
# https://github.com/mandiant/capa/issues/1699
|
||||||
|
from typing_extensions import TypeAlias
|
||||||
|
|
||||||
import capa.features.address
|
import capa.features.address
|
||||||
from capa.features.common import Feature
|
from capa.features.common import Feature
|
||||||
from capa.features.address import Address, AbsoluteVirtualAddress
|
from capa.features.address import Address, ThreadAddress, ProcessAddress, DynamicCallAddress, AbsoluteVirtualAddress
|
||||||
|
|
||||||
# feature extractors may reference functions, BBs, insns by opaque handle values.
|
# feature extractors may reference functions, BBs, insns by opaque handle values.
|
||||||
# you can use the `.address` property to get and render the address of the feature.
|
# you can use the `.address` property to get and render the address of the feature.
|
||||||
@@ -22,6 +29,24 @@ from capa.features.address import Address, AbsoluteVirtualAddress
|
|||||||
# the feature extractor from which they were created.
|
# the feature extractor from which they were created.
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class SampleHashes:
|
||||||
|
md5: str
|
||||||
|
sha1: str
|
||||||
|
sha256: str
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_bytes(cls, buf: bytes) -> "SampleHashes":
|
||||||
|
md5 = hashlib.md5()
|
||||||
|
sha1 = hashlib.sha1()
|
||||||
|
sha256 = hashlib.sha256()
|
||||||
|
md5.update(buf)
|
||||||
|
sha1.update(buf)
|
||||||
|
sha256.update(buf)
|
||||||
|
|
||||||
|
return cls(md5=md5.hexdigest(), sha1=sha1.hexdigest(), sha256=sha256.hexdigest())
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class FunctionHandle:
|
class FunctionHandle:
|
||||||
"""reference to a function recognized by a feature extractor.
|
"""reference to a function recognized by a feature extractor.
|
||||||
@@ -52,7 +77,7 @@ class BBHandle:
|
|||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class InsnHandle:
|
class InsnHandle:
|
||||||
"""reference to a instruction recognized by a feature extractor.
|
"""reference to an instruction recognized by a feature extractor.
|
||||||
|
|
||||||
Attributes:
|
Attributes:
|
||||||
address: the address of the instruction address.
|
address: the address of the instruction address.
|
||||||
@@ -63,16 +88,18 @@ class InsnHandle:
|
|||||||
inner: Any
|
inner: Any
|
||||||
|
|
||||||
|
|
||||||
class FeatureExtractor:
|
class StaticFeatureExtractor:
|
||||||
"""
|
"""
|
||||||
FeatureExtractor defines the interface for fetching features from a sample.
|
StaticFeatureExtractor defines the interface for fetching features from a
|
||||||
|
sample without running it; extractors that rely on the execution trace of
|
||||||
|
a sample must implement the other sibling class, DynamicFeatureExtracor.
|
||||||
|
|
||||||
There may be multiple backends that support fetching features for capa.
|
There may be multiple backends that support fetching features for capa.
|
||||||
For example, we use vivisect by default, but also want to support saving
|
For example, we use vivisect by default, but also want to support saving
|
||||||
and restoring features from a JSON file.
|
and restoring features from a JSON file.
|
||||||
When we restore the features, we'd like to use exactly the same matching logic
|
When we restore the features, we'd like to use exactly the same matching logic
|
||||||
to find matching rules.
|
to find matching rules.
|
||||||
Therefore, we can define a FeatureExtractor that provides features from the
|
Therefore, we can define a StaticFeatureExtractor that provides features from the
|
||||||
serialized JSON file and do matching without a binary analysis pass.
|
serialized JSON file and do matching without a binary analysis pass.
|
||||||
Also, this provides a way to hook in an IDA backend.
|
Also, this provides a way to hook in an IDA backend.
|
||||||
|
|
||||||
@@ -81,13 +108,14 @@ class FeatureExtractor:
|
|||||||
|
|
||||||
__metaclass__ = abc.ABCMeta
|
__metaclass__ = abc.ABCMeta
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self, hashes: SampleHashes):
|
||||||
#
|
#
|
||||||
# note: a subclass should define ctor parameters for its own use.
|
# note: a subclass should define ctor parameters for its own use.
|
||||||
# for example, the Vivisect feature extract might require the vw and/or path.
|
# for example, the Vivisect feature extract might require the vw and/or path.
|
||||||
# this base class doesn't know what to do with that info, though.
|
# this base class doesn't know what to do with that info, though.
|
||||||
#
|
#
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
self._sample_hashes = hashes
|
||||||
|
|
||||||
@abc.abstractmethod
|
@abc.abstractmethod
|
||||||
def get_base_address(self) -> Union[AbsoluteVirtualAddress, capa.features.address._NoAddress]:
|
def get_base_address(self) -> Union[AbsoluteVirtualAddress, capa.features.address._NoAddress]:
|
||||||
@@ -100,6 +128,12 @@ class FeatureExtractor:
|
|||||||
"""
|
"""
|
||||||
raise NotImplementedError()
|
raise NotImplementedError()
|
||||||
|
|
||||||
|
def get_sample_hashes(self) -> SampleHashes:
|
||||||
|
"""
|
||||||
|
fetch the hashes for the sample contained within the extractor.
|
||||||
|
"""
|
||||||
|
return self._sample_hashes
|
||||||
|
|
||||||
@abc.abstractmethod
|
@abc.abstractmethod
|
||||||
def extract_global_features(self) -> Iterator[Tuple[Feature, Address]]:
|
def extract_global_features(self) -> Iterator[Tuple[Feature, Address]]:
|
||||||
"""
|
"""
|
||||||
@@ -262,3 +296,209 @@ class FeatureExtractor:
|
|||||||
Tuple[Feature, Address]: feature and its location
|
Tuple[Feature, Address]: feature and its location
|
||||||
"""
|
"""
|
||||||
raise NotImplementedError()
|
raise NotImplementedError()
|
||||||
|
|
||||||
|
|
||||||
|
def FunctionFilter(extractor: StaticFeatureExtractor, functions: Set) -> StaticFeatureExtractor:
|
||||||
|
original_get_functions = extractor.get_functions
|
||||||
|
|
||||||
|
def filtered_get_functions(self):
|
||||||
|
yield from (f for f in original_get_functions() if f.address in functions)
|
||||||
|
|
||||||
|
# we make a copy of the original extractor object and then update its get_functions() method with the decorated filter one.
|
||||||
|
# this is in order to preserve the original extractor object's get_functions() method, in case it is used elsewhere in the code.
|
||||||
|
# an example where this is important is in our testfiles where we may use the same extractor object with different tests,
|
||||||
|
# with some of these tests needing to install a functions filter on the extractor object.
|
||||||
|
new_extractor = copy(extractor)
|
||||||
|
new_extractor.get_functions = MethodType(filtered_get_functions, extractor) # type: ignore
|
||||||
|
|
||||||
|
return new_extractor
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class ProcessHandle:
|
||||||
|
"""
|
||||||
|
reference to a process extracted by the sandbox.
|
||||||
|
|
||||||
|
Attributes:
|
||||||
|
address: process's address (pid)
|
||||||
|
inner: sandbox-specific data
|
||||||
|
"""
|
||||||
|
|
||||||
|
address: ProcessAddress
|
||||||
|
inner: Any
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class ThreadHandle:
|
||||||
|
"""
|
||||||
|
reference to a thread extracted by the sandbox.
|
||||||
|
|
||||||
|
Attributes:
|
||||||
|
address: thread's address (tid)
|
||||||
|
inner: sandbox-specific data
|
||||||
|
"""
|
||||||
|
|
||||||
|
address: ThreadAddress
|
||||||
|
inner: Any
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class CallHandle:
|
||||||
|
"""
|
||||||
|
reference to an api call extracted by the sandbox.
|
||||||
|
|
||||||
|
Attributes:
|
||||||
|
address: call's address, such as event index or id
|
||||||
|
inner: sandbox-specific data
|
||||||
|
"""
|
||||||
|
|
||||||
|
address: DynamicCallAddress
|
||||||
|
inner: Any
|
||||||
|
|
||||||
|
|
||||||
|
class DynamicFeatureExtractor:
|
||||||
|
"""
|
||||||
|
DynamicFeatureExtractor defines the interface for fetching features from a
|
||||||
|
sandbox' analysis of a sample; extractors that rely on statically analyzing
|
||||||
|
a sample must implement the sibling extractor, StaticFeatureExtractor.
|
||||||
|
|
||||||
|
Features are grouped mainly into threads that alongside their meta-features are also grouped into
|
||||||
|
processes (that also have their own features). Other scopes (such as function and file) may also apply
|
||||||
|
for a specific sandbox.
|
||||||
|
|
||||||
|
This class is not instantiated directly; it is the base class for other implementations.
|
||||||
|
"""
|
||||||
|
|
||||||
|
__metaclass__ = abc.ABCMeta
|
||||||
|
|
||||||
|
def __init__(self, hashes: SampleHashes):
|
||||||
|
#
|
||||||
|
# note: a subclass should define ctor parameters for its own use.
|
||||||
|
# for example, the Vivisect feature extract might require the vw and/or path.
|
||||||
|
# this base class doesn't know what to do with that info, though.
|
||||||
|
#
|
||||||
|
super().__init__()
|
||||||
|
self._sample_hashes = hashes
|
||||||
|
|
||||||
|
def get_sample_hashes(self) -> SampleHashes:
|
||||||
|
"""
|
||||||
|
fetch the hashes for the sample contained within the extractor.
|
||||||
|
"""
|
||||||
|
return self._sample_hashes
|
||||||
|
|
||||||
|
@abc.abstractmethod
|
||||||
|
def extract_global_features(self) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
"""
|
||||||
|
extract features found at every scope ("global").
|
||||||
|
|
||||||
|
example::
|
||||||
|
|
||||||
|
extractor = CapeFeatureExtractor.from_report(json.loads(buf))
|
||||||
|
for feature, addr in extractor.get_global_features():
|
||||||
|
print(addr, feature)
|
||||||
|
|
||||||
|
yields:
|
||||||
|
Tuple[Feature, Address]: feature and its location
|
||||||
|
"""
|
||||||
|
raise NotImplementedError()
|
||||||
|
|
||||||
|
@abc.abstractmethod
|
||||||
|
def extract_file_features(self) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
"""
|
||||||
|
extract file-scope features.
|
||||||
|
|
||||||
|
example::
|
||||||
|
|
||||||
|
extractor = CapeFeatureExtractor.from_report(json.loads(buf))
|
||||||
|
for feature, addr in extractor.get_file_features():
|
||||||
|
print(addr, feature)
|
||||||
|
|
||||||
|
yields:
|
||||||
|
Tuple[Feature, Address]: feature and its location
|
||||||
|
"""
|
||||||
|
raise NotImplementedError()
|
||||||
|
|
||||||
|
@abc.abstractmethod
|
||||||
|
def get_processes(self) -> Iterator[ProcessHandle]:
|
||||||
|
"""
|
||||||
|
Enumerate processes in the trace.
|
||||||
|
"""
|
||||||
|
raise NotImplementedError()
|
||||||
|
|
||||||
|
@abc.abstractmethod
|
||||||
|
def extract_process_features(self, ph: ProcessHandle) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
"""
|
||||||
|
Yields all the features of a process. These include:
|
||||||
|
- file features of the process' image
|
||||||
|
"""
|
||||||
|
raise NotImplementedError()
|
||||||
|
|
||||||
|
@abc.abstractmethod
|
||||||
|
def get_process_name(self, ph: ProcessHandle) -> str:
|
||||||
|
"""
|
||||||
|
Returns the human-readable name for the given process,
|
||||||
|
such as the filename.
|
||||||
|
"""
|
||||||
|
raise NotImplementedError()
|
||||||
|
|
||||||
|
@abc.abstractmethod
|
||||||
|
def get_threads(self, ph: ProcessHandle) -> Iterator[ThreadHandle]:
|
||||||
|
"""
|
||||||
|
Enumerate threads in the given process.
|
||||||
|
"""
|
||||||
|
raise NotImplementedError()
|
||||||
|
|
||||||
|
@abc.abstractmethod
|
||||||
|
def extract_thread_features(self, ph: ProcessHandle, th: ThreadHandle) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
"""
|
||||||
|
Yields all the features of a thread. These include:
|
||||||
|
- sequenced api traces
|
||||||
|
"""
|
||||||
|
raise NotImplementedError()
|
||||||
|
|
||||||
|
@abc.abstractmethod
|
||||||
|
def get_calls(self, ph: ProcessHandle, th: ThreadHandle) -> Iterator[CallHandle]:
|
||||||
|
"""
|
||||||
|
Enumerate calls in the given thread
|
||||||
|
"""
|
||||||
|
raise NotImplementedError()
|
||||||
|
|
||||||
|
@abc.abstractmethod
|
||||||
|
def extract_call_features(
|
||||||
|
self, ph: ProcessHandle, th: ThreadHandle, ch: CallHandle
|
||||||
|
) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
"""
|
||||||
|
Yields all features of a call. These include:
|
||||||
|
- api name
|
||||||
|
- bytes/strings/numbers extracted from arguments
|
||||||
|
"""
|
||||||
|
raise NotImplementedError()
|
||||||
|
|
||||||
|
@abc.abstractmethod
|
||||||
|
def get_call_name(self, ph: ProcessHandle, th: ThreadHandle, ch: CallHandle) -> str:
|
||||||
|
"""
|
||||||
|
Returns the human-readable name for the given call,
|
||||||
|
such as as rendered API log entry, like:
|
||||||
|
|
||||||
|
Foo(1, "two", b"\x00\x11") -> -1
|
||||||
|
"""
|
||||||
|
raise NotImplementedError()
|
||||||
|
|
||||||
|
|
||||||
|
def ProcessFilter(extractor: DynamicFeatureExtractor, processes: Set) -> DynamicFeatureExtractor:
|
||||||
|
original_get_processes = extractor.get_processes
|
||||||
|
|
||||||
|
def filtered_get_processes(self):
|
||||||
|
yield from (f for f in original_get_processes() if f.address.pid in processes)
|
||||||
|
|
||||||
|
# we make a copy of the original extractor object and then update its get_processes() method with the decorated filter one.
|
||||||
|
# this is in order to preserve the original extractor object's get_processes() method, in case it is used elsewhere in the code.
|
||||||
|
# an example where this is important is in our testfiles where we may use the same extractor object with different tests,
|
||||||
|
# with some of these tests needing to install a processes filter on the extractor object.
|
||||||
|
new_extractor = copy(extractor)
|
||||||
|
new_extractor.get_processes = MethodType(filtered_get_processes, extractor) # type: ignore
|
||||||
|
|
||||||
|
return new_extractor
|
||||||
|
|
||||||
|
|
||||||
|
FeatureExtractor: TypeAlias = Union[StaticFeatureExtractor, DynamicFeatureExtractor]
|
||||||
|
|||||||
416
capa/features/extractors/binexport2/__init__.py
Normal file
416
capa/features/extractors/binexport2/__init__.py
Normal file
@@ -0,0 +1,416 @@
|
|||||||
|
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
"""
|
||||||
|
Proto files generated via protobuf v24.4:
|
||||||
|
|
||||||
|
protoc --python_out=. --mypy_out=. binexport2.proto
|
||||||
|
|
||||||
|
from BinExport2 at 6916731d5f6693c4a4f0a052501fd3bd92cfd08b
|
||||||
|
https://github.com/google/binexport/blob/6916731/binexport2.proto
|
||||||
|
"""
|
||||||
|
import io
|
||||||
|
import hashlib
|
||||||
|
import logging
|
||||||
|
import contextlib
|
||||||
|
from typing import Set, Dict, List, Tuple, Iterator
|
||||||
|
from pathlib import Path
|
||||||
|
from collections import defaultdict
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from pefile import PE
|
||||||
|
from elftools.elf.elffile import ELFFile
|
||||||
|
|
||||||
|
import capa.features.common
|
||||||
|
import capa.features.extractors.common
|
||||||
|
import capa.features.extractors.binexport2.helpers
|
||||||
|
from capa.features.extractors.binexport2.binexport2_pb2 import BinExport2
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def get_binexport2(sample: Path) -> BinExport2:
|
||||||
|
be2: BinExport2 = BinExport2()
|
||||||
|
be2.ParseFromString(sample.read_bytes())
|
||||||
|
return be2
|
||||||
|
|
||||||
|
|
||||||
|
def compute_common_prefix_length(m: str, n: str) -> int:
|
||||||
|
# ensure #m < #n
|
||||||
|
if len(n) < len(m):
|
||||||
|
m, n = n, m
|
||||||
|
|
||||||
|
for i, c in enumerate(m):
|
||||||
|
if n[i] != c:
|
||||||
|
return i
|
||||||
|
|
||||||
|
return len(m)
|
||||||
|
|
||||||
|
|
||||||
|
def get_sample_from_binexport2(input_file: Path, be2: BinExport2, search_paths: List[Path]) -> Path:
|
||||||
|
"""attempt to find the sample file, given a BinExport2 file.
|
||||||
|
|
||||||
|
searches in the same directory as the BinExport2 file, and then in search_paths.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def filename_similarity_key(p: Path) -> Tuple[int, str]:
|
||||||
|
# note closure over input_file.
|
||||||
|
# sort first by length of common prefix, then by name (for stability)
|
||||||
|
return (compute_common_prefix_length(p.name, input_file.name), p.name)
|
||||||
|
|
||||||
|
wanted_sha256: str = be2.meta_information.executable_id.lower()
|
||||||
|
|
||||||
|
input_directory: Path = input_file.parent
|
||||||
|
siblings: List[Path] = [p for p in input_directory.iterdir() if p.is_file()]
|
||||||
|
siblings.sort(key=filename_similarity_key, reverse=True)
|
||||||
|
for sibling in siblings:
|
||||||
|
# e.g. with open IDA files in the same directory on Windows
|
||||||
|
with contextlib.suppress(PermissionError):
|
||||||
|
if hashlib.sha256(sibling.read_bytes()).hexdigest().lower() == wanted_sha256:
|
||||||
|
return sibling
|
||||||
|
|
||||||
|
for search_path in search_paths:
|
||||||
|
candidates: List[Path] = [p for p in search_path.iterdir() if p.is_file()]
|
||||||
|
candidates.sort(key=filename_similarity_key, reverse=True)
|
||||||
|
for candidate in candidates:
|
||||||
|
with contextlib.suppress(PermissionError):
|
||||||
|
if hashlib.sha256(candidate.read_bytes()).hexdigest().lower() == wanted_sha256:
|
||||||
|
return candidate
|
||||||
|
|
||||||
|
raise ValueError("cannot find sample, you may specify the path using the CAPA_SAMPLES_DIR environment variable")
|
||||||
|
|
||||||
|
|
||||||
|
class BinExport2Index:
|
||||||
|
def __init__(self, be2: BinExport2):
|
||||||
|
self.be2: BinExport2 = be2
|
||||||
|
|
||||||
|
self.callers_by_vertex_index: Dict[int, List[int]] = defaultdict(list)
|
||||||
|
self.callees_by_vertex_index: Dict[int, List[int]] = defaultdict(list)
|
||||||
|
|
||||||
|
# note: flow graph != call graph (vertex)
|
||||||
|
self.flow_graph_index_by_address: Dict[int, int] = {}
|
||||||
|
self.flow_graph_address_by_index: Dict[int, int] = {}
|
||||||
|
|
||||||
|
# edges that come from the given basic block
|
||||||
|
self.source_edges_by_basic_block_index: Dict[int, List[BinExport2.FlowGraph.Edge]] = defaultdict(list)
|
||||||
|
# edges that end up at the given basic block
|
||||||
|
self.target_edges_by_basic_block_index: Dict[int, List[BinExport2.FlowGraph.Edge]] = defaultdict(list)
|
||||||
|
|
||||||
|
self.vertex_index_by_address: Dict[int, int] = {}
|
||||||
|
|
||||||
|
self.data_reference_index_by_source_instruction_index: Dict[int, List[int]] = defaultdict(list)
|
||||||
|
self.data_reference_index_by_target_address: Dict[int, List[int]] = defaultdict(list)
|
||||||
|
self.string_reference_index_by_source_instruction_index: Dict[int, List[int]] = defaultdict(list)
|
||||||
|
|
||||||
|
self.insn_address_by_index: Dict[int, int] = {}
|
||||||
|
self.insn_index_by_address: Dict[int, int] = {}
|
||||||
|
self.insn_by_address: Dict[int, BinExport2.Instruction] = {}
|
||||||
|
|
||||||
|
# must index instructions first
|
||||||
|
self._index_insn_addresses()
|
||||||
|
self._index_vertex_edges()
|
||||||
|
self._index_flow_graph_nodes()
|
||||||
|
self._index_flow_graph_edges()
|
||||||
|
self._index_call_graph_vertices()
|
||||||
|
self._index_data_references()
|
||||||
|
self._index_string_references()
|
||||||
|
|
||||||
|
def get_insn_address(self, insn_index: int) -> int:
|
||||||
|
assert insn_index in self.insn_address_by_index, f"insn must be indexed, missing {insn_index}"
|
||||||
|
return self.insn_address_by_index[insn_index]
|
||||||
|
|
||||||
|
def get_basic_block_address(self, basic_block_index: int) -> int:
|
||||||
|
basic_block: BinExport2.BasicBlock = self.be2.basic_block[basic_block_index]
|
||||||
|
first_instruction_index: int = next(self.instruction_indices(basic_block))
|
||||||
|
return self.get_insn_address(first_instruction_index)
|
||||||
|
|
||||||
|
def _index_vertex_edges(self):
|
||||||
|
for edge in self.be2.call_graph.edge:
|
||||||
|
if not edge.source_vertex_index:
|
||||||
|
continue
|
||||||
|
if not edge.target_vertex_index:
|
||||||
|
continue
|
||||||
|
|
||||||
|
self.callers_by_vertex_index[edge.target_vertex_index].append(edge.source_vertex_index)
|
||||||
|
self.callees_by_vertex_index[edge.source_vertex_index].append(edge.target_vertex_index)
|
||||||
|
|
||||||
|
def _index_flow_graph_nodes(self):
|
||||||
|
for flow_graph_index, flow_graph in enumerate(self.be2.flow_graph):
|
||||||
|
function_address: int = self.get_basic_block_address(flow_graph.entry_basic_block_index)
|
||||||
|
self.flow_graph_index_by_address[function_address] = flow_graph_index
|
||||||
|
self.flow_graph_address_by_index[flow_graph_index] = function_address
|
||||||
|
|
||||||
|
def _index_flow_graph_edges(self):
|
||||||
|
for flow_graph in self.be2.flow_graph:
|
||||||
|
for edge in flow_graph.edge:
|
||||||
|
if not edge.HasField("source_basic_block_index") or not edge.HasField("target_basic_block_index"):
|
||||||
|
continue
|
||||||
|
|
||||||
|
self.source_edges_by_basic_block_index[edge.source_basic_block_index].append(edge)
|
||||||
|
self.target_edges_by_basic_block_index[edge.target_basic_block_index].append(edge)
|
||||||
|
|
||||||
|
def _index_call_graph_vertices(self):
|
||||||
|
for vertex_index, vertex in enumerate(self.be2.call_graph.vertex):
|
||||||
|
if not vertex.HasField("address"):
|
||||||
|
continue
|
||||||
|
|
||||||
|
vertex_address: int = vertex.address
|
||||||
|
self.vertex_index_by_address[vertex_address] = vertex_index
|
||||||
|
|
||||||
|
def _index_data_references(self):
|
||||||
|
for data_reference_index, data_reference in enumerate(self.be2.data_reference):
|
||||||
|
self.data_reference_index_by_source_instruction_index[data_reference.instruction_index].append(
|
||||||
|
data_reference_index
|
||||||
|
)
|
||||||
|
self.data_reference_index_by_target_address[data_reference.address].append(data_reference_index)
|
||||||
|
|
||||||
|
def _index_string_references(self):
|
||||||
|
for string_reference_index, string_reference in enumerate(self.be2.string_reference):
|
||||||
|
self.string_reference_index_by_source_instruction_index[string_reference.instruction_index].append(
|
||||||
|
string_reference_index
|
||||||
|
)
|
||||||
|
|
||||||
|
def _index_insn_addresses(self):
|
||||||
|
# see https://github.com/google/binexport/blob/39f6445c232bb5caf5c4a2a996de91dfa20c48e8/binexport.cc#L45
|
||||||
|
if len(self.be2.instruction) == 0:
|
||||||
|
return
|
||||||
|
|
||||||
|
assert self.be2.instruction[0].HasField("address"), "first insn must have explicit address"
|
||||||
|
|
||||||
|
addr: int = 0
|
||||||
|
next_addr: int = 0
|
||||||
|
for idx, insn in enumerate(self.be2.instruction):
|
||||||
|
if insn.HasField("address"):
|
||||||
|
addr = insn.address
|
||||||
|
next_addr = addr + len(insn.raw_bytes)
|
||||||
|
else:
|
||||||
|
addr = next_addr
|
||||||
|
next_addr += len(insn.raw_bytes)
|
||||||
|
self.insn_address_by_index[idx] = addr
|
||||||
|
self.insn_index_by_address[addr] = idx
|
||||||
|
self.insn_by_address[addr] = insn
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def instruction_indices(basic_block: BinExport2.BasicBlock) -> Iterator[int]:
|
||||||
|
"""
|
||||||
|
For a given basic block, enumerate the instruction indices.
|
||||||
|
"""
|
||||||
|
for index_range in basic_block.instruction_index:
|
||||||
|
if not index_range.HasField("end_index"):
|
||||||
|
yield index_range.begin_index
|
||||||
|
continue
|
||||||
|
else:
|
||||||
|
yield from range(index_range.begin_index, index_range.end_index)
|
||||||
|
|
||||||
|
def basic_block_instructions(
|
||||||
|
self, basic_block: BinExport2.BasicBlock
|
||||||
|
) -> Iterator[Tuple[int, BinExport2.Instruction, int]]:
|
||||||
|
"""
|
||||||
|
For a given basic block, enumerate the instruction indices,
|
||||||
|
the instruction instances, and their addresses.
|
||||||
|
"""
|
||||||
|
for instruction_index in self.instruction_indices(basic_block):
|
||||||
|
instruction: BinExport2.Instruction = self.be2.instruction[instruction_index]
|
||||||
|
instruction_address: int = self.get_insn_address(instruction_index)
|
||||||
|
|
||||||
|
yield instruction_index, instruction, instruction_address
|
||||||
|
|
||||||
|
def get_function_name_by_vertex(self, vertex_index: int) -> str:
|
||||||
|
vertex: BinExport2.CallGraph.Vertex = self.be2.call_graph.vertex[vertex_index]
|
||||||
|
name: str = f"sub_{vertex.address:x}"
|
||||||
|
if vertex.HasField("mangled_name"):
|
||||||
|
name = vertex.mangled_name
|
||||||
|
|
||||||
|
if vertex.HasField("demangled_name"):
|
||||||
|
name = vertex.demangled_name
|
||||||
|
|
||||||
|
if vertex.HasField("library_index"):
|
||||||
|
library: BinExport2.Library = self.be2.library[vertex.library_index]
|
||||||
|
if library.HasField("name"):
|
||||||
|
name = f"{library.name}!{name}"
|
||||||
|
|
||||||
|
return name
|
||||||
|
|
||||||
|
def get_function_name_by_address(self, address: int) -> str:
|
||||||
|
if address not in self.vertex_index_by_address:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
vertex_index: int = self.vertex_index_by_address[address]
|
||||||
|
return self.get_function_name_by_vertex(vertex_index)
|
||||||
|
|
||||||
|
def get_instruction_by_address(self, address: int) -> BinExport2.Instruction:
|
||||||
|
assert address in self.insn_by_address, f"address must be indexed, missing {address:x}"
|
||||||
|
return self.insn_by_address[address]
|
||||||
|
|
||||||
|
|
||||||
|
class BinExport2Analysis:
|
||||||
|
def __init__(self, be2: BinExport2, idx: BinExport2Index, buf: bytes):
|
||||||
|
self.be2: BinExport2 = be2
|
||||||
|
self.idx: BinExport2Index = idx
|
||||||
|
self.buf: bytes = buf
|
||||||
|
self.base_address: int = 0
|
||||||
|
self.thunks: Dict[int, int] = {}
|
||||||
|
|
||||||
|
self._find_base_address()
|
||||||
|
self._compute_thunks()
|
||||||
|
|
||||||
|
def _find_base_address(self):
|
||||||
|
sections_with_perms: Iterator[BinExport2.Section] = filter(
|
||||||
|
lambda s: s.flag_r or s.flag_w or s.flag_x, self.be2.section
|
||||||
|
)
|
||||||
|
# assume the lowest address is the base address.
|
||||||
|
# this works as long as BinExport doesn't record other
|
||||||
|
# libraries mapped into memory.
|
||||||
|
self.base_address = min(s.address for s in sections_with_perms)
|
||||||
|
|
||||||
|
logger.debug("found base address: %x", self.base_address)
|
||||||
|
|
||||||
|
def _compute_thunks(self):
|
||||||
|
for addr, idx in self.idx.vertex_index_by_address.items():
|
||||||
|
vertex: BinExport2.CallGraph.Vertex = self.be2.call_graph.vertex[idx]
|
||||||
|
if not capa.features.extractors.binexport2.helpers.is_vertex_type(
|
||||||
|
vertex, BinExport2.CallGraph.Vertex.Type.THUNK
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
|
||||||
|
curr_idx: int = idx
|
||||||
|
for _ in range(capa.features.common.THUNK_CHAIN_DEPTH_DELTA):
|
||||||
|
thunk_callees: List[int] = self.idx.callees_by_vertex_index[curr_idx]
|
||||||
|
# if this doesn't hold, then it doesn't seem like this is a thunk,
|
||||||
|
# because either, len is:
|
||||||
|
# 0 and the thunk doesn't point to anything, or
|
||||||
|
# >1 and the thunk may end up at many functions.
|
||||||
|
assert len(thunk_callees) == 1, f"thunk @ {hex(addr)} failed"
|
||||||
|
|
||||||
|
thunked_idx: int = thunk_callees[0]
|
||||||
|
thunked_vertex: BinExport2.CallGraph.Vertex = self.be2.call_graph.vertex[thunked_idx]
|
||||||
|
|
||||||
|
if not capa.features.extractors.binexport2.helpers.is_vertex_type(
|
||||||
|
thunked_vertex, BinExport2.CallGraph.Vertex.Type.THUNK
|
||||||
|
):
|
||||||
|
assert thunked_vertex.HasField("address")
|
||||||
|
|
||||||
|
self.thunks[addr] = thunked_vertex.address
|
||||||
|
break
|
||||||
|
|
||||||
|
curr_idx = thunked_idx
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class MemoryRegion:
|
||||||
|
# location of the bytes, potentially relative to a base address
|
||||||
|
address: int
|
||||||
|
buf: bytes
|
||||||
|
|
||||||
|
@property
|
||||||
|
def end(self) -> int:
|
||||||
|
return self.address + len(self.buf)
|
||||||
|
|
||||||
|
def contains(self, address: int) -> bool:
|
||||||
|
# note: address must be relative to any base address
|
||||||
|
return self.address <= address < self.end
|
||||||
|
|
||||||
|
|
||||||
|
class ReadMemoryError(ValueError): ...
|
||||||
|
|
||||||
|
|
||||||
|
class AddressNotMappedError(ReadMemoryError): ...
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class AddressSpace:
|
||||||
|
base_address: int
|
||||||
|
memory_regions: Tuple[MemoryRegion, ...]
|
||||||
|
|
||||||
|
def read_memory(self, address: int, length: int) -> bytes:
|
||||||
|
rva: int = address - self.base_address
|
||||||
|
for region in self.memory_regions:
|
||||||
|
if region.contains(rva):
|
||||||
|
offset: int = rva - region.address
|
||||||
|
return region.buf[offset : offset + length]
|
||||||
|
|
||||||
|
raise AddressNotMappedError(address)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_pe(cls, pe: PE, base_address: int):
|
||||||
|
regions: List[MemoryRegion] = []
|
||||||
|
for section in pe.sections:
|
||||||
|
address: int = section.VirtualAddress
|
||||||
|
size: int = section.Misc_VirtualSize
|
||||||
|
buf: bytes = section.get_data()
|
||||||
|
|
||||||
|
if len(buf) != size:
|
||||||
|
# pad the section with NULLs
|
||||||
|
# assume page alignment is already handled.
|
||||||
|
# might need more hardening here.
|
||||||
|
buf += b"\x00" * (size - len(buf))
|
||||||
|
|
||||||
|
regions.append(MemoryRegion(address, buf))
|
||||||
|
|
||||||
|
return cls(base_address, tuple(regions))
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_elf(cls, elf: ELFFile, base_address: int):
|
||||||
|
regions: List[MemoryRegion] = []
|
||||||
|
|
||||||
|
# ELF segments are for runtime data,
|
||||||
|
# ELF sections are for link-time data.
|
||||||
|
for segment in elf.iter_segments():
|
||||||
|
# assume p_align is consistent with addresses here.
|
||||||
|
# otherwise, should harden this loader.
|
||||||
|
segment_rva: int = segment.header.p_vaddr
|
||||||
|
segment_size: int = segment.header.p_memsz
|
||||||
|
segment_data: bytes = segment.data()
|
||||||
|
|
||||||
|
if len(segment_data) < segment_size:
|
||||||
|
# pad the section with NULLs
|
||||||
|
# assume page alignment is already handled.
|
||||||
|
# might need more hardening here.
|
||||||
|
segment_data += b"\x00" * (segment_size - len(segment_data))
|
||||||
|
|
||||||
|
regions.append(MemoryRegion(segment_rva, segment_data))
|
||||||
|
|
||||||
|
return cls(base_address, tuple(regions))
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_buf(cls, buf: bytes, base_address: int):
|
||||||
|
if buf.startswith(capa.features.extractors.common.MATCH_PE):
|
||||||
|
pe: PE = PE(data=buf)
|
||||||
|
return cls.from_pe(pe, base_address)
|
||||||
|
elif buf.startswith(capa.features.extractors.common.MATCH_ELF):
|
||||||
|
elf: ELFFile = ELFFile(io.BytesIO(buf))
|
||||||
|
return cls.from_elf(elf, base_address)
|
||||||
|
else:
|
||||||
|
raise NotImplementedError("file format address space")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class AnalysisContext:
|
||||||
|
sample_bytes: bytes
|
||||||
|
be2: BinExport2
|
||||||
|
idx: BinExport2Index
|
||||||
|
analysis: BinExport2Analysis
|
||||||
|
address_space: AddressSpace
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class FunctionContext:
|
||||||
|
ctx: AnalysisContext
|
||||||
|
flow_graph_index: int
|
||||||
|
format: Set[str]
|
||||||
|
os: Set[str]
|
||||||
|
arch: Set[str]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class BasicBlockContext:
|
||||||
|
basic_block_index: int
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class InstructionContext:
|
||||||
|
instruction_index: int
|
||||||
15
capa/features/extractors/binexport2/arch/arm/helpers.py
Normal file
15
capa/features/extractors/binexport2/arch/arm/helpers.py
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
# Copyright (C) 2024 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
|
||||||
|
from capa.features.extractors.binexport2.binexport2_pb2 import BinExport2
|
||||||
|
|
||||||
|
|
||||||
|
def is_stack_register_expression(be2: BinExport2, expression: BinExport2.Expression) -> bool:
|
||||||
|
return bool(
|
||||||
|
expression and expression.type == BinExport2.Expression.REGISTER and expression.symbol.lower().endswith("sp")
|
||||||
|
)
|
||||||
155
capa/features/extractors/binexport2/arch/arm/insn.py
Normal file
155
capa/features/extractors/binexport2/arch/arm/insn.py
Normal file
@@ -0,0 +1,155 @@
|
|||||||
|
# Copyright (C) 2024 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
import logging
|
||||||
|
from typing import List, Tuple, Iterator, Optional
|
||||||
|
|
||||||
|
import capa.features.extractors.binexport2.helpers
|
||||||
|
from capa.features.insn import MAX_STRUCTURE_SIZE, Number, Offset, OperandNumber, OperandOffset
|
||||||
|
from capa.features.common import Feature, Characteristic
|
||||||
|
from capa.features.address import Address
|
||||||
|
from capa.features.extractors.binexport2 import FunctionContext, InstructionContext
|
||||||
|
from capa.features.extractors.base_extractor import BBHandle, InsnHandle, FunctionHandle
|
||||||
|
from capa.features.extractors.binexport2.helpers import (
|
||||||
|
BinExport2InstructionPatternMatcher,
|
||||||
|
mask_immediate,
|
||||||
|
is_address_mapped,
|
||||||
|
get_instruction_mnemonic,
|
||||||
|
get_operand_register_expression,
|
||||||
|
get_operand_immediate_expression,
|
||||||
|
)
|
||||||
|
from capa.features.extractors.binexport2.binexport2_pb2 import BinExport2
|
||||||
|
from capa.features.extractors.binexport2.arch.arm.helpers import is_stack_register_expression
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_insn_number_features(
|
||||||
|
fh: FunctionHandle, _bbh: BBHandle, ih: InsnHandle
|
||||||
|
) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
fhi: FunctionContext = fh.inner
|
||||||
|
ii: InstructionContext = ih.inner
|
||||||
|
|
||||||
|
be2: BinExport2 = fhi.ctx.be2
|
||||||
|
|
||||||
|
instruction_index: int = ii.instruction_index
|
||||||
|
instruction: BinExport2.Instruction = be2.instruction[instruction_index]
|
||||||
|
|
||||||
|
if len(instruction.operand_index) == 0:
|
||||||
|
# skip things like:
|
||||||
|
# .text:0040116e leave
|
||||||
|
return
|
||||||
|
|
||||||
|
mnemonic: str = get_instruction_mnemonic(be2, instruction)
|
||||||
|
|
||||||
|
if mnemonic in ("add", "sub"):
|
||||||
|
assert len(instruction.operand_index) == 3
|
||||||
|
|
||||||
|
operand1_expression: Optional[BinExport2.Expression] = get_operand_register_expression(
|
||||||
|
be2, be2.operand[instruction.operand_index[1]]
|
||||||
|
)
|
||||||
|
if operand1_expression and is_stack_register_expression(be2, operand1_expression):
|
||||||
|
# skip things like:
|
||||||
|
# add x0,sp,#0x8
|
||||||
|
return
|
||||||
|
|
||||||
|
for i, operand_index in enumerate(instruction.operand_index):
|
||||||
|
operand: BinExport2.Operand = be2.operand[operand_index]
|
||||||
|
|
||||||
|
immediate_expression: Optional[BinExport2.Expression] = get_operand_immediate_expression(be2, operand)
|
||||||
|
if not immediate_expression:
|
||||||
|
continue
|
||||||
|
|
||||||
|
value: int = mask_immediate(fhi.arch, immediate_expression.immediate)
|
||||||
|
if is_address_mapped(be2, value):
|
||||||
|
continue
|
||||||
|
|
||||||
|
yield Number(value), ih.address
|
||||||
|
yield OperandNumber(i, value), ih.address
|
||||||
|
|
||||||
|
if mnemonic == "add" and i == 2:
|
||||||
|
if 0 < value < MAX_STRUCTURE_SIZE:
|
||||||
|
yield Offset(value), ih.address
|
||||||
|
yield OperandOffset(i, value), ih.address
|
||||||
|
|
||||||
|
|
||||||
|
OFFSET_PATTERNS = BinExport2InstructionPatternMatcher.from_str(
|
||||||
|
"""
|
||||||
|
ldr|ldrb|ldrh|ldrsb|ldrsh|ldrex|ldrd|str|strb|strh|strex|strd reg, [reg(not-stack), #int] ; capture #int
|
||||||
|
ldr|ldrb|ldrh|ldrsb|ldrsh|ldrex|ldrd|str|strb|strh|strex|strd reg, [reg(not-stack), #int]! ; capture #int
|
||||||
|
ldr|ldrb|ldrh|ldrsb|ldrsh|ldrex|ldrd|str|strb|strh|strex|strd reg, [reg(not-stack)], #int ; capture #int
|
||||||
|
ldp|ldpd|stp|stpd reg, reg, [reg(not-stack), #int] ; capture #int
|
||||||
|
ldp|ldpd|stp|stpd reg, reg, [reg(not-stack), #int]! ; capture #int
|
||||||
|
ldp|ldpd|stp|stpd reg, reg, [reg(not-stack)], #int ; capture #int
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_insn_offset_features(
|
||||||
|
fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle
|
||||||
|
) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
fhi: FunctionContext = fh.inner
|
||||||
|
ii: InstructionContext = ih.inner
|
||||||
|
|
||||||
|
be2: BinExport2 = fhi.ctx.be2
|
||||||
|
|
||||||
|
match = OFFSET_PATTERNS.match_with_be2(be2, ii.instruction_index)
|
||||||
|
if not match:
|
||||||
|
return
|
||||||
|
|
||||||
|
value = match.expression.immediate
|
||||||
|
|
||||||
|
value = mask_immediate(fhi.arch, value)
|
||||||
|
if not is_address_mapped(be2, value):
|
||||||
|
value = capa.features.extractors.binexport2.helpers.twos_complement(fhi.arch, value)
|
||||||
|
yield Offset(value), ih.address
|
||||||
|
yield OperandOffset(match.operand_index, value), ih.address
|
||||||
|
|
||||||
|
|
||||||
|
NZXOR_PATTERNS = BinExport2InstructionPatternMatcher.from_str(
|
||||||
|
"""
|
||||||
|
eor reg, reg, reg
|
||||||
|
eor reg, reg, #int
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_insn_nzxor_characteristic_features(
|
||||||
|
fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle
|
||||||
|
) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
fhi: FunctionContext = fh.inner
|
||||||
|
ii: InstructionContext = ih.inner
|
||||||
|
be2: BinExport2 = fhi.ctx.be2
|
||||||
|
|
||||||
|
if NZXOR_PATTERNS.match_with_be2(be2, ii.instruction_index) is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
instruction: BinExport2.Instruction = be2.instruction[ii.instruction_index]
|
||||||
|
# guaranteed to be simple int/reg operands
|
||||||
|
# so we don't have to realize the tree/list.
|
||||||
|
operands: List[BinExport2.Operand] = [be2.operand[operand_index] for operand_index in instruction.operand_index]
|
||||||
|
|
||||||
|
if operands[1] != operands[2]:
|
||||||
|
yield Characteristic("nzxor"), ih.address
|
||||||
|
|
||||||
|
|
||||||
|
INDIRECT_CALL_PATTERNS = BinExport2InstructionPatternMatcher.from_str(
|
||||||
|
"""
|
||||||
|
blx|bx|blr reg
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_function_indirect_call_characteristic_features(
|
||||||
|
fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle
|
||||||
|
) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
fhi: FunctionContext = fh.inner
|
||||||
|
ii: InstructionContext = ih.inner
|
||||||
|
be2: BinExport2 = fhi.ctx.be2
|
||||||
|
|
||||||
|
if INDIRECT_CALL_PATTERNS.match_with_be2(be2, ii.instruction_index) is not None:
|
||||||
|
yield Characteristic("indirect call"), ih.address
|
||||||
135
capa/features/extractors/binexport2/arch/intel/helpers.py
Normal file
135
capa/features/extractors/binexport2/arch/intel/helpers.py
Normal file
@@ -0,0 +1,135 @@
|
|||||||
|
# Copyright (C) 2024 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
from typing import List, Optional
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
from capa.features.extractors.binexport2.helpers import get_operand_expressions
|
||||||
|
from capa.features.extractors.binexport2.binexport2_pb2 import BinExport2
|
||||||
|
|
||||||
|
# security cookie checks may perform non-zeroing XORs, these are expected within a certain
|
||||||
|
# byte range within the first and returning basic blocks, this helps to reduce FP features
|
||||||
|
SECURITY_COOKIE_BYTES_DELTA: int = 0x40
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class OperandPhraseInfo:
|
||||||
|
scale: Optional[BinExport2.Expression] = None
|
||||||
|
index: Optional[BinExport2.Expression] = None
|
||||||
|
base: Optional[BinExport2.Expression] = None
|
||||||
|
displacement: Optional[BinExport2.Expression] = None
|
||||||
|
|
||||||
|
|
||||||
|
def get_operand_phrase_info(be2: BinExport2, operand: BinExport2.Operand) -> Optional[OperandPhraseInfo]:
|
||||||
|
# assume the following (see https://blog.yossarian.net/2020/06/13/How-x86_64-addresses-memory):
|
||||||
|
#
|
||||||
|
# Scale: A 2-bit constant factor
|
||||||
|
# Index: Any general purpose register
|
||||||
|
# Base: Any general purpose register
|
||||||
|
# Displacement: An integral offset
|
||||||
|
|
||||||
|
expressions: List[BinExport2.Expression] = get_operand_expressions(be2, operand)
|
||||||
|
|
||||||
|
# skip expression up to and including BinExport2.Expression.DEREFERENCE, assume caller
|
||||||
|
# has checked for BinExport2.Expression.DEREFERENCE
|
||||||
|
for i, expression in enumerate(expressions):
|
||||||
|
if expression.type == BinExport2.Expression.DEREFERENCE:
|
||||||
|
expressions = expressions[i + 1 :]
|
||||||
|
break
|
||||||
|
|
||||||
|
expression0: BinExport2.Expression
|
||||||
|
expression1: BinExport2.Expression
|
||||||
|
expression2: BinExport2.Expression
|
||||||
|
expression3: BinExport2.Expression
|
||||||
|
expression4: BinExport2.Expression
|
||||||
|
|
||||||
|
if len(expressions) == 1:
|
||||||
|
expression0 = expressions[0]
|
||||||
|
|
||||||
|
assert (
|
||||||
|
expression0.type == BinExport2.Expression.IMMEDIATE_INT
|
||||||
|
or expression0.type == BinExport2.Expression.REGISTER
|
||||||
|
)
|
||||||
|
|
||||||
|
if expression0.type == BinExport2.Expression.IMMEDIATE_INT:
|
||||||
|
# Displacement
|
||||||
|
return OperandPhraseInfo(displacement=expression0)
|
||||||
|
elif expression0.type == BinExport2.Expression.REGISTER:
|
||||||
|
# Base
|
||||||
|
return OperandPhraseInfo(base=expression0)
|
||||||
|
|
||||||
|
elif len(expressions) == 3:
|
||||||
|
expression0 = expressions[0]
|
||||||
|
expression1 = expressions[1]
|
||||||
|
expression2 = expressions[2]
|
||||||
|
|
||||||
|
assert expression0.type == BinExport2.Expression.REGISTER
|
||||||
|
assert expression1.type == BinExport2.Expression.OPERATOR
|
||||||
|
assert (
|
||||||
|
expression2.type == BinExport2.Expression.IMMEDIATE_INT
|
||||||
|
or expression2.type == BinExport2.Expression.REGISTER
|
||||||
|
)
|
||||||
|
|
||||||
|
if expression2.type == BinExport2.Expression.REGISTER:
|
||||||
|
# Base + Index
|
||||||
|
return OperandPhraseInfo(base=expression0, index=expression2)
|
||||||
|
elif expression2.type == BinExport2.Expression.IMMEDIATE_INT:
|
||||||
|
# Base + Displacement
|
||||||
|
return OperandPhraseInfo(base=expression0, displacement=expression2)
|
||||||
|
|
||||||
|
elif len(expressions) == 5:
|
||||||
|
expression0 = expressions[0]
|
||||||
|
expression1 = expressions[1]
|
||||||
|
expression2 = expressions[2]
|
||||||
|
expression3 = expressions[3]
|
||||||
|
expression4 = expressions[4]
|
||||||
|
|
||||||
|
assert expression0.type == BinExport2.Expression.REGISTER
|
||||||
|
assert expression1.type == BinExport2.Expression.OPERATOR
|
||||||
|
assert (
|
||||||
|
expression2.type == BinExport2.Expression.REGISTER
|
||||||
|
or expression2.type == BinExport2.Expression.IMMEDIATE_INT
|
||||||
|
)
|
||||||
|
assert expression3.type == BinExport2.Expression.OPERATOR
|
||||||
|
assert expression4.type == BinExport2.Expression.IMMEDIATE_INT
|
||||||
|
|
||||||
|
if expression1.symbol == "+" and expression3.symbol == "+":
|
||||||
|
# Base + Index + Displacement
|
||||||
|
return OperandPhraseInfo(base=expression0, index=expression2, displacement=expression4)
|
||||||
|
elif expression1.symbol == "+" and expression3.symbol == "*":
|
||||||
|
# Base + (Index * Scale)
|
||||||
|
return OperandPhraseInfo(base=expression0, index=expression2, scale=expression3)
|
||||||
|
elif expression1.symbol == "*" and expression3.symbol == "+":
|
||||||
|
# (Index * Scale) + Displacement
|
||||||
|
return OperandPhraseInfo(index=expression0, scale=expression2, displacement=expression3)
|
||||||
|
else:
|
||||||
|
raise NotImplementedError(expression1.symbol, expression3.symbol)
|
||||||
|
|
||||||
|
elif len(expressions) == 7:
|
||||||
|
expression0 = expressions[0]
|
||||||
|
expression1 = expressions[1]
|
||||||
|
expression2 = expressions[2]
|
||||||
|
expression3 = expressions[3]
|
||||||
|
expression4 = expressions[4]
|
||||||
|
expression5 = expressions[5]
|
||||||
|
expression6 = expressions[6]
|
||||||
|
|
||||||
|
assert expression0.type == BinExport2.Expression.REGISTER
|
||||||
|
assert expression1.type == BinExport2.Expression.OPERATOR
|
||||||
|
assert expression2.type == BinExport2.Expression.REGISTER
|
||||||
|
assert expression3.type == BinExport2.Expression.OPERATOR
|
||||||
|
assert expression4.type == BinExport2.Expression.IMMEDIATE_INT
|
||||||
|
assert expression5.type == BinExport2.Expression.OPERATOR
|
||||||
|
assert expression6.type == BinExport2.Expression.IMMEDIATE_INT
|
||||||
|
|
||||||
|
# Base + (Index * Scale) + Displacement
|
||||||
|
return OperandPhraseInfo(base=expression0, index=expression2, scale=expression4, displacement=expression6)
|
||||||
|
|
||||||
|
else:
|
||||||
|
raise NotImplementedError(len(expressions))
|
||||||
|
|
||||||
|
return None
|
||||||
248
capa/features/extractors/binexport2/arch/intel/insn.py
Normal file
248
capa/features/extractors/binexport2/arch/intel/insn.py
Normal file
@@ -0,0 +1,248 @@
|
|||||||
|
# Copyright (C) 2024 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
import logging
|
||||||
|
from typing import List, Tuple, Iterator
|
||||||
|
|
||||||
|
import capa.features.extractors.strings
|
||||||
|
import capa.features.extractors.binexport2.helpers
|
||||||
|
from capa.features.insn import MAX_STRUCTURE_SIZE, Number, Offset, OperandNumber, OperandOffset
|
||||||
|
from capa.features.common import Feature, Characteristic
|
||||||
|
from capa.features.address import Address
|
||||||
|
from capa.features.extractors.binexport2 import BinExport2Index, FunctionContext, BasicBlockContext, InstructionContext
|
||||||
|
from capa.features.extractors.base_extractor import BBHandle, InsnHandle, FunctionHandle
|
||||||
|
from capa.features.extractors.binexport2.helpers import (
|
||||||
|
BinExport2InstructionPatternMatcher,
|
||||||
|
mask_immediate,
|
||||||
|
is_address_mapped,
|
||||||
|
get_instruction_mnemonic,
|
||||||
|
)
|
||||||
|
from capa.features.extractors.binexport2.binexport2_pb2 import BinExport2
|
||||||
|
from capa.features.extractors.binexport2.arch.intel.helpers import SECURITY_COOKIE_BYTES_DELTA
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
IGNORE_NUMBER_PATTERNS = BinExport2InstructionPatternMatcher.from_str(
|
||||||
|
"""
|
||||||
|
ret #int
|
||||||
|
retn #int
|
||||||
|
add reg(stack), #int
|
||||||
|
sub reg(stack), #int
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
|
||||||
|
NUMBER_PATTERNS = BinExport2InstructionPatternMatcher.from_str(
|
||||||
|
"""
|
||||||
|
push #int0 ; capture #int0
|
||||||
|
|
||||||
|
# its a little tedious to enumerate all the address forms
|
||||||
|
# but at least we are explicit
|
||||||
|
cmp|and|or|test|mov|add|adc|sub|shl|shr|sal|sar reg, #int0 ; capture #int0
|
||||||
|
cmp|and|or|test|mov|add|adc|sub|shl|shr|sal|sar [reg], #int0 ; capture #int0
|
||||||
|
cmp|and|or|test|mov|add|adc|sub|shl|shr|sal|sar [#int], #int0 ; capture #int0
|
||||||
|
cmp|and|or|test|mov|add|adc|sub|shl|shr|sal|sar [reg + #int], #int0 ; capture #int0
|
||||||
|
cmp|and|or|test|mov|add|adc|sub|shl|shr|sal|sar [reg + reg + #int], #int0 ; capture #int0
|
||||||
|
cmp|and|or|test|mov|add|adc|sub|shl|shr|sal|sar [reg + reg * #int], #int0 ; capture #int0
|
||||||
|
cmp|and|or|test|mov|add|adc|sub|shl|shr|sal|sar [reg + reg * #int + #int], #int0 ; capture #int0
|
||||||
|
|
||||||
|
imul reg, reg, #int ; capture #int
|
||||||
|
# note that int is first
|
||||||
|
cmp|test #int0, reg ; capture #int0
|
||||||
|
|
||||||
|
# imagine reg is zero'd out, then this is like `mov reg, #int`
|
||||||
|
# which is not uncommon.
|
||||||
|
lea reg, [reg + #int] ; capture #int
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_insn_number_features(
|
||||||
|
fh: FunctionHandle, _bbh: BBHandle, ih: InsnHandle
|
||||||
|
) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
fhi: FunctionContext = fh.inner
|
||||||
|
ii: InstructionContext = ih.inner
|
||||||
|
|
||||||
|
be2: BinExport2 = fhi.ctx.be2
|
||||||
|
|
||||||
|
if IGNORE_NUMBER_PATTERNS.match_with_be2(be2, ii.instruction_index):
|
||||||
|
return
|
||||||
|
|
||||||
|
match = NUMBER_PATTERNS.match_with_be2(be2, ii.instruction_index)
|
||||||
|
if not match:
|
||||||
|
return
|
||||||
|
|
||||||
|
value: int = mask_immediate(fhi.arch, match.expression.immediate)
|
||||||
|
if is_address_mapped(be2, value):
|
||||||
|
return
|
||||||
|
|
||||||
|
yield Number(value), ih.address
|
||||||
|
yield OperandNumber(match.operand_index, value), ih.address
|
||||||
|
|
||||||
|
instruction_index: int = ii.instruction_index
|
||||||
|
instruction: BinExport2.Instruction = be2.instruction[instruction_index]
|
||||||
|
|
||||||
|
mnemonic: str = get_instruction_mnemonic(be2, instruction)
|
||||||
|
if mnemonic.startswith("add"):
|
||||||
|
if 0 < value < MAX_STRUCTURE_SIZE:
|
||||||
|
yield Offset(value), ih.address
|
||||||
|
yield OperandOffset(match.operand_index, value), ih.address
|
||||||
|
|
||||||
|
|
||||||
|
OFFSET_PATTERNS = BinExport2InstructionPatternMatcher.from_str(
|
||||||
|
"""
|
||||||
|
mov|movzx|movsb|cmp [reg + reg * #int + #int0], #int ; capture #int0
|
||||||
|
mov|movzx|movsb|cmp [reg * #int + #int0], #int ; capture #int0
|
||||||
|
mov|movzx|movsb|cmp [reg + reg + #int0], #int ; capture #int0
|
||||||
|
mov|movzx|movsb|cmp [reg(not-stack) + #int0], #int ; capture #int0
|
||||||
|
mov|movzx|movsb|cmp [reg + reg * #int + #int0], reg ; capture #int0
|
||||||
|
mov|movzx|movsb|cmp [reg * #int + #int0], reg ; capture #int0
|
||||||
|
mov|movzx|movsb|cmp [reg + reg + #int0], reg ; capture #int0
|
||||||
|
mov|movzx|movsb|cmp [reg(not-stack) + #int0], reg ; capture #int0
|
||||||
|
mov|movzx|movsb|cmp|lea reg, [reg + reg * #int + #int0] ; capture #int0
|
||||||
|
mov|movzx|movsb|cmp|lea reg, [reg * #int + #int0] ; capture #int0
|
||||||
|
mov|movzx|movsb|cmp|lea reg, [reg + reg + #int0] ; capture #int0
|
||||||
|
mov|movzx|movsb|cmp|lea reg, [reg(not-stack) + #int0] ; capture #int0
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
|
||||||
|
# these are patterns that access offset 0 from some pointer
|
||||||
|
# (pointer is not the stack pointer).
|
||||||
|
OFFSET_ZERO_PATTERNS = BinExport2InstructionPatternMatcher.from_str(
|
||||||
|
"""
|
||||||
|
mov|movzx|movsb [reg(not-stack)], reg
|
||||||
|
mov|movzx|movsb [reg(not-stack)], #int
|
||||||
|
lea reg, [reg(not-stack)]
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_insn_offset_features(
|
||||||
|
fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle
|
||||||
|
) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
fhi: FunctionContext = fh.inner
|
||||||
|
ii: InstructionContext = ih.inner
|
||||||
|
|
||||||
|
be2: BinExport2 = fhi.ctx.be2
|
||||||
|
|
||||||
|
match = OFFSET_PATTERNS.match_with_be2(be2, ii.instruction_index)
|
||||||
|
if not match:
|
||||||
|
match = OFFSET_ZERO_PATTERNS.match_with_be2(be2, ii.instruction_index)
|
||||||
|
if not match:
|
||||||
|
return
|
||||||
|
|
||||||
|
yield Offset(0), ih.address
|
||||||
|
yield OperandOffset(match.operand_index, 0), ih.address
|
||||||
|
|
||||||
|
value = mask_immediate(fhi.arch, match.expression.immediate)
|
||||||
|
if is_address_mapped(be2, value):
|
||||||
|
return
|
||||||
|
|
||||||
|
value = capa.features.extractors.binexport2.helpers.twos_complement(fhi.arch, value, 32)
|
||||||
|
yield Offset(value), ih.address
|
||||||
|
yield OperandOffset(match.operand_index, value), ih.address
|
||||||
|
|
||||||
|
|
||||||
|
def is_security_cookie(
|
||||||
|
fhi: FunctionContext,
|
||||||
|
bbi: BasicBlockContext,
|
||||||
|
instruction_address: int,
|
||||||
|
instruction: BinExport2.Instruction,
|
||||||
|
) -> bool:
|
||||||
|
"""
|
||||||
|
check if an instruction is related to security cookie checks.
|
||||||
|
"""
|
||||||
|
be2: BinExport2 = fhi.ctx.be2
|
||||||
|
idx: BinExport2Index = fhi.ctx.idx
|
||||||
|
|
||||||
|
# security cookie check should use SP or BP
|
||||||
|
op1: BinExport2.Operand = be2.operand[instruction.operand_index[1]]
|
||||||
|
op1_exprs: List[BinExport2.Expression] = [be2.expression[expr_i] for expr_i in op1.expression_index]
|
||||||
|
if all(expr.symbol.lower() not in ("bp", "esp", "ebp", "rbp", "rsp") for expr in op1_exprs):
|
||||||
|
return False
|
||||||
|
|
||||||
|
# check_nzxor_security_cookie_delta
|
||||||
|
# if insn falls at the start of first entry block of the parent function.
|
||||||
|
flow_graph: BinExport2.FlowGraph = be2.flow_graph[fhi.flow_graph_index]
|
||||||
|
basic_block_index: int = bbi.basic_block_index
|
||||||
|
bb: BinExport2.BasicBlock = be2.basic_block[basic_block_index]
|
||||||
|
if flow_graph.entry_basic_block_index == basic_block_index:
|
||||||
|
first_addr: int = min((idx.insn_address_by_index[ir.begin_index] for ir in bb.instruction_index))
|
||||||
|
if instruction_address < first_addr + SECURITY_COOKIE_BYTES_DELTA:
|
||||||
|
return True
|
||||||
|
# or insn falls at the end before return in a terminal basic block.
|
||||||
|
if basic_block_index not in (e.source_basic_block_index for e in flow_graph.edge):
|
||||||
|
last_addr: int = max((idx.insn_address_by_index[ir.end_index - 1] for ir in bb.instruction_index))
|
||||||
|
if instruction_address > last_addr - SECURITY_COOKIE_BYTES_DELTA:
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
NZXOR_PATTERNS = BinExport2InstructionPatternMatcher.from_str(
|
||||||
|
"""
|
||||||
|
xor|xorpd|xorps|pxor reg, reg
|
||||||
|
xor|xorpd|xorps|pxor reg, #int
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_insn_nzxor_characteristic_features(
|
||||||
|
fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle
|
||||||
|
) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
"""
|
||||||
|
parse non-zeroing XOR instruction from the given instruction.
|
||||||
|
ignore expected non-zeroing XORs, e.g. security cookies.
|
||||||
|
"""
|
||||||
|
fhi: FunctionContext = fh.inner
|
||||||
|
ii: InstructionContext = ih.inner
|
||||||
|
|
||||||
|
be2: BinExport2 = fhi.ctx.be2
|
||||||
|
idx: BinExport2Index = fhi.ctx.idx
|
||||||
|
|
||||||
|
if NZXOR_PATTERNS.match_with_be2(be2, ii.instruction_index) is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
instruction: BinExport2.Instruction = be2.instruction[ii.instruction_index]
|
||||||
|
# guaranteed to be simple int/reg operands
|
||||||
|
# so we don't have to realize the tree/list.
|
||||||
|
operands: List[BinExport2.Operand] = [be2.operand[operand_index] for operand_index in instruction.operand_index]
|
||||||
|
|
||||||
|
if operands[0] == operands[1]:
|
||||||
|
return
|
||||||
|
|
||||||
|
instruction_address: int = idx.insn_address_by_index[ii.instruction_index]
|
||||||
|
if is_security_cookie(fhi, bbh.inner, instruction_address, instruction):
|
||||||
|
return
|
||||||
|
|
||||||
|
yield Characteristic("nzxor"), ih.address
|
||||||
|
|
||||||
|
|
||||||
|
INDIRECT_CALL_PATTERNS = BinExport2InstructionPatternMatcher.from_str(
|
||||||
|
"""
|
||||||
|
call|jmp reg0
|
||||||
|
call|jmp [reg + reg * #int + #int]
|
||||||
|
call|jmp [reg + reg * #int]
|
||||||
|
call|jmp [reg * #int + #int]
|
||||||
|
call|jmp [reg + reg + #int]
|
||||||
|
call|jmp [reg + #int]
|
||||||
|
call|jmp [reg]
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_function_indirect_call_characteristic_features(
|
||||||
|
fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle
|
||||||
|
) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
fhi: FunctionContext = fh.inner
|
||||||
|
ii: InstructionContext = ih.inner
|
||||||
|
be2: BinExport2 = fhi.ctx.be2
|
||||||
|
|
||||||
|
match = INDIRECT_CALL_PATTERNS.match_with_be2(be2, ii.instruction_index)
|
||||||
|
if match is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
yield Characteristic("indirect call"), ih.address
|
||||||
40
capa/features/extractors/binexport2/basicblock.py
Normal file
40
capa/features/extractors/binexport2/basicblock.py
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
|
||||||
|
from typing import List, Tuple, Iterator
|
||||||
|
|
||||||
|
from capa.features.common import Feature, Characteristic
|
||||||
|
from capa.features.address import Address, AbsoluteVirtualAddress
|
||||||
|
from capa.features.basicblock import BasicBlock
|
||||||
|
from capa.features.extractors.binexport2 import FunctionContext, BasicBlockContext
|
||||||
|
from capa.features.extractors.base_extractor import BBHandle, FunctionHandle
|
||||||
|
from capa.features.extractors.binexport2.binexport2_pb2 import BinExport2
|
||||||
|
|
||||||
|
|
||||||
|
def extract_bb_tight_loop(fh: FunctionHandle, bbh: BBHandle) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
fhi: FunctionContext = fh.inner
|
||||||
|
bbi: BasicBlockContext = bbh.inner
|
||||||
|
|
||||||
|
idx = fhi.ctx.idx
|
||||||
|
|
||||||
|
basic_block_index: int = bbi.basic_block_index
|
||||||
|
target_edges: List[BinExport2.FlowGraph.Edge] = idx.target_edges_by_basic_block_index[basic_block_index]
|
||||||
|
if basic_block_index in (e.source_basic_block_index for e in target_edges):
|
||||||
|
basic_block_address: int = idx.get_basic_block_address(basic_block_index)
|
||||||
|
yield Characteristic("tight loop"), AbsoluteVirtualAddress(basic_block_address)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_features(fh: FunctionHandle, bbh: BBHandle) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
"""extract basic block features"""
|
||||||
|
for bb_handler in BASIC_BLOCK_HANDLERS:
|
||||||
|
for feature, addr in bb_handler(fh, bbh):
|
||||||
|
yield feature, addr
|
||||||
|
yield BasicBlock(), bbh.address
|
||||||
|
|
||||||
|
|
||||||
|
BASIC_BLOCK_HANDLERS = (extract_bb_tight_loop,)
|
||||||
72
capa/features/extractors/binexport2/binexport2_pb2.py
Normal file
72
capa/features/extractors/binexport2/binexport2_pb2.py
Normal file
File diff suppressed because one or more lines are too long
784
capa/features/extractors/binexport2/binexport2_pb2.pyi
Normal file
784
capa/features/extractors/binexport2/binexport2_pb2.pyi
Normal file
@@ -0,0 +1,784 @@
|
|||||||
|
"""
|
||||||
|
@generated by mypy-protobuf. Do not edit manually!
|
||||||
|
isort:skip_file
|
||||||
|
The representation is generic to accommodate various source architectures.
|
||||||
|
In particular 32 and 64 bit versions of x86, ARM, PowerPC and MIPS have been
|
||||||
|
tested.
|
||||||
|
|
||||||
|
Multiple levels of deduping have been applied to make the format more compact
|
||||||
|
and avoid redundant data duplication. Some of this due to hard-earned
|
||||||
|
experience trying to cope with intentionally obfuscated malicious binaries.
|
||||||
|
Note in particular that the same instruction may occur in multiple basic
|
||||||
|
blocks and the same basic block in multiple functions (instruction and basic
|
||||||
|
block sharing). Implemented naively, malware can use this to cause
|
||||||
|
combinatorial explosion in memory usage, DOSing the analyst. This format
|
||||||
|
should store every unique expression, mnemonic, operand, instruction and
|
||||||
|
basic block only once instead of duplicating the information for every
|
||||||
|
instance of it.
|
||||||
|
|
||||||
|
This format does _not_ try to be 100% backwards compatible with the old
|
||||||
|
version. In particular, we do not store IDA's comment types, making lossless
|
||||||
|
porting of IDA comments impossible. We do however, store comments and
|
||||||
|
expression substitutions, so porting the actual data is possible, just not
|
||||||
|
the exact IDA type.
|
||||||
|
|
||||||
|
While it would be more natural to use addresses when defining call graph and
|
||||||
|
flow graph edges and other such references, it is more efficient to employ
|
||||||
|
one more level of indirection and use indices into the basic block or
|
||||||
|
function arrays instead. This is because addresses will usually use most of
|
||||||
|
the available 64 bit space while indices will be much smaller and compress
|
||||||
|
much better (less randomly distributed).
|
||||||
|
|
||||||
|
We omit all fields that are set to their default value anyways. Note that
|
||||||
|
this has two side effects:
|
||||||
|
- changing the defaults in this proto file will, in effect, change what's
|
||||||
|
read from disk
|
||||||
|
- the generated code has_* methods are somewhat less useful
|
||||||
|
WARNING: We omit the defaults manually in the code writing the data. Do not
|
||||||
|
change the defaults here without changing the code!
|
||||||
|
|
||||||
|
TODO(cblichmann): Link flow graphs to call graph nodes. The connection is
|
||||||
|
there via the address, but tricky to extract.
|
||||||
|
"""
|
||||||
|
import builtins
|
||||||
|
import collections.abc
|
||||||
|
import google.protobuf.descriptor
|
||||||
|
import google.protobuf.internal.containers
|
||||||
|
import google.protobuf.internal.enum_type_wrapper
|
||||||
|
import google.protobuf.message
|
||||||
|
import sys
|
||||||
|
import typing
|
||||||
|
|
||||||
|
if sys.version_info >= (3, 10):
|
||||||
|
import typing as typing_extensions
|
||||||
|
else:
|
||||||
|
import typing_extensions
|
||||||
|
|
||||||
|
DESCRIPTOR: google.protobuf.descriptor.FileDescriptor
|
||||||
|
|
||||||
|
@typing_extensions.final
|
||||||
|
class BinExport2(google.protobuf.message.Message):
|
||||||
|
DESCRIPTOR: google.protobuf.descriptor.Descriptor
|
||||||
|
|
||||||
|
@typing_extensions.final
|
||||||
|
class Meta(google.protobuf.message.Message):
|
||||||
|
DESCRIPTOR: google.protobuf.descriptor.Descriptor
|
||||||
|
|
||||||
|
EXECUTABLE_NAME_FIELD_NUMBER: builtins.int
|
||||||
|
EXECUTABLE_ID_FIELD_NUMBER: builtins.int
|
||||||
|
ARCHITECTURE_NAME_FIELD_NUMBER: builtins.int
|
||||||
|
TIMESTAMP_FIELD_NUMBER: builtins.int
|
||||||
|
executable_name: builtins.str
|
||||||
|
"""Input binary filename including file extension but excluding file path.
|
||||||
|
example: "insider_gcc.exe"
|
||||||
|
"""
|
||||||
|
executable_id: builtins.str
|
||||||
|
"""Application defined executable id. Often the SHA256 hash of the input
|
||||||
|
binary.
|
||||||
|
"""
|
||||||
|
architecture_name: builtins.str
|
||||||
|
"""Input architecture name, e.g. x86-32."""
|
||||||
|
timestamp: builtins.int
|
||||||
|
"""When did this file get created? Unix time. This may be used for some
|
||||||
|
primitive versioning in case the file format ever changes.
|
||||||
|
"""
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
executable_name: builtins.str | None = ...,
|
||||||
|
executable_id: builtins.str | None = ...,
|
||||||
|
architecture_name: builtins.str | None = ...,
|
||||||
|
timestamp: builtins.int | None = ...,
|
||||||
|
) -> None: ...
|
||||||
|
def HasField(self, field_name: typing_extensions.Literal["architecture_name", b"architecture_name", "executable_id", b"executable_id", "executable_name", b"executable_name", "timestamp", b"timestamp"]) -> builtins.bool: ...
|
||||||
|
def ClearField(self, field_name: typing_extensions.Literal["architecture_name", b"architecture_name", "executable_id", b"executable_id", "executable_name", b"executable_name", "timestamp", b"timestamp"]) -> None: ...
|
||||||
|
|
||||||
|
@typing_extensions.final
|
||||||
|
class CallGraph(google.protobuf.message.Message):
|
||||||
|
DESCRIPTOR: google.protobuf.descriptor.Descriptor
|
||||||
|
|
||||||
|
@typing_extensions.final
|
||||||
|
class Vertex(google.protobuf.message.Message):
|
||||||
|
DESCRIPTOR: google.protobuf.descriptor.Descriptor
|
||||||
|
|
||||||
|
class _Type:
|
||||||
|
ValueType = typing.NewType("ValueType", builtins.int)
|
||||||
|
V: typing_extensions.TypeAlias = ValueType
|
||||||
|
|
||||||
|
class _TypeEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[BinExport2.CallGraph.Vertex._Type.ValueType], builtins.type):
|
||||||
|
DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor
|
||||||
|
NORMAL: BinExport2.CallGraph.Vertex._Type.ValueType # 0
|
||||||
|
"""Regular function with full disassembly."""
|
||||||
|
LIBRARY: BinExport2.CallGraph.Vertex._Type.ValueType # 1
|
||||||
|
"""This function is a well known library function."""
|
||||||
|
IMPORTED: BinExport2.CallGraph.Vertex._Type.ValueType # 2
|
||||||
|
"""Imported from a dynamic link library (e.g. dll)."""
|
||||||
|
THUNK: BinExport2.CallGraph.Vertex._Type.ValueType # 3
|
||||||
|
"""A thunk function, forwarding its work via an unconditional jump."""
|
||||||
|
INVALID: BinExport2.CallGraph.Vertex._Type.ValueType # 4
|
||||||
|
"""An invalid function (a function that contained invalid code or was
|
||||||
|
considered invalid by some heuristics).
|
||||||
|
"""
|
||||||
|
|
||||||
|
class Type(_Type, metaclass=_TypeEnumTypeWrapper): ...
|
||||||
|
NORMAL: BinExport2.CallGraph.Vertex.Type.ValueType # 0
|
||||||
|
"""Regular function with full disassembly."""
|
||||||
|
LIBRARY: BinExport2.CallGraph.Vertex.Type.ValueType # 1
|
||||||
|
"""This function is a well known library function."""
|
||||||
|
IMPORTED: BinExport2.CallGraph.Vertex.Type.ValueType # 2
|
||||||
|
"""Imported from a dynamic link library (e.g. dll)."""
|
||||||
|
THUNK: BinExport2.CallGraph.Vertex.Type.ValueType # 3
|
||||||
|
"""A thunk function, forwarding its work via an unconditional jump."""
|
||||||
|
INVALID: BinExport2.CallGraph.Vertex.Type.ValueType # 4
|
||||||
|
"""An invalid function (a function that contained invalid code or was
|
||||||
|
considered invalid by some heuristics).
|
||||||
|
"""
|
||||||
|
|
||||||
|
ADDRESS_FIELD_NUMBER: builtins.int
|
||||||
|
TYPE_FIELD_NUMBER: builtins.int
|
||||||
|
MANGLED_NAME_FIELD_NUMBER: builtins.int
|
||||||
|
DEMANGLED_NAME_FIELD_NUMBER: builtins.int
|
||||||
|
LIBRARY_INDEX_FIELD_NUMBER: builtins.int
|
||||||
|
MODULE_INDEX_FIELD_NUMBER: builtins.int
|
||||||
|
address: builtins.int
|
||||||
|
"""The function's entry point address. Messages need to be sorted, see
|
||||||
|
comment below on `vertex`.
|
||||||
|
"""
|
||||||
|
type: global___BinExport2.CallGraph.Vertex.Type.ValueType
|
||||||
|
mangled_name: builtins.str
|
||||||
|
"""If the function has a user defined, real name it will be given here.
|
||||||
|
main() is a proper name, sub_BAADF00D is not (auto generated dummy
|
||||||
|
name).
|
||||||
|
"""
|
||||||
|
demangled_name: builtins.str
|
||||||
|
"""Demangled name if the function is a mangled C++ function and we could
|
||||||
|
demangle it.
|
||||||
|
"""
|
||||||
|
library_index: builtins.int
|
||||||
|
"""If this is a library function, what is its index in library arrays."""
|
||||||
|
module_index: builtins.int
|
||||||
|
"""If module name, such as class name for DEX files, is present - index in
|
||||||
|
module table.
|
||||||
|
"""
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
address: builtins.int | None = ...,
|
||||||
|
type: global___BinExport2.CallGraph.Vertex.Type.ValueType | None = ...,
|
||||||
|
mangled_name: builtins.str | None = ...,
|
||||||
|
demangled_name: builtins.str | None = ...,
|
||||||
|
library_index: builtins.int | None = ...,
|
||||||
|
module_index: builtins.int | None = ...,
|
||||||
|
) -> None: ...
|
||||||
|
def HasField(self, field_name: typing_extensions.Literal["address", b"address", "demangled_name", b"demangled_name", "library_index", b"library_index", "mangled_name", b"mangled_name", "module_index", b"module_index", "type", b"type"]) -> builtins.bool: ...
|
||||||
|
def ClearField(self, field_name: typing_extensions.Literal["address", b"address", "demangled_name", b"demangled_name", "library_index", b"library_index", "mangled_name", b"mangled_name", "module_index", b"module_index", "type", b"type"]) -> None: ...
|
||||||
|
|
||||||
|
@typing_extensions.final
|
||||||
|
class Edge(google.protobuf.message.Message):
|
||||||
|
DESCRIPTOR: google.protobuf.descriptor.Descriptor
|
||||||
|
|
||||||
|
SOURCE_VERTEX_INDEX_FIELD_NUMBER: builtins.int
|
||||||
|
TARGET_VERTEX_INDEX_FIELD_NUMBER: builtins.int
|
||||||
|
source_vertex_index: builtins.int
|
||||||
|
"""source and target index into the vertex repeated field."""
|
||||||
|
target_vertex_index: builtins.int
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
source_vertex_index: builtins.int | None = ...,
|
||||||
|
target_vertex_index: builtins.int | None = ...,
|
||||||
|
) -> None: ...
|
||||||
|
def HasField(self, field_name: typing_extensions.Literal["source_vertex_index", b"source_vertex_index", "target_vertex_index", b"target_vertex_index"]) -> builtins.bool: ...
|
||||||
|
def ClearField(self, field_name: typing_extensions.Literal["source_vertex_index", b"source_vertex_index", "target_vertex_index", b"target_vertex_index"]) -> None: ...
|
||||||
|
|
||||||
|
VERTEX_FIELD_NUMBER: builtins.int
|
||||||
|
EDGE_FIELD_NUMBER: builtins.int
|
||||||
|
@property
|
||||||
|
def vertex(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___BinExport2.CallGraph.Vertex]:
|
||||||
|
"""vertices == functions in the call graph.
|
||||||
|
Important: Most downstream tooling (notably BinDiff), need these to be
|
||||||
|
sorted by `Vertex::address` (ascending). For C++, the
|
||||||
|
`BinExport2Writer` class enforces this invariant.
|
||||||
|
"""
|
||||||
|
@property
|
||||||
|
def edge(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___BinExport2.CallGraph.Edge]:
|
||||||
|
"""edges == calls in the call graph."""
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
vertex: collections.abc.Iterable[global___BinExport2.CallGraph.Vertex] | None = ...,
|
||||||
|
edge: collections.abc.Iterable[global___BinExport2.CallGraph.Edge] | None = ...,
|
||||||
|
) -> None: ...
|
||||||
|
def ClearField(self, field_name: typing_extensions.Literal["edge", b"edge", "vertex", b"vertex"]) -> None: ...
|
||||||
|
|
||||||
|
@typing_extensions.final
|
||||||
|
class Expression(google.protobuf.message.Message):
|
||||||
|
"""An operand consists of 1 or more expressions, linked together as a tree."""
|
||||||
|
|
||||||
|
DESCRIPTOR: google.protobuf.descriptor.Descriptor
|
||||||
|
|
||||||
|
class _Type:
|
||||||
|
ValueType = typing.NewType("ValueType", builtins.int)
|
||||||
|
V: typing_extensions.TypeAlias = ValueType
|
||||||
|
|
||||||
|
class _TypeEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[BinExport2.Expression._Type.ValueType], builtins.type):
|
||||||
|
DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor
|
||||||
|
SYMBOL: BinExport2.Expression._Type.ValueType # 1
|
||||||
|
IMMEDIATE_INT: BinExport2.Expression._Type.ValueType # 2
|
||||||
|
IMMEDIATE_FLOAT: BinExport2.Expression._Type.ValueType # 3
|
||||||
|
OPERATOR: BinExport2.Expression._Type.ValueType # 4
|
||||||
|
REGISTER: BinExport2.Expression._Type.ValueType # 5
|
||||||
|
SIZE_PREFIX: BinExport2.Expression._Type.ValueType # 6
|
||||||
|
DEREFERENCE: BinExport2.Expression._Type.ValueType # 7
|
||||||
|
|
||||||
|
class Type(_Type, metaclass=_TypeEnumTypeWrapper): ...
|
||||||
|
SYMBOL: BinExport2.Expression.Type.ValueType # 1
|
||||||
|
IMMEDIATE_INT: BinExport2.Expression.Type.ValueType # 2
|
||||||
|
IMMEDIATE_FLOAT: BinExport2.Expression.Type.ValueType # 3
|
||||||
|
OPERATOR: BinExport2.Expression.Type.ValueType # 4
|
||||||
|
REGISTER: BinExport2.Expression.Type.ValueType # 5
|
||||||
|
SIZE_PREFIX: BinExport2.Expression.Type.ValueType # 6
|
||||||
|
DEREFERENCE: BinExport2.Expression.Type.ValueType # 7
|
||||||
|
|
||||||
|
TYPE_FIELD_NUMBER: builtins.int
|
||||||
|
SYMBOL_FIELD_NUMBER: builtins.int
|
||||||
|
IMMEDIATE_FIELD_NUMBER: builtins.int
|
||||||
|
PARENT_INDEX_FIELD_NUMBER: builtins.int
|
||||||
|
IS_RELOCATION_FIELD_NUMBER: builtins.int
|
||||||
|
type: global___BinExport2.Expression.Type.ValueType
|
||||||
|
"""IMMEDIATE_INT is by far the most common type and thus we can save some
|
||||||
|
space by omitting it as the default.
|
||||||
|
"""
|
||||||
|
symbol: builtins.str
|
||||||
|
"""Symbol for this expression. Interpretation depends on type. Examples
|
||||||
|
include: "eax", "[", "+"
|
||||||
|
"""
|
||||||
|
immediate: builtins.int
|
||||||
|
"""If the expression can be interpreted as an integer value (IMMEDIATE_INT)
|
||||||
|
the value is given here.
|
||||||
|
"""
|
||||||
|
parent_index: builtins.int
|
||||||
|
"""The parent expression. Example expression tree for the second operand of:
|
||||||
|
mov eax, b4 [ebx + 12]
|
||||||
|
"b4" --- "[" --- "+" --- "ebx"
|
||||||
|
\\ "12"
|
||||||
|
"""
|
||||||
|
is_relocation: builtins.bool
|
||||||
|
"""true if the expression has entry in relocation table"""
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
type: global___BinExport2.Expression.Type.ValueType | None = ...,
|
||||||
|
symbol: builtins.str | None = ...,
|
||||||
|
immediate: builtins.int | None = ...,
|
||||||
|
parent_index: builtins.int | None = ...,
|
||||||
|
is_relocation: builtins.bool | None = ...,
|
||||||
|
) -> None: ...
|
||||||
|
def HasField(self, field_name: typing_extensions.Literal["immediate", b"immediate", "is_relocation", b"is_relocation", "parent_index", b"parent_index", "symbol", b"symbol", "type", b"type"]) -> builtins.bool: ...
|
||||||
|
def ClearField(self, field_name: typing_extensions.Literal["immediate", b"immediate", "is_relocation", b"is_relocation", "parent_index", b"parent_index", "symbol", b"symbol", "type", b"type"]) -> None: ...
|
||||||
|
|
||||||
|
@typing_extensions.final
|
||||||
|
class Operand(google.protobuf.message.Message):
|
||||||
|
"""An instruction may have 0 or more operands."""
|
||||||
|
|
||||||
|
DESCRIPTOR: google.protobuf.descriptor.Descriptor
|
||||||
|
|
||||||
|
EXPRESSION_INDEX_FIELD_NUMBER: builtins.int
|
||||||
|
@property
|
||||||
|
def expression_index(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]:
|
||||||
|
"""Contains all expressions constituting this operand. All expressions
|
||||||
|
should be linked into a single tree, i.e. there should only be one
|
||||||
|
expression in this list with parent_index == NULL and all others should
|
||||||
|
descend from that. Rendering order for expressions on the same tree level
|
||||||
|
(siblings) is implicitly given by the order they are referenced in this
|
||||||
|
repeated field.
|
||||||
|
Implicit: expression sequence
|
||||||
|
"""
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
expression_index: collections.abc.Iterable[builtins.int] | None = ...,
|
||||||
|
) -> None: ...
|
||||||
|
def ClearField(self, field_name: typing_extensions.Literal["expression_index", b"expression_index"]) -> None: ...
|
||||||
|
|
||||||
|
@typing_extensions.final
|
||||||
|
class Mnemonic(google.protobuf.message.Message):
|
||||||
|
"""An instruction has exactly 1 mnemonic."""
|
||||||
|
|
||||||
|
DESCRIPTOR: google.protobuf.descriptor.Descriptor
|
||||||
|
|
||||||
|
NAME_FIELD_NUMBER: builtins.int
|
||||||
|
name: builtins.str
|
||||||
|
"""Literal representation of the mnemonic, e.g.: "mov"."""
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
name: builtins.str | None = ...,
|
||||||
|
) -> None: ...
|
||||||
|
def HasField(self, field_name: typing_extensions.Literal["name", b"name"]) -> builtins.bool: ...
|
||||||
|
def ClearField(self, field_name: typing_extensions.Literal["name", b"name"]) -> None: ...
|
||||||
|
|
||||||
|
@typing_extensions.final
|
||||||
|
class Instruction(google.protobuf.message.Message):
|
||||||
|
DESCRIPTOR: google.protobuf.descriptor.Descriptor
|
||||||
|
|
||||||
|
ADDRESS_FIELD_NUMBER: builtins.int
|
||||||
|
CALL_TARGET_FIELD_NUMBER: builtins.int
|
||||||
|
MNEMONIC_INDEX_FIELD_NUMBER: builtins.int
|
||||||
|
OPERAND_INDEX_FIELD_NUMBER: builtins.int
|
||||||
|
RAW_BYTES_FIELD_NUMBER: builtins.int
|
||||||
|
COMMENT_INDEX_FIELD_NUMBER: builtins.int
|
||||||
|
address: builtins.int
|
||||||
|
"""This will only be filled for instructions that do not just flow from the
|
||||||
|
immediately preceding instruction. Regular instructions will have to
|
||||||
|
calculate their own address by adding raw_bytes.size() to the previous
|
||||||
|
instruction's address.
|
||||||
|
"""
|
||||||
|
@property
|
||||||
|
def call_target(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]:
|
||||||
|
"""If this is a call instruction and call targets could be determined
|
||||||
|
they'll be given here. Note that we may or may not have a flow graph for
|
||||||
|
the target and thus cannot use an index into the flow graph table here.
|
||||||
|
We could potentially use call graph nodes, but linking instructions to
|
||||||
|
the call graph directly does not seem a good choice.
|
||||||
|
"""
|
||||||
|
mnemonic_index: builtins.int
|
||||||
|
"""Index into the mnemonic array of strings. Used for de-duping the data.
|
||||||
|
The default value is used for the most common mnemonic in the executable.
|
||||||
|
"""
|
||||||
|
@property
|
||||||
|
def operand_index(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]:
|
||||||
|
"""Indices into the operand tree. On X86 this can be 0, 1 or 2 elements
|
||||||
|
long, 3 elements with VEX/EVEX.
|
||||||
|
Implicit: operand sequence
|
||||||
|
"""
|
||||||
|
raw_bytes: builtins.bytes
|
||||||
|
"""The unmodified input bytes corresponding to this instruction."""
|
||||||
|
@property
|
||||||
|
def comment_index(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]:
|
||||||
|
"""Implicit: comment sequence"""
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
address: builtins.int | None = ...,
|
||||||
|
call_target: collections.abc.Iterable[builtins.int] | None = ...,
|
||||||
|
mnemonic_index: builtins.int | None = ...,
|
||||||
|
operand_index: collections.abc.Iterable[builtins.int] | None = ...,
|
||||||
|
raw_bytes: builtins.bytes | None = ...,
|
||||||
|
comment_index: collections.abc.Iterable[builtins.int] | None = ...,
|
||||||
|
) -> None: ...
|
||||||
|
def HasField(self, field_name: typing_extensions.Literal["address", b"address", "mnemonic_index", b"mnemonic_index", "raw_bytes", b"raw_bytes"]) -> builtins.bool: ...
|
||||||
|
def ClearField(self, field_name: typing_extensions.Literal["address", b"address", "call_target", b"call_target", "comment_index", b"comment_index", "mnemonic_index", b"mnemonic_index", "operand_index", b"operand_index", "raw_bytes", b"raw_bytes"]) -> None: ...
|
||||||
|
|
||||||
|
@typing_extensions.final
|
||||||
|
class BasicBlock(google.protobuf.message.Message):
|
||||||
|
DESCRIPTOR: google.protobuf.descriptor.Descriptor
|
||||||
|
|
||||||
|
@typing_extensions.final
|
||||||
|
class IndexRange(google.protobuf.message.Message):
|
||||||
|
"""This is a space optimization. The instructions for an individual basic
|
||||||
|
block will usually be in a continuous index range. Thus it is more
|
||||||
|
efficient to store the range instead of individual indices. However, this
|
||||||
|
does not hold true for all basic blocks, so we need to be able to store
|
||||||
|
multiple index ranges per block.
|
||||||
|
"""
|
||||||
|
|
||||||
|
DESCRIPTOR: google.protobuf.descriptor.Descriptor
|
||||||
|
|
||||||
|
BEGIN_INDEX_FIELD_NUMBER: builtins.int
|
||||||
|
END_INDEX_FIELD_NUMBER: builtins.int
|
||||||
|
begin_index: builtins.int
|
||||||
|
"""These work like begin and end iterators, i.e. the sequence is
|
||||||
|
[begin_index, end_index). If the sequence only contains a single
|
||||||
|
element end_index will be omitted.
|
||||||
|
"""
|
||||||
|
end_index: builtins.int
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
begin_index: builtins.int | None = ...,
|
||||||
|
end_index: builtins.int | None = ...,
|
||||||
|
) -> None: ...
|
||||||
|
def HasField(self, field_name: typing_extensions.Literal["begin_index", b"begin_index", "end_index", b"end_index"]) -> builtins.bool: ...
|
||||||
|
def ClearField(self, field_name: typing_extensions.Literal["begin_index", b"begin_index", "end_index", b"end_index"]) -> None: ...
|
||||||
|
|
||||||
|
INSTRUCTION_INDEX_FIELD_NUMBER: builtins.int
|
||||||
|
@property
|
||||||
|
def instruction_index(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___BinExport2.BasicBlock.IndexRange]:
|
||||||
|
"""Implicit: instruction sequence"""
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
instruction_index: collections.abc.Iterable[global___BinExport2.BasicBlock.IndexRange] | None = ...,
|
||||||
|
) -> None: ...
|
||||||
|
def ClearField(self, field_name: typing_extensions.Literal["instruction_index", b"instruction_index"]) -> None: ...
|
||||||
|
|
||||||
|
@typing_extensions.final
|
||||||
|
class FlowGraph(google.protobuf.message.Message):
|
||||||
|
DESCRIPTOR: google.protobuf.descriptor.Descriptor
|
||||||
|
|
||||||
|
@typing_extensions.final
|
||||||
|
class Edge(google.protobuf.message.Message):
|
||||||
|
DESCRIPTOR: google.protobuf.descriptor.Descriptor
|
||||||
|
|
||||||
|
class _Type:
|
||||||
|
ValueType = typing.NewType("ValueType", builtins.int)
|
||||||
|
V: typing_extensions.TypeAlias = ValueType
|
||||||
|
|
||||||
|
class _TypeEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[BinExport2.FlowGraph.Edge._Type.ValueType], builtins.type):
|
||||||
|
DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor
|
||||||
|
CONDITION_TRUE: BinExport2.FlowGraph.Edge._Type.ValueType # 1
|
||||||
|
CONDITION_FALSE: BinExport2.FlowGraph.Edge._Type.ValueType # 2
|
||||||
|
UNCONDITIONAL: BinExport2.FlowGraph.Edge._Type.ValueType # 3
|
||||||
|
SWITCH: BinExport2.FlowGraph.Edge._Type.ValueType # 4
|
||||||
|
|
||||||
|
class Type(_Type, metaclass=_TypeEnumTypeWrapper): ...
|
||||||
|
CONDITION_TRUE: BinExport2.FlowGraph.Edge.Type.ValueType # 1
|
||||||
|
CONDITION_FALSE: BinExport2.FlowGraph.Edge.Type.ValueType # 2
|
||||||
|
UNCONDITIONAL: BinExport2.FlowGraph.Edge.Type.ValueType # 3
|
||||||
|
SWITCH: BinExport2.FlowGraph.Edge.Type.ValueType # 4
|
||||||
|
|
||||||
|
SOURCE_BASIC_BLOCK_INDEX_FIELD_NUMBER: builtins.int
|
||||||
|
TARGET_BASIC_BLOCK_INDEX_FIELD_NUMBER: builtins.int
|
||||||
|
TYPE_FIELD_NUMBER: builtins.int
|
||||||
|
IS_BACK_EDGE_FIELD_NUMBER: builtins.int
|
||||||
|
source_basic_block_index: builtins.int
|
||||||
|
"""Source instruction will always be the last instruction of the source
|
||||||
|
basic block, target instruction the first instruction of the target
|
||||||
|
basic block.
|
||||||
|
"""
|
||||||
|
target_basic_block_index: builtins.int
|
||||||
|
type: global___BinExport2.FlowGraph.Edge.Type.ValueType
|
||||||
|
is_back_edge: builtins.bool
|
||||||
|
"""Indicates whether this is a loop edge as determined by Lengauer-Tarjan."""
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
source_basic_block_index: builtins.int | None = ...,
|
||||||
|
target_basic_block_index: builtins.int | None = ...,
|
||||||
|
type: global___BinExport2.FlowGraph.Edge.Type.ValueType | None = ...,
|
||||||
|
is_back_edge: builtins.bool | None = ...,
|
||||||
|
) -> None: ...
|
||||||
|
def HasField(self, field_name: typing_extensions.Literal["is_back_edge", b"is_back_edge", "source_basic_block_index", b"source_basic_block_index", "target_basic_block_index", b"target_basic_block_index", "type", b"type"]) -> builtins.bool: ...
|
||||||
|
def ClearField(self, field_name: typing_extensions.Literal["is_back_edge", b"is_back_edge", "source_basic_block_index", b"source_basic_block_index", "target_basic_block_index", b"target_basic_block_index", "type", b"type"]) -> None: ...
|
||||||
|
|
||||||
|
BASIC_BLOCK_INDEX_FIELD_NUMBER: builtins.int
|
||||||
|
ENTRY_BASIC_BLOCK_INDEX_FIELD_NUMBER: builtins.int
|
||||||
|
EDGE_FIELD_NUMBER: builtins.int
|
||||||
|
@property
|
||||||
|
def basic_block_index(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.int]:
|
||||||
|
"""Basic blocks are sorted by address."""
|
||||||
|
entry_basic_block_index: builtins.int
|
||||||
|
"""The flow graph's entry point address is the first instruction of the
|
||||||
|
entry_basic_block.
|
||||||
|
"""
|
||||||
|
@property
|
||||||
|
def edge(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___BinExport2.FlowGraph.Edge]: ...
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
basic_block_index: collections.abc.Iterable[builtins.int] | None = ...,
|
||||||
|
entry_basic_block_index: builtins.int | None = ...,
|
||||||
|
edge: collections.abc.Iterable[global___BinExport2.FlowGraph.Edge] | None = ...,
|
||||||
|
) -> None: ...
|
||||||
|
def HasField(self, field_name: typing_extensions.Literal["entry_basic_block_index", b"entry_basic_block_index"]) -> builtins.bool: ...
|
||||||
|
def ClearField(self, field_name: typing_extensions.Literal["basic_block_index", b"basic_block_index", "edge", b"edge", "entry_basic_block_index", b"entry_basic_block_index"]) -> None: ...
|
||||||
|
|
||||||
|
@typing_extensions.final
|
||||||
|
class Reference(google.protobuf.message.Message):
|
||||||
|
"""Generic reference class used for address comments (deprecated), string
|
||||||
|
references and expression substitutions. It allows referencing from an
|
||||||
|
instruction, operand, expression subtree tuple to a de-duped string in the
|
||||||
|
string table.
|
||||||
|
"""
|
||||||
|
|
||||||
|
DESCRIPTOR: google.protobuf.descriptor.Descriptor
|
||||||
|
|
||||||
|
INSTRUCTION_INDEX_FIELD_NUMBER: builtins.int
|
||||||
|
INSTRUCTION_OPERAND_INDEX_FIELD_NUMBER: builtins.int
|
||||||
|
OPERAND_EXPRESSION_INDEX_FIELD_NUMBER: builtins.int
|
||||||
|
STRING_TABLE_INDEX_FIELD_NUMBER: builtins.int
|
||||||
|
instruction_index: builtins.int
|
||||||
|
"""Index into the global instruction table."""
|
||||||
|
instruction_operand_index: builtins.int
|
||||||
|
"""Index into the operand array local to an instruction."""
|
||||||
|
operand_expression_index: builtins.int
|
||||||
|
"""Index into the expression array local to an operand."""
|
||||||
|
string_table_index: builtins.int
|
||||||
|
"""Index into the global string table."""
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
instruction_index: builtins.int | None = ...,
|
||||||
|
instruction_operand_index: builtins.int | None = ...,
|
||||||
|
operand_expression_index: builtins.int | None = ...,
|
||||||
|
string_table_index: builtins.int | None = ...,
|
||||||
|
) -> None: ...
|
||||||
|
def HasField(self, field_name: typing_extensions.Literal["instruction_index", b"instruction_index", "instruction_operand_index", b"instruction_operand_index", "operand_expression_index", b"operand_expression_index", "string_table_index", b"string_table_index"]) -> builtins.bool: ...
|
||||||
|
def ClearField(self, field_name: typing_extensions.Literal["instruction_index", b"instruction_index", "instruction_operand_index", b"instruction_operand_index", "operand_expression_index", b"operand_expression_index", "string_table_index", b"string_table_index"]) -> None: ...
|
||||||
|
|
||||||
|
@typing_extensions.final
|
||||||
|
class DataReference(google.protobuf.message.Message):
|
||||||
|
DESCRIPTOR: google.protobuf.descriptor.Descriptor
|
||||||
|
|
||||||
|
INSTRUCTION_INDEX_FIELD_NUMBER: builtins.int
|
||||||
|
ADDRESS_FIELD_NUMBER: builtins.int
|
||||||
|
instruction_index: builtins.int
|
||||||
|
"""Index into the global instruction table."""
|
||||||
|
address: builtins.int
|
||||||
|
"""Address being referred."""
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
instruction_index: builtins.int | None = ...,
|
||||||
|
address: builtins.int | None = ...,
|
||||||
|
) -> None: ...
|
||||||
|
def HasField(self, field_name: typing_extensions.Literal["address", b"address", "instruction_index", b"instruction_index"]) -> builtins.bool: ...
|
||||||
|
def ClearField(self, field_name: typing_extensions.Literal["address", b"address", "instruction_index", b"instruction_index"]) -> None: ...
|
||||||
|
|
||||||
|
@typing_extensions.final
|
||||||
|
class Comment(google.protobuf.message.Message):
|
||||||
|
DESCRIPTOR: google.protobuf.descriptor.Descriptor
|
||||||
|
|
||||||
|
class _Type:
|
||||||
|
ValueType = typing.NewType("ValueType", builtins.int)
|
||||||
|
V: typing_extensions.TypeAlias = ValueType
|
||||||
|
|
||||||
|
class _TypeEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[BinExport2.Comment._Type.ValueType], builtins.type):
|
||||||
|
DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor
|
||||||
|
DEFAULT: BinExport2.Comment._Type.ValueType # 0
|
||||||
|
"""A regular instruction comment. Typically displayed next to the
|
||||||
|
instruction disassembly.
|
||||||
|
"""
|
||||||
|
ANTERIOR: BinExport2.Comment._Type.ValueType # 1
|
||||||
|
"""A comment line that is typically displayed before (above) the
|
||||||
|
instruction it refers to.
|
||||||
|
"""
|
||||||
|
POSTERIOR: BinExport2.Comment._Type.ValueType # 2
|
||||||
|
"""Like ANTERIOR, but a typically displayed after (below)."""
|
||||||
|
FUNCTION: BinExport2.Comment._Type.ValueType # 3
|
||||||
|
"""Similar to an ANTERIOR comment, but applies to the beginning of an
|
||||||
|
identified function. Programs displaying the proto may choose to render
|
||||||
|
these differently (e.g. above an inferred function signature).
|
||||||
|
"""
|
||||||
|
ENUM: BinExport2.Comment._Type.ValueType # 4
|
||||||
|
"""Named constants, bitfields and similar."""
|
||||||
|
LOCATION: BinExport2.Comment._Type.ValueType # 5
|
||||||
|
"""Named locations, usually the target of a jump."""
|
||||||
|
GLOBAL_REFERENCE: BinExport2.Comment._Type.ValueType # 6
|
||||||
|
"""Data cross references."""
|
||||||
|
LOCAL_REFERENCE: BinExport2.Comment._Type.ValueType # 7
|
||||||
|
"""Local/stack variables."""
|
||||||
|
|
||||||
|
class Type(_Type, metaclass=_TypeEnumTypeWrapper): ...
|
||||||
|
DEFAULT: BinExport2.Comment.Type.ValueType # 0
|
||||||
|
"""A regular instruction comment. Typically displayed next to the
|
||||||
|
instruction disassembly.
|
||||||
|
"""
|
||||||
|
ANTERIOR: BinExport2.Comment.Type.ValueType # 1
|
||||||
|
"""A comment line that is typically displayed before (above) the
|
||||||
|
instruction it refers to.
|
||||||
|
"""
|
||||||
|
POSTERIOR: BinExport2.Comment.Type.ValueType # 2
|
||||||
|
"""Like ANTERIOR, but a typically displayed after (below)."""
|
||||||
|
FUNCTION: BinExport2.Comment.Type.ValueType # 3
|
||||||
|
"""Similar to an ANTERIOR comment, but applies to the beginning of an
|
||||||
|
identified function. Programs displaying the proto may choose to render
|
||||||
|
these differently (e.g. above an inferred function signature).
|
||||||
|
"""
|
||||||
|
ENUM: BinExport2.Comment.Type.ValueType # 4
|
||||||
|
"""Named constants, bitfields and similar."""
|
||||||
|
LOCATION: BinExport2.Comment.Type.ValueType # 5
|
||||||
|
"""Named locations, usually the target of a jump."""
|
||||||
|
GLOBAL_REFERENCE: BinExport2.Comment.Type.ValueType # 6
|
||||||
|
"""Data cross references."""
|
||||||
|
LOCAL_REFERENCE: BinExport2.Comment.Type.ValueType # 7
|
||||||
|
"""Local/stack variables."""
|
||||||
|
|
||||||
|
INSTRUCTION_INDEX_FIELD_NUMBER: builtins.int
|
||||||
|
INSTRUCTION_OPERAND_INDEX_FIELD_NUMBER: builtins.int
|
||||||
|
OPERAND_EXPRESSION_INDEX_FIELD_NUMBER: builtins.int
|
||||||
|
STRING_TABLE_INDEX_FIELD_NUMBER: builtins.int
|
||||||
|
REPEATABLE_FIELD_NUMBER: builtins.int
|
||||||
|
TYPE_FIELD_NUMBER: builtins.int
|
||||||
|
instruction_index: builtins.int
|
||||||
|
"""Index into the global instruction table. This is here to enable
|
||||||
|
comment processing without having to iterate over all instructions.
|
||||||
|
There is an N:M mapping of instructions to comments.
|
||||||
|
"""
|
||||||
|
instruction_operand_index: builtins.int
|
||||||
|
"""Index into the operand array local to an instruction."""
|
||||||
|
operand_expression_index: builtins.int
|
||||||
|
"""Index into the expression array local to an operand, like in Reference.
|
||||||
|
This is not currently used, but allows to implement expression
|
||||||
|
substitutions.
|
||||||
|
"""
|
||||||
|
string_table_index: builtins.int
|
||||||
|
"""Index into the global string table."""
|
||||||
|
repeatable: builtins.bool
|
||||||
|
"""Comment is propagated to all locations that reference the original
|
||||||
|
location.
|
||||||
|
"""
|
||||||
|
type: global___BinExport2.Comment.Type.ValueType
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
instruction_index: builtins.int | None = ...,
|
||||||
|
instruction_operand_index: builtins.int | None = ...,
|
||||||
|
operand_expression_index: builtins.int | None = ...,
|
||||||
|
string_table_index: builtins.int | None = ...,
|
||||||
|
repeatable: builtins.bool | None = ...,
|
||||||
|
type: global___BinExport2.Comment.Type.ValueType | None = ...,
|
||||||
|
) -> None: ...
|
||||||
|
def HasField(self, field_name: typing_extensions.Literal["instruction_index", b"instruction_index", "instruction_operand_index", b"instruction_operand_index", "operand_expression_index", b"operand_expression_index", "repeatable", b"repeatable", "string_table_index", b"string_table_index", "type", b"type"]) -> builtins.bool: ...
|
||||||
|
def ClearField(self, field_name: typing_extensions.Literal["instruction_index", b"instruction_index", "instruction_operand_index", b"instruction_operand_index", "operand_expression_index", b"operand_expression_index", "repeatable", b"repeatable", "string_table_index", b"string_table_index", "type", b"type"]) -> None: ...
|
||||||
|
|
||||||
|
@typing_extensions.final
|
||||||
|
class Section(google.protobuf.message.Message):
|
||||||
|
DESCRIPTOR: google.protobuf.descriptor.Descriptor
|
||||||
|
|
||||||
|
ADDRESS_FIELD_NUMBER: builtins.int
|
||||||
|
SIZE_FIELD_NUMBER: builtins.int
|
||||||
|
FLAG_R_FIELD_NUMBER: builtins.int
|
||||||
|
FLAG_W_FIELD_NUMBER: builtins.int
|
||||||
|
FLAG_X_FIELD_NUMBER: builtins.int
|
||||||
|
address: builtins.int
|
||||||
|
"""Section start address."""
|
||||||
|
size: builtins.int
|
||||||
|
"""Section size."""
|
||||||
|
flag_r: builtins.bool
|
||||||
|
"""Read flag of the section, True when section is readable."""
|
||||||
|
flag_w: builtins.bool
|
||||||
|
"""Write flag of the section, True when section is writable."""
|
||||||
|
flag_x: builtins.bool
|
||||||
|
"""Execute flag of the section, True when section is executable."""
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
address: builtins.int | None = ...,
|
||||||
|
size: builtins.int | None = ...,
|
||||||
|
flag_r: builtins.bool | None = ...,
|
||||||
|
flag_w: builtins.bool | None = ...,
|
||||||
|
flag_x: builtins.bool | None = ...,
|
||||||
|
) -> None: ...
|
||||||
|
def HasField(self, field_name: typing_extensions.Literal["address", b"address", "flag_r", b"flag_r", "flag_w", b"flag_w", "flag_x", b"flag_x", "size", b"size"]) -> builtins.bool: ...
|
||||||
|
def ClearField(self, field_name: typing_extensions.Literal["address", b"address", "flag_r", b"flag_r", "flag_w", b"flag_w", "flag_x", b"flag_x", "size", b"size"]) -> None: ...
|
||||||
|
|
||||||
|
@typing_extensions.final
|
||||||
|
class Library(google.protobuf.message.Message):
|
||||||
|
DESCRIPTOR: google.protobuf.descriptor.Descriptor
|
||||||
|
|
||||||
|
IS_STATIC_FIELD_NUMBER: builtins.int
|
||||||
|
LOAD_ADDRESS_FIELD_NUMBER: builtins.int
|
||||||
|
NAME_FIELD_NUMBER: builtins.int
|
||||||
|
is_static: builtins.bool
|
||||||
|
"""If this library is statically linked."""
|
||||||
|
load_address: builtins.int
|
||||||
|
"""Address where this library was loaded, 0 if unknown."""
|
||||||
|
name: builtins.str
|
||||||
|
"""Name of the library (format is platform-dependent)."""
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
is_static: builtins.bool | None = ...,
|
||||||
|
load_address: builtins.int | None = ...,
|
||||||
|
name: builtins.str | None = ...,
|
||||||
|
) -> None: ...
|
||||||
|
def HasField(self, field_name: typing_extensions.Literal["is_static", b"is_static", "load_address", b"load_address", "name", b"name"]) -> builtins.bool: ...
|
||||||
|
def ClearField(self, field_name: typing_extensions.Literal["is_static", b"is_static", "load_address", b"load_address", "name", b"name"]) -> None: ...
|
||||||
|
|
||||||
|
@typing_extensions.final
|
||||||
|
class Module(google.protobuf.message.Message):
|
||||||
|
DESCRIPTOR: google.protobuf.descriptor.Descriptor
|
||||||
|
|
||||||
|
NAME_FIELD_NUMBER: builtins.int
|
||||||
|
name: builtins.str
|
||||||
|
"""Name, such as Java class name. Platform-dependent."""
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
name: builtins.str | None = ...,
|
||||||
|
) -> None: ...
|
||||||
|
def HasField(self, field_name: typing_extensions.Literal["name", b"name"]) -> builtins.bool: ...
|
||||||
|
def ClearField(self, field_name: typing_extensions.Literal["name", b"name"]) -> None: ...
|
||||||
|
|
||||||
|
META_INFORMATION_FIELD_NUMBER: builtins.int
|
||||||
|
EXPRESSION_FIELD_NUMBER: builtins.int
|
||||||
|
OPERAND_FIELD_NUMBER: builtins.int
|
||||||
|
MNEMONIC_FIELD_NUMBER: builtins.int
|
||||||
|
INSTRUCTION_FIELD_NUMBER: builtins.int
|
||||||
|
BASIC_BLOCK_FIELD_NUMBER: builtins.int
|
||||||
|
FLOW_GRAPH_FIELD_NUMBER: builtins.int
|
||||||
|
CALL_GRAPH_FIELD_NUMBER: builtins.int
|
||||||
|
STRING_TABLE_FIELD_NUMBER: builtins.int
|
||||||
|
ADDRESS_COMMENT_FIELD_NUMBER: builtins.int
|
||||||
|
COMMENT_FIELD_NUMBER: builtins.int
|
||||||
|
STRING_REFERENCE_FIELD_NUMBER: builtins.int
|
||||||
|
EXPRESSION_SUBSTITUTION_FIELD_NUMBER: builtins.int
|
||||||
|
SECTION_FIELD_NUMBER: builtins.int
|
||||||
|
LIBRARY_FIELD_NUMBER: builtins.int
|
||||||
|
DATA_REFERENCE_FIELD_NUMBER: builtins.int
|
||||||
|
MODULE_FIELD_NUMBER: builtins.int
|
||||||
|
@property
|
||||||
|
def meta_information(self) -> global___BinExport2.Meta: ...
|
||||||
|
@property
|
||||||
|
def expression(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___BinExport2.Expression]: ...
|
||||||
|
@property
|
||||||
|
def operand(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___BinExport2.Operand]: ...
|
||||||
|
@property
|
||||||
|
def mnemonic(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___BinExport2.Mnemonic]: ...
|
||||||
|
@property
|
||||||
|
def instruction(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___BinExport2.Instruction]: ...
|
||||||
|
@property
|
||||||
|
def basic_block(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___BinExport2.BasicBlock]: ...
|
||||||
|
@property
|
||||||
|
def flow_graph(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___BinExport2.FlowGraph]: ...
|
||||||
|
@property
|
||||||
|
def call_graph(self) -> global___BinExport2.CallGraph: ...
|
||||||
|
@property
|
||||||
|
def string_table(self) -> google.protobuf.internal.containers.RepeatedScalarFieldContainer[builtins.str]: ...
|
||||||
|
@property
|
||||||
|
def address_comment(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___BinExport2.Reference]:
|
||||||
|
"""No longer written. This is here so that BinDiff can work with older
|
||||||
|
BinExport files.
|
||||||
|
"""
|
||||||
|
@property
|
||||||
|
def comment(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___BinExport2.Comment]:
|
||||||
|
"""Rich comment index used for BinDiff's comment porting."""
|
||||||
|
@property
|
||||||
|
def string_reference(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___BinExport2.Reference]: ...
|
||||||
|
@property
|
||||||
|
def expression_substitution(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___BinExport2.Reference]: ...
|
||||||
|
@property
|
||||||
|
def section(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___BinExport2.Section]: ...
|
||||||
|
@property
|
||||||
|
def library(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___BinExport2.Library]: ...
|
||||||
|
@property
|
||||||
|
def data_reference(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___BinExport2.DataReference]: ...
|
||||||
|
@property
|
||||||
|
def module(self) -> google.protobuf.internal.containers.RepeatedCompositeFieldContainer[global___BinExport2.Module]: ...
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
meta_information: global___BinExport2.Meta | None = ...,
|
||||||
|
expression: collections.abc.Iterable[global___BinExport2.Expression] | None = ...,
|
||||||
|
operand: collections.abc.Iterable[global___BinExport2.Operand] | None = ...,
|
||||||
|
mnemonic: collections.abc.Iterable[global___BinExport2.Mnemonic] | None = ...,
|
||||||
|
instruction: collections.abc.Iterable[global___BinExport2.Instruction] | None = ...,
|
||||||
|
basic_block: collections.abc.Iterable[global___BinExport2.BasicBlock] | None = ...,
|
||||||
|
flow_graph: collections.abc.Iterable[global___BinExport2.FlowGraph] | None = ...,
|
||||||
|
call_graph: global___BinExport2.CallGraph | None = ...,
|
||||||
|
string_table: collections.abc.Iterable[builtins.str] | None = ...,
|
||||||
|
address_comment: collections.abc.Iterable[global___BinExport2.Reference] | None = ...,
|
||||||
|
comment: collections.abc.Iterable[global___BinExport2.Comment] | None = ...,
|
||||||
|
string_reference: collections.abc.Iterable[global___BinExport2.Reference] | None = ...,
|
||||||
|
expression_substitution: collections.abc.Iterable[global___BinExport2.Reference] | None = ...,
|
||||||
|
section: collections.abc.Iterable[global___BinExport2.Section] | None = ...,
|
||||||
|
library: collections.abc.Iterable[global___BinExport2.Library] | None = ...,
|
||||||
|
data_reference: collections.abc.Iterable[global___BinExport2.DataReference] | None = ...,
|
||||||
|
module: collections.abc.Iterable[global___BinExport2.Module] | None = ...,
|
||||||
|
) -> None: ...
|
||||||
|
def HasField(self, field_name: typing_extensions.Literal["call_graph", b"call_graph", "meta_information", b"meta_information"]) -> builtins.bool: ...
|
||||||
|
def ClearField(self, field_name: typing_extensions.Literal["address_comment", b"address_comment", "basic_block", b"basic_block", "call_graph", b"call_graph", "comment", b"comment", "data_reference", b"data_reference", "expression", b"expression", "expression_substitution", b"expression_substitution", "flow_graph", b"flow_graph", "instruction", b"instruction", "library", b"library", "meta_information", b"meta_information", "mnemonic", b"mnemonic", "module", b"module", "operand", b"operand", "section", b"section", "string_reference", b"string_reference", "string_table", b"string_table"]) -> None: ...
|
||||||
|
|
||||||
|
global___BinExport2 = BinExport2
|
||||||
130
capa/features/extractors/binexport2/extractor.py
Normal file
130
capa/features/extractors/binexport2/extractor.py
Normal file
@@ -0,0 +1,130 @@
|
|||||||
|
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
import logging
|
||||||
|
from typing import Set, List, Tuple, Iterator
|
||||||
|
|
||||||
|
import capa.features.extractors.elf
|
||||||
|
import capa.features.extractors.common
|
||||||
|
import capa.features.extractors.binexport2.file
|
||||||
|
import capa.features.extractors.binexport2.insn
|
||||||
|
import capa.features.extractors.binexport2.helpers
|
||||||
|
import capa.features.extractors.binexport2.function
|
||||||
|
import capa.features.extractors.binexport2.basicblock
|
||||||
|
from capa.features.common import OS, Arch, Format, Feature
|
||||||
|
from capa.features.address import Address, AbsoluteVirtualAddress
|
||||||
|
from capa.features.extractors.binexport2 import (
|
||||||
|
AddressSpace,
|
||||||
|
AnalysisContext,
|
||||||
|
BinExport2Index,
|
||||||
|
FunctionContext,
|
||||||
|
BasicBlockContext,
|
||||||
|
BinExport2Analysis,
|
||||||
|
InstructionContext,
|
||||||
|
)
|
||||||
|
from capa.features.extractors.base_extractor import (
|
||||||
|
BBHandle,
|
||||||
|
InsnHandle,
|
||||||
|
SampleHashes,
|
||||||
|
FunctionHandle,
|
||||||
|
StaticFeatureExtractor,
|
||||||
|
)
|
||||||
|
from capa.features.extractors.binexport2.binexport2_pb2 import BinExport2
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class BinExport2FeatureExtractor(StaticFeatureExtractor):
|
||||||
|
def __init__(self, be2: BinExport2, buf: bytes):
|
||||||
|
super().__init__(hashes=SampleHashes.from_bytes(buf))
|
||||||
|
self.be2: BinExport2 = be2
|
||||||
|
self.buf: bytes = buf
|
||||||
|
self.idx: BinExport2Index = BinExport2Index(self.be2)
|
||||||
|
self.analysis: BinExport2Analysis = BinExport2Analysis(self.be2, self.idx, self.buf)
|
||||||
|
address_space: AddressSpace = AddressSpace.from_buf(buf, self.analysis.base_address)
|
||||||
|
self.ctx: AnalysisContext = AnalysisContext(self.buf, self.be2, self.idx, self.analysis, address_space)
|
||||||
|
|
||||||
|
self.global_features: List[Tuple[Feature, Address]] = []
|
||||||
|
self.global_features.extend(list(capa.features.extractors.common.extract_format(self.buf)))
|
||||||
|
self.global_features.extend(list(capa.features.extractors.common.extract_os(self.buf)))
|
||||||
|
self.global_features.extend(list(capa.features.extractors.common.extract_arch(self.buf)))
|
||||||
|
|
||||||
|
self.format: Set[str] = set()
|
||||||
|
self.os: Set[str] = set()
|
||||||
|
self.arch: Set[str] = set()
|
||||||
|
|
||||||
|
for feature, _ in self.global_features:
|
||||||
|
assert isinstance(feature.value, str)
|
||||||
|
|
||||||
|
if isinstance(feature, Format):
|
||||||
|
self.format.add(feature.value)
|
||||||
|
elif isinstance(feature, OS):
|
||||||
|
self.os.add(feature.value)
|
||||||
|
elif isinstance(feature, Arch):
|
||||||
|
self.arch.add(feature.value)
|
||||||
|
else:
|
||||||
|
raise ValueError("unexpected global feature: %s", feature)
|
||||||
|
|
||||||
|
def get_base_address(self) -> AbsoluteVirtualAddress:
|
||||||
|
return AbsoluteVirtualAddress(self.analysis.base_address)
|
||||||
|
|
||||||
|
def extract_global_features(self) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
yield from self.global_features
|
||||||
|
|
||||||
|
def extract_file_features(self) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
yield from capa.features.extractors.binexport2.file.extract_features(self.be2, self.buf)
|
||||||
|
|
||||||
|
def get_functions(self) -> Iterator[FunctionHandle]:
|
||||||
|
for flow_graph_index, flow_graph in enumerate(self.be2.flow_graph):
|
||||||
|
entry_basic_block_index: int = flow_graph.entry_basic_block_index
|
||||||
|
flow_graph_address: int = self.idx.get_basic_block_address(entry_basic_block_index)
|
||||||
|
|
||||||
|
vertex_idx: int = self.idx.vertex_index_by_address[flow_graph_address]
|
||||||
|
be2_vertex: BinExport2.CallGraph.Vertex = self.be2.call_graph.vertex[vertex_idx]
|
||||||
|
|
||||||
|
# skip thunks
|
||||||
|
if capa.features.extractors.binexport2.helpers.is_vertex_type(
|
||||||
|
be2_vertex, BinExport2.CallGraph.Vertex.Type.THUNK
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
|
||||||
|
yield FunctionHandle(
|
||||||
|
AbsoluteVirtualAddress(flow_graph_address),
|
||||||
|
inner=FunctionContext(self.ctx, flow_graph_index, self.format, self.os, self.arch),
|
||||||
|
)
|
||||||
|
|
||||||
|
def extract_function_features(self, fh: FunctionHandle) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
yield from capa.features.extractors.binexport2.function.extract_features(fh)
|
||||||
|
|
||||||
|
def get_basic_blocks(self, fh: FunctionHandle) -> Iterator[BBHandle]:
|
||||||
|
fhi: FunctionContext = fh.inner
|
||||||
|
flow_graph_index: int = fhi.flow_graph_index
|
||||||
|
flow_graph: BinExport2.FlowGraph = self.be2.flow_graph[flow_graph_index]
|
||||||
|
|
||||||
|
for basic_block_index in flow_graph.basic_block_index:
|
||||||
|
basic_block_address: int = self.idx.get_basic_block_address(basic_block_index)
|
||||||
|
yield BBHandle(
|
||||||
|
address=AbsoluteVirtualAddress(basic_block_address),
|
||||||
|
inner=BasicBlockContext(basic_block_index),
|
||||||
|
)
|
||||||
|
|
||||||
|
def extract_basic_block_features(self, fh: FunctionHandle, bbh: BBHandle) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
yield from capa.features.extractors.binexport2.basicblock.extract_features(fh, bbh)
|
||||||
|
|
||||||
|
def get_instructions(self, fh: FunctionHandle, bbh: BBHandle) -> Iterator[InsnHandle]:
|
||||||
|
bbi: BasicBlockContext = bbh.inner
|
||||||
|
basic_block: BinExport2.BasicBlock = self.be2.basic_block[bbi.basic_block_index]
|
||||||
|
for instruction_index, _, instruction_address in self.idx.basic_block_instructions(basic_block):
|
||||||
|
yield InsnHandle(
|
||||||
|
address=AbsoluteVirtualAddress(instruction_address),
|
||||||
|
inner=InstructionContext(instruction_index),
|
||||||
|
)
|
||||||
|
|
||||||
|
def extract_insn_features(
|
||||||
|
self, fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle
|
||||||
|
) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
yield from capa.features.extractors.binexport2.insn.extract_features(fh, bbh, ih)
|
||||||
80
capa/features/extractors/binexport2/file.py
Normal file
80
capa/features/extractors/binexport2/file.py
Normal file
@@ -0,0 +1,80 @@
|
|||||||
|
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
import io
|
||||||
|
import logging
|
||||||
|
from typing import Tuple, Iterator
|
||||||
|
|
||||||
|
import pefile
|
||||||
|
from elftools.elf.elffile import ELFFile
|
||||||
|
|
||||||
|
import capa.features.common
|
||||||
|
import capa.features.extractors.common
|
||||||
|
import capa.features.extractors.pefile
|
||||||
|
import capa.features.extractors.elffile
|
||||||
|
from capa.features.common import Feature
|
||||||
|
from capa.features.address import Address
|
||||||
|
from capa.features.extractors.binexport2.binexport2_pb2 import BinExport2
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_file_export_names(_be2: BinExport2, buf: bytes) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
if buf.startswith(capa.features.extractors.common.MATCH_PE):
|
||||||
|
pe: pefile.PE = pefile.PE(data=buf)
|
||||||
|
yield from capa.features.extractors.pefile.extract_file_export_names(pe)
|
||||||
|
elif buf.startswith(capa.features.extractors.common.MATCH_ELF):
|
||||||
|
elf: ELFFile = ELFFile(io.BytesIO(buf))
|
||||||
|
yield from capa.features.extractors.elffile.extract_file_export_names(elf)
|
||||||
|
else:
|
||||||
|
logger.warning("unsupported format")
|
||||||
|
|
||||||
|
|
||||||
|
def extract_file_import_names(_be2: BinExport2, buf: bytes) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
if buf.startswith(capa.features.extractors.common.MATCH_PE):
|
||||||
|
pe: pefile.PE = pefile.PE(data=buf)
|
||||||
|
yield from capa.features.extractors.pefile.extract_file_import_names(pe)
|
||||||
|
elif buf.startswith(capa.features.extractors.common.MATCH_ELF):
|
||||||
|
elf: ELFFile = ELFFile(io.BytesIO(buf))
|
||||||
|
yield from capa.features.extractors.elffile.extract_file_import_names(elf)
|
||||||
|
else:
|
||||||
|
logger.warning("unsupported format")
|
||||||
|
|
||||||
|
|
||||||
|
def extract_file_section_names(_be2: BinExport2, buf: bytes) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
if buf.startswith(capa.features.extractors.common.MATCH_PE):
|
||||||
|
pe: pefile.PE = pefile.PE(data=buf)
|
||||||
|
yield from capa.features.extractors.pefile.extract_file_section_names(pe)
|
||||||
|
elif buf.startswith(capa.features.extractors.common.MATCH_ELF):
|
||||||
|
elf: ELFFile = ELFFile(io.BytesIO(buf))
|
||||||
|
yield from capa.features.extractors.elffile.extract_file_section_names(elf)
|
||||||
|
else:
|
||||||
|
logger.warning("unsupported format")
|
||||||
|
|
||||||
|
|
||||||
|
def extract_file_strings(_be2: BinExport2, buf: bytes) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
yield from capa.features.extractors.common.extract_file_strings(buf)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_file_format(_be2: BinExport2, buf: bytes) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
yield from capa.features.extractors.common.extract_format(buf)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_features(be2: BinExport2, buf: bytes) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
"""extract file features"""
|
||||||
|
for file_handler in FILE_HANDLERS:
|
||||||
|
for feature, addr in file_handler(be2, buf):
|
||||||
|
yield feature, addr
|
||||||
|
|
||||||
|
|
||||||
|
FILE_HANDLERS = (
|
||||||
|
extract_file_export_names,
|
||||||
|
extract_file_import_names,
|
||||||
|
extract_file_strings,
|
||||||
|
extract_file_section_names,
|
||||||
|
extract_file_format,
|
||||||
|
)
|
||||||
72
capa/features/extractors/binexport2/function.py
Normal file
72
capa/features/extractors/binexport2/function.py
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
from typing import List, Tuple, Iterator
|
||||||
|
|
||||||
|
from capa.features.file import FunctionName
|
||||||
|
from capa.features.common import Feature, Characteristic
|
||||||
|
from capa.features.address import Address, AbsoluteVirtualAddress
|
||||||
|
from capa.features.extractors import loops
|
||||||
|
from capa.features.extractors.binexport2 import BinExport2Index, FunctionContext
|
||||||
|
from capa.features.extractors.base_extractor import FunctionHandle
|
||||||
|
from capa.features.extractors.binexport2.binexport2_pb2 import BinExport2
|
||||||
|
|
||||||
|
|
||||||
|
def extract_function_calls_to(fh: FunctionHandle) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
fhi: FunctionContext = fh.inner
|
||||||
|
|
||||||
|
be2: BinExport2 = fhi.ctx.be2
|
||||||
|
idx: BinExport2Index = fhi.ctx.idx
|
||||||
|
|
||||||
|
flow_graph_index: int = fhi.flow_graph_index
|
||||||
|
flow_graph_address: int = idx.flow_graph_address_by_index[flow_graph_index]
|
||||||
|
vertex_index: int = idx.vertex_index_by_address[flow_graph_address]
|
||||||
|
|
||||||
|
for caller_index in idx.callers_by_vertex_index[vertex_index]:
|
||||||
|
caller: BinExport2.CallGraph.Vertex = be2.call_graph.vertex[caller_index]
|
||||||
|
caller_address: int = caller.address
|
||||||
|
yield Characteristic("calls to"), AbsoluteVirtualAddress(caller_address)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_function_loop(fh: FunctionHandle) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
fhi: FunctionContext = fh.inner
|
||||||
|
|
||||||
|
be2: BinExport2 = fhi.ctx.be2
|
||||||
|
|
||||||
|
flow_graph_index: int = fhi.flow_graph_index
|
||||||
|
flow_graph: BinExport2.FlowGraph = be2.flow_graph[flow_graph_index]
|
||||||
|
|
||||||
|
edges: List[Tuple[int, int]] = []
|
||||||
|
for edge in flow_graph.edge:
|
||||||
|
edges.append((edge.source_basic_block_index, edge.target_basic_block_index))
|
||||||
|
|
||||||
|
if loops.has_loop(edges):
|
||||||
|
yield Characteristic("loop"), fh.address
|
||||||
|
|
||||||
|
|
||||||
|
def extract_function_name(fh: FunctionHandle) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
fhi: FunctionContext = fh.inner
|
||||||
|
|
||||||
|
be2: BinExport2 = fhi.ctx.be2
|
||||||
|
idx: BinExport2Index = fhi.ctx.idx
|
||||||
|
flow_graph_index: int = fhi.flow_graph_index
|
||||||
|
|
||||||
|
flow_graph_address: int = idx.flow_graph_address_by_index[flow_graph_index]
|
||||||
|
vertex_index: int = idx.vertex_index_by_address[flow_graph_address]
|
||||||
|
vertex: BinExport2.CallGraph.Vertex = be2.call_graph.vertex[vertex_index]
|
||||||
|
|
||||||
|
if vertex.HasField("mangled_name"):
|
||||||
|
yield FunctionName(vertex.mangled_name), fh.address
|
||||||
|
|
||||||
|
|
||||||
|
def extract_features(fh: FunctionHandle) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
for func_handler in FUNCTION_HANDLERS:
|
||||||
|
for feature, addr in func_handler(fh):
|
||||||
|
yield feature, addr
|
||||||
|
|
||||||
|
|
||||||
|
FUNCTION_HANDLERS = (extract_function_calls_to, extract_function_loop, extract_function_name)
|
||||||
650
capa/features/extractors/binexport2/helpers.py
Normal file
650
capa/features/extractors/binexport2/helpers.py
Normal file
@@ -0,0 +1,650 @@
|
|||||||
|
# Copyright (C) 2024 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
import re
|
||||||
|
from typing import Set, Dict, List, Tuple, Union, Iterator, Optional
|
||||||
|
from collections import defaultdict
|
||||||
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
import capa.features.extractors.helpers
|
||||||
|
import capa.features.extractors.binexport2.helpers
|
||||||
|
from capa.features.common import ARCH_I386, ARCH_AMD64, ARCH_AARCH64
|
||||||
|
from capa.features.extractors.binexport2.binexport2_pb2 import BinExport2
|
||||||
|
|
||||||
|
HAS_ARCH32 = {ARCH_I386}
|
||||||
|
HAS_ARCH64 = {ARCH_AARCH64, ARCH_AMD64}
|
||||||
|
|
||||||
|
HAS_ARCH_INTEL = {ARCH_I386, ARCH_AMD64}
|
||||||
|
HAS_ARCH_ARM = {ARCH_AARCH64}
|
||||||
|
|
||||||
|
|
||||||
|
def mask_immediate(arch: Set[str], immediate: int) -> int:
|
||||||
|
if arch & HAS_ARCH64:
|
||||||
|
immediate &= 0xFFFFFFFFFFFFFFFF
|
||||||
|
elif arch & HAS_ARCH32:
|
||||||
|
immediate &= 0xFFFFFFFF
|
||||||
|
return immediate
|
||||||
|
|
||||||
|
|
||||||
|
def twos_complement(arch: Set[str], immediate: int, default: Optional[int] = None) -> int:
|
||||||
|
if default is not None:
|
||||||
|
return capa.features.extractors.helpers.twos_complement(immediate, default)
|
||||||
|
elif arch & HAS_ARCH64:
|
||||||
|
return capa.features.extractors.helpers.twos_complement(immediate, 64)
|
||||||
|
elif arch & HAS_ARCH32:
|
||||||
|
return capa.features.extractors.helpers.twos_complement(immediate, 32)
|
||||||
|
return immediate
|
||||||
|
|
||||||
|
|
||||||
|
def is_address_mapped(be2: BinExport2, address: int) -> bool:
|
||||||
|
"""return True if the given address is mapped"""
|
||||||
|
sections_with_perms: Iterator[BinExport2.Section] = filter(lambda s: s.flag_r or s.flag_w or s.flag_x, be2.section)
|
||||||
|
return any(section.address <= address < section.address + section.size for section in sections_with_perms)
|
||||||
|
|
||||||
|
|
||||||
|
def is_vertex_type(vertex: BinExport2.CallGraph.Vertex, type_: BinExport2.CallGraph.Vertex.Type.ValueType) -> bool:
|
||||||
|
return vertex.HasField("type") and vertex.type == type_
|
||||||
|
|
||||||
|
|
||||||
|
# internal to `build_expression_tree`
|
||||||
|
# this is unstable: it is subject to change, so don't rely on it!
|
||||||
|
def _prune_expression_tree_empty_shifts(
|
||||||
|
be2: BinExport2,
|
||||||
|
operand: BinExport2.Operand,
|
||||||
|
expression_tree: List[List[int]],
|
||||||
|
tree_index: int,
|
||||||
|
):
|
||||||
|
expression_index = operand.expression_index[tree_index]
|
||||||
|
expression = be2.expression[expression_index]
|
||||||
|
children_tree_indexes: List[int] = expression_tree[tree_index]
|
||||||
|
|
||||||
|
if expression.type == BinExport2.Expression.OPERATOR:
|
||||||
|
if len(children_tree_indexes) == 0 and expression.symbol in ("lsl", "lsr"):
|
||||||
|
# Ghidra may emit superfluous lsl nodes with no children.
|
||||||
|
# https://github.com/mandiant/capa/pull/2340/files#r1750003919
|
||||||
|
# Which is maybe: https://github.com/NationalSecurityAgency/ghidra/issues/6821#issuecomment-2295394697
|
||||||
|
#
|
||||||
|
# Which seems to be as if the shift wasn't there (shift of #0)
|
||||||
|
# so we want to remove references to this node from any parent nodes.
|
||||||
|
for tree_node in expression_tree:
|
||||||
|
if tree_index in tree_node:
|
||||||
|
tree_node.remove(tree_index)
|
||||||
|
|
||||||
|
return
|
||||||
|
|
||||||
|
for child_tree_index in children_tree_indexes:
|
||||||
|
_prune_expression_tree_empty_shifts(be2, operand, expression_tree, child_tree_index)
|
||||||
|
|
||||||
|
|
||||||
|
# internal to `build_expression_tree`
|
||||||
|
# this is unstable: it is subject to change, so don't rely on it!
|
||||||
|
def _prune_expression_tree_empty_commas(
|
||||||
|
be2: BinExport2,
|
||||||
|
operand: BinExport2.Operand,
|
||||||
|
expression_tree: List[List[int]],
|
||||||
|
tree_index: int,
|
||||||
|
):
|
||||||
|
expression_index = operand.expression_index[tree_index]
|
||||||
|
expression = be2.expression[expression_index]
|
||||||
|
children_tree_indexes: List[int] = expression_tree[tree_index]
|
||||||
|
|
||||||
|
if expression.type == BinExport2.Expression.OPERATOR:
|
||||||
|
if len(children_tree_indexes) == 1 and expression.symbol == ",":
|
||||||
|
# Due to the above pruning of empty LSL or LSR expressions,
|
||||||
|
# the parents might need to be fixed up.
|
||||||
|
#
|
||||||
|
# Specifically, if the pruned node was part of a comma list with two children,
|
||||||
|
# now there's only a single child, which renders as an extra comma,
|
||||||
|
# so we replace references to the comma node with the immediate child.
|
||||||
|
#
|
||||||
|
# A more correct way of doing this might be to walk up the parents and do fixups,
|
||||||
|
# but I'm not quite sure how to do this yet. Just do two passes right now.
|
||||||
|
child = children_tree_indexes[0]
|
||||||
|
|
||||||
|
for tree_node in expression_tree:
|
||||||
|
tree_node.index
|
||||||
|
if tree_index in tree_node:
|
||||||
|
tree_node[tree_node.index(tree_index)] = child
|
||||||
|
|
||||||
|
return
|
||||||
|
|
||||||
|
for child_tree_index in children_tree_indexes:
|
||||||
|
_prune_expression_tree_empty_commas(be2, operand, expression_tree, child_tree_index)
|
||||||
|
|
||||||
|
|
||||||
|
# internal to `build_expression_tree`
|
||||||
|
# this is unstable: it is subject to change, so don't rely on it!
|
||||||
|
def _prune_expression_tree(
|
||||||
|
be2: BinExport2,
|
||||||
|
operand: BinExport2.Operand,
|
||||||
|
expression_tree: List[List[int]],
|
||||||
|
):
|
||||||
|
_prune_expression_tree_empty_shifts(be2, operand, expression_tree, 0)
|
||||||
|
_prune_expression_tree_empty_commas(be2, operand, expression_tree, 0)
|
||||||
|
|
||||||
|
|
||||||
|
# this is unstable: it is subject to change, so don't rely on it!
|
||||||
|
def _build_expression_tree(
|
||||||
|
be2: BinExport2,
|
||||||
|
operand: BinExport2.Operand,
|
||||||
|
) -> List[List[int]]:
|
||||||
|
# The reconstructed expression tree layout, linking parent nodes to their children.
|
||||||
|
#
|
||||||
|
# There is one list of integers for each expression in the operand.
|
||||||
|
# These integers are indexes of other expressions in the same operand,
|
||||||
|
# which are the children of that expression.
|
||||||
|
#
|
||||||
|
# So:
|
||||||
|
#
|
||||||
|
# [ [1, 3], [2], [], [4], [5], []]
|
||||||
|
#
|
||||||
|
# means the first expression has two children, at index 1 and 3,
|
||||||
|
# and the tree looks like:
|
||||||
|
#
|
||||||
|
# 0
|
||||||
|
# / \
|
||||||
|
# 1 3
|
||||||
|
# | |
|
||||||
|
# 2 4
|
||||||
|
# |
|
||||||
|
# 5
|
||||||
|
#
|
||||||
|
# Remember, these are the indices into the entries in operand.expression_index.
|
||||||
|
if len(operand.expression_index) == 0:
|
||||||
|
# Ghidra bug where empty operands (no expressions) may
|
||||||
|
# exist (see https://github.com/NationalSecurityAgency/ghidra/issues/6817)
|
||||||
|
return []
|
||||||
|
|
||||||
|
tree: List[List[int]] = []
|
||||||
|
for i, expression_index in enumerate(operand.expression_index):
|
||||||
|
children = []
|
||||||
|
|
||||||
|
# scan all subsequent expressions, looking for those that have parent_index == current.expression_index
|
||||||
|
for j, candidate_index in enumerate(operand.expression_index[i + 1 :]):
|
||||||
|
candidate = be2.expression[candidate_index]
|
||||||
|
|
||||||
|
if candidate.parent_index == expression_index:
|
||||||
|
children.append(i + j + 1)
|
||||||
|
|
||||||
|
tree.append(children)
|
||||||
|
|
||||||
|
_prune_expression_tree(be2, operand, tree)
|
||||||
|
_prune_expression_tree(be2, operand, tree)
|
||||||
|
|
||||||
|
return tree
|
||||||
|
|
||||||
|
|
||||||
|
def _fill_operand_expression_list(
|
||||||
|
be2: BinExport2,
|
||||||
|
operand: BinExport2.Operand,
|
||||||
|
expression_tree: List[List[int]],
|
||||||
|
tree_index: int,
|
||||||
|
expression_list: List[BinExport2.Expression],
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Walk the given expression tree and collect the expression nodes in-order.
|
||||||
|
"""
|
||||||
|
expression_index = operand.expression_index[tree_index]
|
||||||
|
expression = be2.expression[expression_index]
|
||||||
|
children_tree_indexes: List[int] = expression_tree[tree_index]
|
||||||
|
|
||||||
|
if expression.type == BinExport2.Expression.REGISTER:
|
||||||
|
assert len(children_tree_indexes) == 0
|
||||||
|
expression_list.append(expression)
|
||||||
|
return
|
||||||
|
|
||||||
|
elif expression.type == BinExport2.Expression.SYMBOL:
|
||||||
|
assert len(children_tree_indexes) <= 1
|
||||||
|
expression_list.append(expression)
|
||||||
|
|
||||||
|
if len(children_tree_indexes) == 0:
|
||||||
|
return
|
||||||
|
elif len(children_tree_indexes) == 1:
|
||||||
|
# like: v
|
||||||
|
# from: mov v0.D[0x1], x9
|
||||||
|
# |
|
||||||
|
# 0
|
||||||
|
# .
|
||||||
|
# |
|
||||||
|
# D
|
||||||
|
child_index = children_tree_indexes[0]
|
||||||
|
_fill_operand_expression_list(be2, operand, expression_tree, child_index, expression_list)
|
||||||
|
return
|
||||||
|
else:
|
||||||
|
raise NotImplementedError(len(children_tree_indexes))
|
||||||
|
|
||||||
|
elif expression.type == BinExport2.Expression.IMMEDIATE_INT:
|
||||||
|
assert len(children_tree_indexes) == 0
|
||||||
|
expression_list.append(expression)
|
||||||
|
return
|
||||||
|
|
||||||
|
elif expression.type == BinExport2.Expression.SIZE_PREFIX:
|
||||||
|
# like: b4
|
||||||
|
#
|
||||||
|
# We might want to use this occasionally, such as to disambiguate the
|
||||||
|
# size of MOVs into/out of memory. But I'm not sure when/where we need that yet.
|
||||||
|
#
|
||||||
|
# IDA spams this size prefix hint *everywhere*, so we can't rely on the exporter
|
||||||
|
# to provide it only when necessary.
|
||||||
|
assert len(children_tree_indexes) == 1
|
||||||
|
child_index = children_tree_indexes[0]
|
||||||
|
_fill_operand_expression_list(be2, operand, expression_tree, child_index, expression_list)
|
||||||
|
return
|
||||||
|
|
||||||
|
elif expression.type == BinExport2.Expression.OPERATOR:
|
||||||
|
if len(children_tree_indexes) == 1:
|
||||||
|
# prefix operator, like "ds:"
|
||||||
|
expression_list.append(expression)
|
||||||
|
child_index = children_tree_indexes[0]
|
||||||
|
_fill_operand_expression_list(be2, operand, expression_tree, child_index, expression_list)
|
||||||
|
return
|
||||||
|
|
||||||
|
elif len(children_tree_indexes) == 2:
|
||||||
|
# infix operator: like "+" in "ebp+10"
|
||||||
|
child_a = children_tree_indexes[0]
|
||||||
|
child_b = children_tree_indexes[1]
|
||||||
|
_fill_operand_expression_list(be2, operand, expression_tree, child_a, expression_list)
|
||||||
|
expression_list.append(expression)
|
||||||
|
_fill_operand_expression_list(be2, operand, expression_tree, child_b, expression_list)
|
||||||
|
return
|
||||||
|
|
||||||
|
elif len(children_tree_indexes) == 3:
|
||||||
|
# infix operator: like "+" in "ebp+ecx+10"
|
||||||
|
child_a = children_tree_indexes[0]
|
||||||
|
child_b = children_tree_indexes[1]
|
||||||
|
child_c = children_tree_indexes[2]
|
||||||
|
_fill_operand_expression_list(be2, operand, expression_tree, child_a, expression_list)
|
||||||
|
expression_list.append(expression)
|
||||||
|
_fill_operand_expression_list(be2, operand, expression_tree, child_b, expression_list)
|
||||||
|
expression_list.append(expression)
|
||||||
|
_fill_operand_expression_list(be2, operand, expression_tree, child_c, expression_list)
|
||||||
|
return
|
||||||
|
|
||||||
|
else:
|
||||||
|
raise NotImplementedError(len(children_tree_indexes))
|
||||||
|
|
||||||
|
elif expression.type == BinExport2.Expression.DEREFERENCE:
|
||||||
|
assert len(children_tree_indexes) == 1
|
||||||
|
expression_list.append(expression)
|
||||||
|
|
||||||
|
child_index = children_tree_indexes[0]
|
||||||
|
_fill_operand_expression_list(be2, operand, expression_tree, child_index, expression_list)
|
||||||
|
return
|
||||||
|
|
||||||
|
elif expression.type == BinExport2.Expression.IMMEDIATE_FLOAT:
|
||||||
|
raise NotImplementedError(expression.type)
|
||||||
|
|
||||||
|
else:
|
||||||
|
raise NotImplementedError(expression.type)
|
||||||
|
|
||||||
|
|
||||||
|
def get_operand_expressions(be2: BinExport2, op: BinExport2.Operand) -> List[BinExport2.Expression]:
|
||||||
|
tree = _build_expression_tree(be2, op)
|
||||||
|
|
||||||
|
expressions: List[BinExport2.Expression] = []
|
||||||
|
_fill_operand_expression_list(be2, op, tree, 0, expressions)
|
||||||
|
|
||||||
|
return expressions
|
||||||
|
|
||||||
|
|
||||||
|
def get_operand_register_expression(be2: BinExport2, operand: BinExport2.Operand) -> Optional[BinExport2.Expression]:
|
||||||
|
if len(operand.expression_index) == 1:
|
||||||
|
expression: BinExport2.Expression = be2.expression[operand.expression_index[0]]
|
||||||
|
if expression.type == BinExport2.Expression.REGISTER:
|
||||||
|
return expression
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def get_operand_immediate_expression(be2: BinExport2, operand: BinExport2.Operand) -> Optional[BinExport2.Expression]:
|
||||||
|
if len(operand.expression_index) == 1:
|
||||||
|
# - type: IMMEDIATE_INT
|
||||||
|
# immediate: 20588728364
|
||||||
|
# parent_index: 0
|
||||||
|
expression: BinExport2.Expression = be2.expression[operand.expression_index[0]]
|
||||||
|
if expression.type == BinExport2.Expression.IMMEDIATE_INT:
|
||||||
|
return expression
|
||||||
|
|
||||||
|
elif len(operand.expression_index) == 2:
|
||||||
|
# from IDA, which provides a size hint for every operand,
|
||||||
|
# we get the following pattern for immediate constants:
|
||||||
|
#
|
||||||
|
# - type: SIZE_PREFIX
|
||||||
|
# symbol: "b8"
|
||||||
|
# - type: IMMEDIATE_INT
|
||||||
|
# immediate: 20588728364
|
||||||
|
# parent_index: 0
|
||||||
|
expression0: BinExport2.Expression = be2.expression[operand.expression_index[0]]
|
||||||
|
expression1: BinExport2.Expression = be2.expression[operand.expression_index[1]]
|
||||||
|
|
||||||
|
if expression0.type == BinExport2.Expression.SIZE_PREFIX:
|
||||||
|
if expression1.type == BinExport2.Expression.IMMEDIATE_INT:
|
||||||
|
return expression1
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def get_instruction_mnemonic(be2: BinExport2, instruction: BinExport2.Instruction) -> str:
|
||||||
|
return be2.mnemonic[instruction.mnemonic_index].name.lower()
|
||||||
|
|
||||||
|
|
||||||
|
def get_instruction_operands(be2: BinExport2, instruction: BinExport2.Instruction) -> List[BinExport2.Operand]:
|
||||||
|
return [be2.operand[operand_index] for operand_index in instruction.operand_index]
|
||||||
|
|
||||||
|
|
||||||
|
def split_with_delimiters(s: str, delimiters: Tuple[str, ...]) -> Iterator[str]:
|
||||||
|
"""
|
||||||
|
Splits a string by any of the provided delimiter characters,
|
||||||
|
including the delimiters in the results.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
string: The string to split.
|
||||||
|
delimiters: A string containing the characters to use as delimiters.
|
||||||
|
"""
|
||||||
|
start = 0
|
||||||
|
for i, char in enumerate(s):
|
||||||
|
if char in delimiters:
|
||||||
|
yield s[start:i]
|
||||||
|
yield char
|
||||||
|
start = i + 1
|
||||||
|
|
||||||
|
if start < len(s):
|
||||||
|
yield s[start:]
|
||||||
|
|
||||||
|
|
||||||
|
BinExport2OperandPattern = Union[str, Tuple[str, ...]]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class BinExport2InstructionPattern:
|
||||||
|
"""
|
||||||
|
This describes a way to match disassembled instructions, with mnemonics and operands.
|
||||||
|
|
||||||
|
You can specify constraints on the instruction, via:
|
||||||
|
- the mnemonics, like "mov",
|
||||||
|
- number of operands, and
|
||||||
|
- format of each operand, "[reg, reg, #int]".
|
||||||
|
|
||||||
|
During matching, you can also capture a single element, to see its concrete value.
|
||||||
|
For example, given the pattern:
|
||||||
|
|
||||||
|
mov reg0, #int0 ; capture int0
|
||||||
|
|
||||||
|
and the instruction:
|
||||||
|
|
||||||
|
mov eax, 1
|
||||||
|
|
||||||
|
Then the capture will contain the immediate integer 1.
|
||||||
|
|
||||||
|
This matcher uses the BinExport2 data layout under the hood.
|
||||||
|
"""
|
||||||
|
|
||||||
|
mnemonics: Tuple[str, ...]
|
||||||
|
operands: Tuple[Union[str, BinExport2OperandPattern], ...]
|
||||||
|
capture: Optional[str]
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_str(cls, query: str):
|
||||||
|
"""
|
||||||
|
Parse a pattern string into a Pattern instance.
|
||||||
|
The supported syntax is like this:
|
||||||
|
|
||||||
|
br reg
|
||||||
|
br reg ; capture reg
|
||||||
|
br reg(stack) ; capture reg
|
||||||
|
br reg(not-stack) ; capture reg
|
||||||
|
mov reg0, reg1 ; capture reg0
|
||||||
|
adrp reg, #int ; capture #int
|
||||||
|
add reg, reg, #int ; capture #int
|
||||||
|
ldr reg0, [reg1] ; capture reg1
|
||||||
|
ldr|str reg, [reg, #int] ; capture #int
|
||||||
|
ldr|str reg, [reg(stack), #int] ; capture #int
|
||||||
|
ldr|str reg, [reg(not-stack), #int] ; capture #int
|
||||||
|
ldr|str reg, [reg, #int]! ; capture #int
|
||||||
|
ldr|str reg, [reg], #int ; capture #int
|
||||||
|
ldp|stp reg, reg, [reg, #int] ; capture #int
|
||||||
|
ldp|stp reg, reg, [reg, #int]! ; capture #int
|
||||||
|
ldp|stp reg, reg, [reg], #int ; capture #int
|
||||||
|
"""
|
||||||
|
#
|
||||||
|
# The implementation of the parser here is obviously ugly.
|
||||||
|
# Its handwritten and probably fragile. But since we don't
|
||||||
|
# expect this to be widely used, its probably ok.
|
||||||
|
# Don't hesitate to rewrite this if it becomes more important.
|
||||||
|
#
|
||||||
|
# Note that this doesn't have to be very performant.
|
||||||
|
# We expect these patterns to be parsed once upfront and then reused
|
||||||
|
# (globally at the module level?) rather than within any loop.
|
||||||
|
#
|
||||||
|
|
||||||
|
pattern, _, comment = query.strip().partition(";")
|
||||||
|
|
||||||
|
# we don't support fs: yet
|
||||||
|
assert ":" not in pattern
|
||||||
|
|
||||||
|
# from "capture #int" to "#int"
|
||||||
|
if comment:
|
||||||
|
comment = comment.strip()
|
||||||
|
assert comment.startswith("capture ")
|
||||||
|
capture = comment[len("capture ") :]
|
||||||
|
else:
|
||||||
|
capture = None
|
||||||
|
|
||||||
|
# from "ldr|str ..." to ["ldr", "str"]
|
||||||
|
pattern = pattern.strip()
|
||||||
|
mnemonic, _, rest = pattern.partition(" ")
|
||||||
|
mnemonics = mnemonic.split("|")
|
||||||
|
|
||||||
|
operands: List[Union[str, Tuple[str, ...]]] = []
|
||||||
|
while rest:
|
||||||
|
rest = rest.strip()
|
||||||
|
if not rest.startswith("["):
|
||||||
|
# If its not a dereference, which looks like `[op, op, op, ...]`,
|
||||||
|
# then its a simple operand, which we can split by the next comma.
|
||||||
|
operand, _, rest = rest.partition(", ")
|
||||||
|
rest = rest.strip()
|
||||||
|
operands.append(operand)
|
||||||
|
|
||||||
|
else:
|
||||||
|
# This looks like a dereference, something like `[op, op, op, ...]`.
|
||||||
|
# Since these can't be nested, look for the next ] and then parse backwards.
|
||||||
|
deref_end = rest.index("]")
|
||||||
|
try:
|
||||||
|
deref_end = rest.index(", ", deref_end)
|
||||||
|
deref_end += len(", ")
|
||||||
|
except ValueError:
|
||||||
|
deref = rest
|
||||||
|
rest = ""
|
||||||
|
else:
|
||||||
|
deref = rest[:deref_end]
|
||||||
|
rest = rest[deref_end:]
|
||||||
|
rest = rest.strip()
|
||||||
|
deref = deref.rstrip(" ")
|
||||||
|
deref = deref.rstrip(",")
|
||||||
|
|
||||||
|
# like: [reg, #int]!
|
||||||
|
has_postindex_writeback = deref.endswith("!")
|
||||||
|
|
||||||
|
deref = deref.rstrip("!")
|
||||||
|
deref = deref.rstrip("]")
|
||||||
|
deref = deref.lstrip("[")
|
||||||
|
|
||||||
|
parts = tuple(split_with_delimiters(deref, (",", "+", "*")))
|
||||||
|
parts = tuple(s.strip() for s in parts)
|
||||||
|
|
||||||
|
# emit operands in this order to match
|
||||||
|
# how BinExport2 expressions are flatted
|
||||||
|
# by get_operand_expressions
|
||||||
|
if has_postindex_writeback:
|
||||||
|
operands.append(("!", "[") + parts)
|
||||||
|
else:
|
||||||
|
operands.append(("[",) + parts)
|
||||||
|
|
||||||
|
for operand in operands: # type: ignore
|
||||||
|
# Try to ensure we've parsed the operands correctly.
|
||||||
|
# This is just sanity checking.
|
||||||
|
for o in (operand,) if isinstance(operand, str) else operand:
|
||||||
|
# operands can look like:
|
||||||
|
# - reg
|
||||||
|
# - reg0
|
||||||
|
# - reg(stack)
|
||||||
|
# - reg0(stack)
|
||||||
|
# - reg(not-stack)
|
||||||
|
# - reg0(not-stack)
|
||||||
|
# - #int
|
||||||
|
# - #int0
|
||||||
|
# and a limited set of supported operators.
|
||||||
|
# use an inline regex so that its easy to read. not perf critical.
|
||||||
|
assert re.match(r"^(reg|#int)[0-9]?(\(stack\)|\(not-stack\))?$", o) or o in ("[", ",", "!", "+", "*")
|
||||||
|
|
||||||
|
return cls(tuple(mnemonics), tuple(operands), capture)
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class MatchResult:
|
||||||
|
operand_index: int
|
||||||
|
expression_index: int
|
||||||
|
expression: BinExport2.Expression
|
||||||
|
|
||||||
|
def match(
|
||||||
|
self, mnemonic: str, operand_expressions: List[List[BinExport2.Expression]]
|
||||||
|
) -> Optional["BinExport2InstructionPattern.MatchResult"]:
|
||||||
|
"""
|
||||||
|
Match the given BinExport2 data against this pattern.
|
||||||
|
|
||||||
|
The BinExport2 expression tree must have been flattened, such as with
|
||||||
|
capa.features.extractors.binexport2.helpers.get_operand_expressions.
|
||||||
|
|
||||||
|
If there's a match, the captured Expression instance is returned.
|
||||||
|
Otherwise, you get None back.
|
||||||
|
"""
|
||||||
|
if mnemonic not in self.mnemonics:
|
||||||
|
return None
|
||||||
|
|
||||||
|
if len(self.operands) != len(operand_expressions):
|
||||||
|
return None
|
||||||
|
|
||||||
|
captured = None
|
||||||
|
|
||||||
|
for operand_index, found_expressions in enumerate(operand_expressions):
|
||||||
|
wanted_expressions = self.operands[operand_index]
|
||||||
|
|
||||||
|
# from `"reg"` to `("reg", )`
|
||||||
|
if isinstance(wanted_expressions, str):
|
||||||
|
wanted_expressions = (wanted_expressions,)
|
||||||
|
assert isinstance(wanted_expressions, tuple)
|
||||||
|
|
||||||
|
if len(wanted_expressions) != len(found_expressions):
|
||||||
|
return None
|
||||||
|
|
||||||
|
for expression_index, (wanted_expression, found_expression) in enumerate(
|
||||||
|
zip(wanted_expressions, found_expressions)
|
||||||
|
):
|
||||||
|
if wanted_expression.startswith("reg"):
|
||||||
|
if found_expression.type != BinExport2.Expression.REGISTER:
|
||||||
|
return None
|
||||||
|
|
||||||
|
if wanted_expression.endswith(")"):
|
||||||
|
if wanted_expression.endswith("(not-stack)"):
|
||||||
|
# intel 64: rsp, esp, sp,
|
||||||
|
# intel 32: ebp, ebp, bp
|
||||||
|
# arm: sp
|
||||||
|
register_name = found_expression.symbol.lower()
|
||||||
|
if register_name in ("rsp", "esp", "sp", "rbp", "ebp", "bp"):
|
||||||
|
return None
|
||||||
|
|
||||||
|
elif wanted_expression.endswith("(stack)"):
|
||||||
|
register_name = found_expression.symbol.lower()
|
||||||
|
if register_name not in ("rsp", "esp", "sp", "rbp", "ebp", "bp"):
|
||||||
|
return None
|
||||||
|
|
||||||
|
else:
|
||||||
|
raise ValueError("unexpected expression suffix", wanted_expression)
|
||||||
|
|
||||||
|
if self.capture == wanted_expression:
|
||||||
|
captured = BinExport2InstructionPattern.MatchResult(
|
||||||
|
operand_index, expression_index, found_expression
|
||||||
|
)
|
||||||
|
|
||||||
|
elif wanted_expression.startswith("#int"):
|
||||||
|
if found_expression.type != BinExport2.Expression.IMMEDIATE_INT:
|
||||||
|
return None
|
||||||
|
|
||||||
|
if self.capture == wanted_expression:
|
||||||
|
captured = BinExport2InstructionPattern.MatchResult(
|
||||||
|
operand_index, expression_index, found_expression
|
||||||
|
)
|
||||||
|
|
||||||
|
elif wanted_expression == "[":
|
||||||
|
if found_expression.type != BinExport2.Expression.DEREFERENCE:
|
||||||
|
return None
|
||||||
|
|
||||||
|
elif wanted_expression in (",", "!", "+", "*"):
|
||||||
|
if found_expression.type != BinExport2.Expression.OPERATOR:
|
||||||
|
return None
|
||||||
|
|
||||||
|
if found_expression.symbol != wanted_expression:
|
||||||
|
return None
|
||||||
|
|
||||||
|
else:
|
||||||
|
raise ValueError(found_expression)
|
||||||
|
|
||||||
|
if captured:
|
||||||
|
return captured
|
||||||
|
else:
|
||||||
|
# There were no captures, so
|
||||||
|
# return arbitrary non-None expression
|
||||||
|
return BinExport2InstructionPattern.MatchResult(operand_index, expression_index, found_expression)
|
||||||
|
|
||||||
|
|
||||||
|
class BinExport2InstructionPatternMatcher:
|
||||||
|
"""Index and match a collection of instruction patterns."""
|
||||||
|
|
||||||
|
def __init__(self, queries: List[BinExport2InstructionPattern]):
|
||||||
|
self.queries = queries
|
||||||
|
# shard the patterns by (mnemonic, #operands)
|
||||||
|
self._index: Dict[Tuple[str, int], List[BinExport2InstructionPattern]] = defaultdict(list)
|
||||||
|
|
||||||
|
for query in queries:
|
||||||
|
for mnemonic in query.mnemonics:
|
||||||
|
self._index[(mnemonic.lower(), len(query.operands))].append(query)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_str(cls, patterns: str):
|
||||||
|
return cls(
|
||||||
|
[
|
||||||
|
BinExport2InstructionPattern.from_str(line)
|
||||||
|
for line in filter(
|
||||||
|
lambda line: not line.startswith("#"), (line.strip() for line in patterns.split("\n"))
|
||||||
|
)
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
def match(
|
||||||
|
self, mnemonic: str, operand_expressions: List[List[BinExport2.Expression]]
|
||||||
|
) -> Optional[BinExport2InstructionPattern.MatchResult]:
|
||||||
|
queries = self._index.get((mnemonic.lower(), len(operand_expressions)), [])
|
||||||
|
for query in queries:
|
||||||
|
captured = query.match(mnemonic.lower(), operand_expressions)
|
||||||
|
if captured:
|
||||||
|
return captured
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
def match_with_be2(
|
||||||
|
self, be2: BinExport2, instruction_index: int
|
||||||
|
) -> Optional[BinExport2InstructionPattern.MatchResult]:
|
||||||
|
instruction: BinExport2.Instruction = be2.instruction[instruction_index]
|
||||||
|
mnemonic: str = get_instruction_mnemonic(be2, instruction)
|
||||||
|
|
||||||
|
if (mnemonic.lower(), len(instruction.operand_index)) not in self._index:
|
||||||
|
# verify that we might have a hit before we realize the operand expression list
|
||||||
|
return None
|
||||||
|
|
||||||
|
operands = []
|
||||||
|
for operand_index in instruction.operand_index:
|
||||||
|
operands.append(get_operand_expressions(be2, be2.operand[operand_index]))
|
||||||
|
|
||||||
|
return self.match(mnemonic, operands)
|
||||||
254
capa/features/extractors/binexport2/insn.py
Normal file
254
capa/features/extractors/binexport2/insn.py
Normal file
@@ -0,0 +1,254 @@
|
|||||||
|
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
import logging
|
||||||
|
from typing import List, Tuple, Iterator
|
||||||
|
|
||||||
|
import capa.features.extractors.helpers
|
||||||
|
import capa.features.extractors.strings
|
||||||
|
import capa.features.extractors.binexport2.helpers
|
||||||
|
import capa.features.extractors.binexport2.arch.arm.insn
|
||||||
|
import capa.features.extractors.binexport2.arch.intel.insn
|
||||||
|
from capa.features.insn import API, Mnemonic
|
||||||
|
from capa.features.common import Bytes, String, Feature, Characteristic
|
||||||
|
from capa.features.address import Address, AbsoluteVirtualAddress
|
||||||
|
from capa.features.extractors.binexport2 import (
|
||||||
|
AddressSpace,
|
||||||
|
AnalysisContext,
|
||||||
|
BinExport2Index,
|
||||||
|
FunctionContext,
|
||||||
|
ReadMemoryError,
|
||||||
|
BinExport2Analysis,
|
||||||
|
InstructionContext,
|
||||||
|
)
|
||||||
|
from capa.features.extractors.base_extractor import BBHandle, InsnHandle, FunctionHandle
|
||||||
|
from capa.features.extractors.binexport2.helpers import HAS_ARCH_ARM, HAS_ARCH_INTEL
|
||||||
|
from capa.features.extractors.binexport2.binexport2_pb2 import BinExport2
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_insn_api_features(fh: FunctionHandle, _bbh: BBHandle, ih: InsnHandle) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
fhi: FunctionContext = fh.inner
|
||||||
|
ii: InstructionContext = ih.inner
|
||||||
|
|
||||||
|
be2: BinExport2 = fhi.ctx.be2
|
||||||
|
be2_index: BinExport2Index = fhi.ctx.idx
|
||||||
|
be2_analysis: BinExport2Analysis = fhi.ctx.analysis
|
||||||
|
insn: BinExport2.Instruction = be2.instruction[ii.instruction_index]
|
||||||
|
|
||||||
|
for addr in insn.call_target:
|
||||||
|
addr = be2_analysis.thunks.get(addr, addr)
|
||||||
|
|
||||||
|
if addr not in be2_index.vertex_index_by_address:
|
||||||
|
# disassembler did not define function at address
|
||||||
|
logger.debug("0x%x is not a vertex", addr)
|
||||||
|
continue
|
||||||
|
|
||||||
|
vertex_idx: int = be2_index.vertex_index_by_address[addr]
|
||||||
|
vertex: BinExport2.CallGraph.Vertex = be2.call_graph.vertex[vertex_idx]
|
||||||
|
|
||||||
|
if not capa.features.extractors.binexport2.helpers.is_vertex_type(
|
||||||
|
vertex, BinExport2.CallGraph.Vertex.Type.IMPORTED
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
|
||||||
|
if not vertex.HasField("mangled_name"):
|
||||||
|
logger.debug("vertex %d does not have mangled_name", vertex_idx)
|
||||||
|
continue
|
||||||
|
|
||||||
|
api_name: str = vertex.mangled_name
|
||||||
|
for name in capa.features.extractors.helpers.generate_symbols("", api_name):
|
||||||
|
yield API(name), ih.address
|
||||||
|
|
||||||
|
|
||||||
|
def extract_insn_number_features(
|
||||||
|
fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle
|
||||||
|
) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
fhi: FunctionContext = fh.inner
|
||||||
|
|
||||||
|
if fhi.arch & HAS_ARCH_INTEL:
|
||||||
|
yield from capa.features.extractors.binexport2.arch.intel.insn.extract_insn_number_features(fh, bbh, ih)
|
||||||
|
elif fhi.arch & HAS_ARCH_ARM:
|
||||||
|
yield from capa.features.extractors.binexport2.arch.arm.insn.extract_insn_number_features(fh, bbh, ih)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_insn_bytes_features(fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
fhi: FunctionContext = fh.inner
|
||||||
|
ii: InstructionContext = ih.inner
|
||||||
|
|
||||||
|
ctx: AnalysisContext = fhi.ctx
|
||||||
|
be2: BinExport2 = ctx.be2
|
||||||
|
idx: BinExport2Index = ctx.idx
|
||||||
|
address_space: AddressSpace = ctx.address_space
|
||||||
|
|
||||||
|
instruction_index: int = ii.instruction_index
|
||||||
|
|
||||||
|
if instruction_index in idx.string_reference_index_by_source_instruction_index:
|
||||||
|
# disassembler already identified string reference from instruction
|
||||||
|
return
|
||||||
|
|
||||||
|
reference_addresses: List[int] = []
|
||||||
|
|
||||||
|
if instruction_index in idx.data_reference_index_by_source_instruction_index:
|
||||||
|
for data_reference_index in idx.data_reference_index_by_source_instruction_index[instruction_index]:
|
||||||
|
data_reference: BinExport2.DataReference = be2.data_reference[data_reference_index]
|
||||||
|
data_reference_address: int = data_reference.address
|
||||||
|
|
||||||
|
if data_reference_address in idx.insn_address_by_index:
|
||||||
|
# appears to be code
|
||||||
|
continue
|
||||||
|
|
||||||
|
reference_addresses.append(data_reference_address)
|
||||||
|
|
||||||
|
for reference_address in reference_addresses:
|
||||||
|
try:
|
||||||
|
# if at end of segment then there might be an overrun here.
|
||||||
|
buf: bytes = address_space.read_memory(reference_address, 0x100)
|
||||||
|
except ReadMemoryError:
|
||||||
|
logger.debug("failed to read memory: 0x%x", reference_address)
|
||||||
|
continue
|
||||||
|
|
||||||
|
if capa.features.extractors.helpers.all_zeros(buf):
|
||||||
|
continue
|
||||||
|
|
||||||
|
is_string: bool = False
|
||||||
|
|
||||||
|
# note: we *always* break after the first iteration
|
||||||
|
for s in capa.features.extractors.strings.extract_ascii_strings(buf):
|
||||||
|
if s.offset != 0:
|
||||||
|
break
|
||||||
|
|
||||||
|
yield String(s.s), ih.address
|
||||||
|
is_string = True
|
||||||
|
break
|
||||||
|
|
||||||
|
# note: we *always* break after the first iteration
|
||||||
|
for s in capa.features.extractors.strings.extract_unicode_strings(buf):
|
||||||
|
if s.offset != 0:
|
||||||
|
break
|
||||||
|
|
||||||
|
yield String(s.s), ih.address
|
||||||
|
is_string = True
|
||||||
|
break
|
||||||
|
|
||||||
|
if not is_string:
|
||||||
|
yield Bytes(buf), ih.address
|
||||||
|
|
||||||
|
|
||||||
|
def extract_insn_string_features(
|
||||||
|
fh: FunctionHandle, _bbh: BBHandle, ih: InsnHandle
|
||||||
|
) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
fhi: FunctionContext = fh.inner
|
||||||
|
ii: InstructionContext = ih.inner
|
||||||
|
|
||||||
|
be2: BinExport2 = fhi.ctx.be2
|
||||||
|
idx: BinExport2Index = fhi.ctx.idx
|
||||||
|
|
||||||
|
instruction_index: int = ii.instruction_index
|
||||||
|
|
||||||
|
if instruction_index in idx.string_reference_index_by_source_instruction_index:
|
||||||
|
for string_reference_index in idx.string_reference_index_by_source_instruction_index[instruction_index]:
|
||||||
|
string_reference: BinExport2.Reference = be2.string_reference[string_reference_index]
|
||||||
|
string_index: int = string_reference.string_table_index
|
||||||
|
string: str = be2.string_table[string_index]
|
||||||
|
yield String(string), ih.address
|
||||||
|
|
||||||
|
|
||||||
|
def extract_insn_offset_features(
|
||||||
|
fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle
|
||||||
|
) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
fhi: FunctionContext = fh.inner
|
||||||
|
|
||||||
|
if fhi.arch & HAS_ARCH_INTEL:
|
||||||
|
yield from capa.features.extractors.binexport2.arch.intel.insn.extract_insn_offset_features(fh, bbh, ih)
|
||||||
|
elif fhi.arch & HAS_ARCH_ARM:
|
||||||
|
yield from capa.features.extractors.binexport2.arch.arm.insn.extract_insn_offset_features(fh, bbh, ih)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_insn_nzxor_characteristic_features(
|
||||||
|
fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle
|
||||||
|
) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
fhi: FunctionContext = fh.inner
|
||||||
|
|
||||||
|
if fhi.arch & HAS_ARCH_INTEL:
|
||||||
|
yield from capa.features.extractors.binexport2.arch.intel.insn.extract_insn_nzxor_characteristic_features(
|
||||||
|
fh, bbh, ih
|
||||||
|
)
|
||||||
|
elif fhi.arch & HAS_ARCH_ARM:
|
||||||
|
yield from capa.features.extractors.binexport2.arch.arm.insn.extract_insn_nzxor_characteristic_features(
|
||||||
|
fh, bbh, ih
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_insn_mnemonic_features(
|
||||||
|
fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle
|
||||||
|
) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
fhi: FunctionContext = fh.inner
|
||||||
|
ii: InstructionContext = ih.inner
|
||||||
|
|
||||||
|
be2: BinExport2 = fhi.ctx.be2
|
||||||
|
|
||||||
|
instruction: BinExport2.Instruction = be2.instruction[ii.instruction_index]
|
||||||
|
mnemonic: BinExport2.Mnemonic = be2.mnemonic[instruction.mnemonic_index]
|
||||||
|
mnemonic_name: str = mnemonic.name.lower()
|
||||||
|
yield Mnemonic(mnemonic_name), ih.address
|
||||||
|
|
||||||
|
|
||||||
|
def extract_function_calls_from(fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
"""extract functions calls from features
|
||||||
|
|
||||||
|
most relevant at the function scope;
|
||||||
|
however, its most efficient to extract at the instruction scope.
|
||||||
|
"""
|
||||||
|
fhi: FunctionContext = fh.inner
|
||||||
|
ii: InstructionContext = ih.inner
|
||||||
|
|
||||||
|
be2: BinExport2 = fhi.ctx.be2
|
||||||
|
|
||||||
|
instruction: BinExport2.Instruction = be2.instruction[ii.instruction_index]
|
||||||
|
for call_target_address in instruction.call_target:
|
||||||
|
addr: AbsoluteVirtualAddress = AbsoluteVirtualAddress(call_target_address)
|
||||||
|
yield Characteristic("calls from"), addr
|
||||||
|
|
||||||
|
if fh.address == addr:
|
||||||
|
yield Characteristic("recursive call"), addr
|
||||||
|
|
||||||
|
|
||||||
|
def extract_function_indirect_call_characteristic_features(
|
||||||
|
fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle
|
||||||
|
) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
fhi: FunctionContext = fh.inner
|
||||||
|
|
||||||
|
if fhi.arch & HAS_ARCH_INTEL:
|
||||||
|
yield from capa.features.extractors.binexport2.arch.intel.insn.extract_function_indirect_call_characteristic_features(
|
||||||
|
fh, bbh, ih
|
||||||
|
)
|
||||||
|
elif fhi.arch & HAS_ARCH_ARM:
|
||||||
|
yield from capa.features.extractors.binexport2.arch.arm.insn.extract_function_indirect_call_characteristic_features(
|
||||||
|
fh, bbh, ih
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_features(f: FunctionHandle, bbh: BBHandle, insn: InsnHandle) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
"""extract instruction features"""
|
||||||
|
for inst_handler in INSTRUCTION_HANDLERS:
|
||||||
|
for feature, ea in inst_handler(f, bbh, insn):
|
||||||
|
yield feature, ea
|
||||||
|
|
||||||
|
|
||||||
|
INSTRUCTION_HANDLERS = (
|
||||||
|
extract_insn_api_features,
|
||||||
|
extract_insn_number_features,
|
||||||
|
extract_insn_bytes_features,
|
||||||
|
extract_insn_string_features,
|
||||||
|
extract_insn_offset_features,
|
||||||
|
extract_insn_nzxor_characteristic_features,
|
||||||
|
extract_insn_mnemonic_features,
|
||||||
|
extract_function_calls_from,
|
||||||
|
extract_function_indirect_call_characteristic_features,
|
||||||
|
)
|
||||||
@@ -7,17 +7,15 @@
|
|||||||
# See the License for the specific language governing permissions and limitations under the License.
|
# See the License for the specific language governing permissions and limitations under the License.
|
||||||
|
|
||||||
import string
|
import string
|
||||||
import struct
|
|
||||||
from typing import Tuple, Iterator
|
from typing import Tuple, Iterator
|
||||||
|
|
||||||
from binaryninja import Function, Settings
|
from binaryninja import Function
|
||||||
from binaryninja import BasicBlock as BinjaBasicBlock
|
from binaryninja import BasicBlock as BinjaBasicBlock
|
||||||
from binaryninja import (
|
from binaryninja import (
|
||||||
BinaryView,
|
BinaryView,
|
||||||
SymbolType,
|
SymbolType,
|
||||||
RegisterValueType,
|
RegisterValueType,
|
||||||
VariableSourceType,
|
VariableSourceType,
|
||||||
MediumLevelILSetVar,
|
|
||||||
MediumLevelILOperation,
|
MediumLevelILOperation,
|
||||||
MediumLevelILBasicBlock,
|
MediumLevelILBasicBlock,
|
||||||
MediumLevelILInstruction,
|
MediumLevelILInstruction,
|
||||||
@@ -29,11 +27,6 @@ from capa.features.basicblock import BasicBlock
|
|||||||
from capa.features.extractors.helpers import MIN_STACKSTRING_LEN
|
from capa.features.extractors.helpers import MIN_STACKSTRING_LEN
|
||||||
from capa.features.extractors.base_extractor import BBHandle, FunctionHandle
|
from capa.features.extractors.base_extractor import BBHandle, FunctionHandle
|
||||||
|
|
||||||
use_const_outline: bool = False
|
|
||||||
settings: Settings = Settings()
|
|
||||||
if settings.contains("analysis.outlining.builtins") and settings.get_bool("analysis.outlining.builtins"):
|
|
||||||
use_const_outline = True
|
|
||||||
|
|
||||||
|
|
||||||
def get_printable_len_ascii(s: bytes) -> int:
|
def get_printable_len_ascii(s: bytes) -> int:
|
||||||
"""Return string length if all operand bytes are ascii or utf16-le printable"""
|
"""Return string length if all operand bytes are ascii or utf16-le printable"""
|
||||||
@@ -65,7 +58,7 @@ def get_stack_string_len(f: Function, il: MediumLevelILInstruction) -> int:
|
|||||||
|
|
||||||
addr = target.value.value
|
addr = target.value.value
|
||||||
sym = bv.get_symbol_at(addr)
|
sym = bv.get_symbol_at(addr)
|
||||||
if not sym or sym.type != SymbolType.LibraryFunctionSymbol:
|
if not sym or sym.type not in [SymbolType.LibraryFunctionSymbol, SymbolType.SymbolicFunctionSymbol]:
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
if sym.name not in ["__builtin_strncpy", "__builtin_strcpy", "__builtin_wcscpy"]:
|
if sym.name not in ["__builtin_strncpy", "__builtin_strcpy", "__builtin_wcscpy"]:
|
||||||
@@ -91,52 +84,6 @@ def get_stack_string_len(f: Function, il: MediumLevelILInstruction) -> int:
|
|||||||
return max(get_printable_len_ascii(bytes(s)), get_printable_len_wide(bytes(s)))
|
return max(get_printable_len_ascii(bytes(s)), get_printable_len_wide(bytes(s)))
|
||||||
|
|
||||||
|
|
||||||
def get_printable_len(il: MediumLevelILSetVar) -> int:
|
|
||||||
"""Return string length if all operand bytes are ascii or utf16-le printable"""
|
|
||||||
width = il.dest.type.width
|
|
||||||
value = il.src.value.value
|
|
||||||
|
|
||||||
if width == 1:
|
|
||||||
chars = struct.pack("<B", value & 0xFF)
|
|
||||||
elif width == 2:
|
|
||||||
chars = struct.pack("<H", value & 0xFFFF)
|
|
||||||
elif width == 4:
|
|
||||||
chars = struct.pack("<I", value & 0xFFFFFFFF)
|
|
||||||
elif width == 8:
|
|
||||||
chars = struct.pack("<Q", value & 0xFFFFFFFFFFFFFFFF)
|
|
||||||
else:
|
|
||||||
return 0
|
|
||||||
|
|
||||||
def is_printable_ascii(chars_: bytes):
|
|
||||||
return all(c < 127 and chr(c) in string.printable for c in chars_)
|
|
||||||
|
|
||||||
def is_printable_utf16le(chars_: bytes):
|
|
||||||
if all(c == 0x00 for c in chars_[1::2]):
|
|
||||||
return is_printable_ascii(chars_[::2])
|
|
||||||
|
|
||||||
if is_printable_ascii(chars):
|
|
||||||
return width
|
|
||||||
|
|
||||||
if is_printable_utf16le(chars):
|
|
||||||
return width // 2
|
|
||||||
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
def is_mov_imm_to_stack(il: MediumLevelILInstruction) -> bool:
|
|
||||||
"""verify instruction moves immediate onto stack"""
|
|
||||||
if il.operation != MediumLevelILOperation.MLIL_SET_VAR:
|
|
||||||
return False
|
|
||||||
|
|
||||||
if il.src.operation != MediumLevelILOperation.MLIL_CONST:
|
|
||||||
return False
|
|
||||||
|
|
||||||
if il.dest.source_type != VariableSourceType.StackVariableSourceType:
|
|
||||||
return False
|
|
||||||
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
def bb_contains_stackstring(f: Function, bb: MediumLevelILBasicBlock) -> bool:
|
def bb_contains_stackstring(f: Function, bb: MediumLevelILBasicBlock) -> bool:
|
||||||
"""check basic block for stackstring indicators
|
"""check basic block for stackstring indicators
|
||||||
|
|
||||||
@@ -144,14 +91,10 @@ def bb_contains_stackstring(f: Function, bb: MediumLevelILBasicBlock) -> bool:
|
|||||||
"""
|
"""
|
||||||
count = 0
|
count = 0
|
||||||
for il in bb:
|
for il in bb:
|
||||||
if use_const_outline:
|
|
||||||
count += get_stack_string_len(f, il)
|
count += get_stack_string_len(f, il)
|
||||||
else:
|
|
||||||
if is_mov_imm_to_stack(il):
|
|
||||||
count += get_printable_len(il)
|
|
||||||
|
|
||||||
if count > MIN_STACKSTRING_LEN:
|
if count > MIN_STACKSTRING_LEN:
|
||||||
return True
|
return True
|
||||||
|
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -17,12 +17,18 @@ import capa.features.extractors.binja.function
|
|||||||
import capa.features.extractors.binja.basicblock
|
import capa.features.extractors.binja.basicblock
|
||||||
from capa.features.common import Feature
|
from capa.features.common import Feature
|
||||||
from capa.features.address import Address, AbsoluteVirtualAddress
|
from capa.features.address import Address, AbsoluteVirtualAddress
|
||||||
from capa.features.extractors.base_extractor import BBHandle, InsnHandle, FunctionHandle, FeatureExtractor
|
from capa.features.extractors.base_extractor import (
|
||||||
|
BBHandle,
|
||||||
|
InsnHandle,
|
||||||
|
SampleHashes,
|
||||||
|
FunctionHandle,
|
||||||
|
StaticFeatureExtractor,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class BinjaFeatureExtractor(FeatureExtractor):
|
class BinjaFeatureExtractor(StaticFeatureExtractor):
|
||||||
def __init__(self, bv: binja.BinaryView):
|
def __init__(self, bv: binja.BinaryView):
|
||||||
super().__init__()
|
super().__init__(hashes=SampleHashes.from_bytes(bv.file.raw.read(0, bv.file.raw.length)))
|
||||||
self.bv = bv
|
self.bv = bv
|
||||||
self.global_features: List[Tuple[Feature, Address]] = []
|
self.global_features: List[Tuple[Feature, Address]] = []
|
||||||
self.global_features.extend(capa.features.extractors.binja.file.extract_file_format(self.bv))
|
self.global_features.extend(capa.features.extractors.binja.file.extract_file_format(self.bv))
|
||||||
|
|||||||
@@ -5,8 +5,6 @@
|
|||||||
# Unless required by applicable law or agreed to in writing, software distributed under the License
|
# 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.
|
# 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.
|
# See the License for the specific language governing permissions and limitations under the License.
|
||||||
|
|
||||||
import struct
|
|
||||||
from typing import Tuple, Iterator
|
from typing import Tuple, Iterator
|
||||||
|
|
||||||
from binaryninja import Segment, BinaryView, SymbolType, SymbolBinding
|
from binaryninja import Segment, BinaryView, SymbolType, SymbolBinding
|
||||||
@@ -20,64 +18,37 @@ from capa.features.address import NO_ADDRESS, Address, FileOffsetAddress, Absolu
|
|||||||
from capa.features.extractors.binja.helpers import read_c_string, unmangle_c_name
|
from capa.features.extractors.binja.helpers import read_c_string, unmangle_c_name
|
||||||
|
|
||||||
|
|
||||||
def check_segment_for_pe(bv: BinaryView, seg: Segment) -> Iterator[Tuple[int, int]]:
|
def check_segment_for_pe(bv: BinaryView, seg: Segment) -> Iterator[Tuple[Feature, Address]]:
|
||||||
"""check segment for embedded PE
|
"""check segment for embedded PE"""
|
||||||
|
start = 0
|
||||||
adapted for binja from:
|
if bv.view_type == "PE" and seg.start == bv.start:
|
||||||
https://github.com/vivisect/vivisect/blob/7be4037b1cecc4551b397f840405a1fc606f9b53/PE/carve.py#L19
|
# If this is the first segment of the binary, skip the first bytes.
|
||||||
"""
|
# Otherwise, there will always be a matched PE at the start of the binaryview.
|
||||||
mz_xor = [
|
|
||||||
(
|
|
||||||
capa.features.extractors.helpers.xor_static(b"MZ", i),
|
|
||||||
capa.features.extractors.helpers.xor_static(b"PE", i),
|
|
||||||
i,
|
|
||||||
)
|
|
||||||
for i in range(256)
|
|
||||||
]
|
|
||||||
|
|
||||||
todo = []
|
|
||||||
# If this is the first segment of the binary, skip the first bytes. Otherwise, there will always be a matched
|
|
||||||
# PE at the start of the binaryview.
|
|
||||||
start = seg.start
|
|
||||||
if bv.view_type == "PE" and start == bv.start:
|
|
||||||
start += 1
|
start += 1
|
||||||
|
|
||||||
for mzx, pex, i in mz_xor:
|
buf = bv.read(seg.start, seg.length)
|
||||||
for off, _ in bv.find_all_data(start, seg.end, mzx):
|
|
||||||
todo.append((off, mzx, pex, i))
|
|
||||||
|
|
||||||
while len(todo):
|
for offset, _ in capa.features.extractors.helpers.carve_pe(buf, start):
|
||||||
off, mzx, pex, i = todo.pop()
|
yield Characteristic("embedded pe"), FileOffsetAddress(seg.start + offset)
|
||||||
|
|
||||||
# The MZ header has one field we will check e_lfanew is at 0x3c
|
|
||||||
e_lfanew = off + 0x3C
|
|
||||||
|
|
||||||
if seg.end < (e_lfanew + 4):
|
|
||||||
continue
|
|
||||||
|
|
||||||
newoff = struct.unpack("<I", capa.features.extractors.helpers.xor_static(bv.read(e_lfanew, 4), i))[0]
|
|
||||||
|
|
||||||
peoff = off + newoff
|
|
||||||
if seg.end < (peoff + 2):
|
|
||||||
continue
|
|
||||||
|
|
||||||
if bv.read(peoff, 2) == pex:
|
|
||||||
yield off, i
|
|
||||||
|
|
||||||
|
|
||||||
def extract_file_embedded_pe(bv: BinaryView) -> Iterator[Tuple[Feature, Address]]:
|
def extract_file_embedded_pe(bv: BinaryView) -> Iterator[Tuple[Feature, Address]]:
|
||||||
"""extract embedded PE features"""
|
"""extract embedded PE features"""
|
||||||
for seg in bv.segments:
|
for seg in bv.segments:
|
||||||
for ea, _ in check_segment_for_pe(bv, seg):
|
yield from check_segment_for_pe(bv, seg)
|
||||||
yield Characteristic("embedded pe"), FileOffsetAddress(ea)
|
|
||||||
|
|
||||||
|
|
||||||
def extract_file_export_names(bv: BinaryView) -> Iterator[Tuple[Feature, Address]]:
|
def extract_file_export_names(bv: BinaryView) -> Iterator[Tuple[Feature, Address]]:
|
||||||
"""extract function exports"""
|
"""extract function exports"""
|
||||||
for sym in bv.get_symbols_of_type(SymbolType.FunctionSymbol):
|
for sym in bv.get_symbols_of_type(SymbolType.FunctionSymbol) + bv.get_symbols_of_type(SymbolType.DataSymbol):
|
||||||
if sym.binding in [SymbolBinding.GlobalBinding, SymbolBinding.WeakBinding]:
|
if sym.binding in [SymbolBinding.GlobalBinding, SymbolBinding.WeakBinding]:
|
||||||
name = sym.short_name
|
name = sym.short_name
|
||||||
|
if name.startswith("__forwarder_name(") and name.endswith(")"):
|
||||||
|
yield Export(name[17:-1]), AbsoluteVirtualAddress(sym.address)
|
||||||
|
yield Characteristic("forwarded export"), AbsoluteVirtualAddress(sym.address)
|
||||||
|
else:
|
||||||
yield Export(name), AbsoluteVirtualAddress(sym.address)
|
yield Export(name), AbsoluteVirtualAddress(sym.address)
|
||||||
|
|
||||||
unmangled_name = unmangle_c_name(name)
|
unmangled_name = unmangle_c_name(name)
|
||||||
if name != unmangled_name:
|
if name != unmangled_name:
|
||||||
yield Export(unmangled_name), AbsoluteVirtualAddress(sym.address)
|
yield Export(unmangled_name), AbsoluteVirtualAddress(sym.address)
|
||||||
@@ -115,13 +86,13 @@ def extract_file_import_names(bv: BinaryView) -> Iterator[Tuple[Feature, Address
|
|||||||
for sym in bv.get_symbols_of_type(SymbolType.ImportAddressSymbol):
|
for sym in bv.get_symbols_of_type(SymbolType.ImportAddressSymbol):
|
||||||
lib_name = str(sym.namespace)
|
lib_name = str(sym.namespace)
|
||||||
addr = AbsoluteVirtualAddress(sym.address)
|
addr = AbsoluteVirtualAddress(sym.address)
|
||||||
for name in capa.features.extractors.helpers.generate_symbols(lib_name, sym.short_name):
|
for name in capa.features.extractors.helpers.generate_symbols(lib_name, sym.short_name, include_dll=True):
|
||||||
yield Import(name), addr
|
yield Import(name), addr
|
||||||
|
|
||||||
ordinal = sym.ordinal
|
ordinal = sym.ordinal
|
||||||
if ordinal != 0 and (lib_name != ""):
|
if ordinal != 0 and (lib_name != ""):
|
||||||
ordinal_name = f"#{ordinal}"
|
ordinal_name = f"#{ordinal}"
|
||||||
for name in capa.features.extractors.helpers.generate_symbols(lib_name, ordinal_name):
|
for name in capa.features.extractors.helpers.generate_symbols(lib_name, ordinal_name, include_dll=True):
|
||||||
yield Import(name), addr
|
yield Import(name), addr
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -5,16 +5,24 @@
|
|||||||
# Unless required by applicable law or agreed to in writing, software distributed under the License
|
# 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.
|
# 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.
|
# See the License for the specific language governing permissions and limitations under the License.
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import logging
|
||||||
import subprocess
|
import subprocess
|
||||||
|
import importlib.util
|
||||||
|
from typing import Optional
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
# When the script gets executed as a standalone executable (via PyInstaller), `import binaryninja` does not work because
|
# When the script gets executed as a standalone executable (via PyInstaller), `import binaryninja` does not work because
|
||||||
# we have excluded the binaryninja module in `pyinstaller.spec`. The trick here is to call the system Python and try
|
# we have excluded the binaryninja module in `pyinstaller.spec`. The trick here is to call the system Python and try
|
||||||
# to find out the path of the binaryninja module that has been installed.
|
# to find out the path of the binaryninja module that has been installed.
|
||||||
# Note, including the binaryninja module in the `pyintaller.spec` would not work, since the binaryninja module tries to
|
# Note, including the binaryninja module in the `pyinstaller.spec` would not work, since the binaryninja module tries to
|
||||||
# find the binaryninja core e.g., `libbinaryninjacore.dylib`, using a relative path. And this does not work when the
|
# find the binaryninja core e.g., `libbinaryninjacore.dylib`, using a relative path. And this does not work when the
|
||||||
# binaryninja module is extracted by the PyInstaller.
|
# binaryninja module is extracted by the PyInstaller.
|
||||||
code = r"""
|
CODE = r"""
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from importlib import util
|
from importlib import util
|
||||||
spec = util.find_spec('binaryninja')
|
spec = util.find_spec('binaryninja')
|
||||||
@@ -26,10 +34,146 @@ if spec is not None:
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
def find_binja_path() -> Path:
|
def find_binaryninja_path_via_subprocess() -> Optional[Path]:
|
||||||
raw_output = subprocess.check_output(["python", "-c", code]).decode("ascii").strip()
|
raw_output = subprocess.check_output(["python", "-c", CODE]).decode("ascii").strip()
|
||||||
return Path(bytes.fromhex(raw_output).decode("utf8"))
|
output = bytes.fromhex(raw_output).decode("utf8")
|
||||||
|
if not output.strip():
|
||||||
|
return None
|
||||||
|
return Path(output)
|
||||||
|
|
||||||
|
|
||||||
|
def get_desktop_entry(name: str) -> Optional[Path]:
|
||||||
|
"""
|
||||||
|
Find the path for the given XDG Desktop Entry name.
|
||||||
|
|
||||||
|
Like:
|
||||||
|
|
||||||
|
>> get_desktop_entry("com.vector35.binaryninja.desktop")
|
||||||
|
Path("~/.local/share/applications/com.vector35.binaryninja.desktop")
|
||||||
|
"""
|
||||||
|
assert sys.platform in ("linux", "linux2")
|
||||||
|
assert name.endswith(".desktop")
|
||||||
|
|
||||||
|
data_dirs = os.environ.get("XDG_DATA_DIRS", "/usr/share") + f":{Path.home()}/.local/share"
|
||||||
|
for data_dir in data_dirs.split(":"):
|
||||||
|
applications = Path(data_dir) / "applications"
|
||||||
|
for application in applications.glob("*.desktop"):
|
||||||
|
if application.name == name:
|
||||||
|
return application
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def get_binaryninja_path(desktop_entry: Path) -> Optional[Path]:
|
||||||
|
# from: Exec=/home/wballenthin/software/binaryninja/binaryninja %u
|
||||||
|
# to: /home/wballenthin/software/binaryninja/
|
||||||
|
for line in desktop_entry.read_text(encoding="utf-8").splitlines():
|
||||||
|
if not line.startswith("Exec="):
|
||||||
|
continue
|
||||||
|
|
||||||
|
if not line.endswith("binaryninja %u"):
|
||||||
|
continue
|
||||||
|
|
||||||
|
binaryninja_path = Path(line[len("Exec=") : -len("binaryninja %u")])
|
||||||
|
if not binaryninja_path.exists():
|
||||||
|
return None
|
||||||
|
|
||||||
|
return binaryninja_path
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def validate_binaryninja_path(binaryninja_path: Path) -> bool:
|
||||||
|
if not binaryninja_path:
|
||||||
|
return False
|
||||||
|
|
||||||
|
module_path = binaryninja_path / "python"
|
||||||
|
if not module_path.is_dir():
|
||||||
|
return False
|
||||||
|
|
||||||
|
if not (module_path / "binaryninja" / "__init__.py").is_file():
|
||||||
|
return False
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def find_binaryninja() -> Optional[Path]:
|
||||||
|
binaryninja_path = find_binaryninja_path_via_subprocess()
|
||||||
|
if not binaryninja_path or not validate_binaryninja_path(binaryninja_path):
|
||||||
|
if sys.platform == "linux" or sys.platform == "linux2":
|
||||||
|
# ok
|
||||||
|
logger.debug("detected OS: linux")
|
||||||
|
elif sys.platform == "darwin":
|
||||||
|
logger.warning("unsupported platform to find Binary Ninja: %s", sys.platform)
|
||||||
|
return False
|
||||||
|
elif sys.platform == "win32":
|
||||||
|
logger.warning("unsupported platform to find Binary Ninja: %s", sys.platform)
|
||||||
|
return False
|
||||||
|
else:
|
||||||
|
logger.warning("unsupported platform to find Binary Ninja: %s", sys.platform)
|
||||||
|
return False
|
||||||
|
|
||||||
|
desktop_entry = get_desktop_entry("com.vector35.binaryninja.desktop")
|
||||||
|
if not desktop_entry:
|
||||||
|
logger.debug("failed to find Binary Ninja application")
|
||||||
|
return None
|
||||||
|
logger.debug("found Binary Ninja application: %s", desktop_entry)
|
||||||
|
|
||||||
|
binaryninja_path = get_binaryninja_path(desktop_entry)
|
||||||
|
if not binaryninja_path:
|
||||||
|
logger.debug("failed to determine Binary Ninja installation path")
|
||||||
|
return None
|
||||||
|
|
||||||
|
if not validate_binaryninja_path(binaryninja_path):
|
||||||
|
logger.debug("failed to validate Binary Ninja installation")
|
||||||
|
return None
|
||||||
|
|
||||||
|
logger.debug("found Binary Ninja installation: %s", binaryninja_path)
|
||||||
|
|
||||||
|
return binaryninja_path / "python"
|
||||||
|
|
||||||
|
|
||||||
|
def is_binaryninja_installed() -> bool:
|
||||||
|
"""Is the binaryninja module ready to import?"""
|
||||||
|
try:
|
||||||
|
return importlib.util.find_spec("binaryninja") is not None
|
||||||
|
except ModuleNotFoundError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def has_binaryninja() -> bool:
|
||||||
|
if is_binaryninja_installed():
|
||||||
|
logger.debug("found installed Binary Ninja API")
|
||||||
|
return True
|
||||||
|
|
||||||
|
logger.debug("Binary Ninja API not installed, searching...")
|
||||||
|
|
||||||
|
binaryninja_path = find_binaryninja()
|
||||||
|
if not binaryninja_path:
|
||||||
|
logger.debug("failed to find Binary Ninja installation")
|
||||||
|
|
||||||
|
logger.debug("found Binary Ninja API: %s", binaryninja_path)
|
||||||
|
return binaryninja_path is not None
|
||||||
|
|
||||||
|
|
||||||
|
def load_binaryninja() -> bool:
|
||||||
|
try:
|
||||||
|
import binaryninja
|
||||||
|
|
||||||
|
return True
|
||||||
|
except ImportError:
|
||||||
|
binaryninja_path = find_binaryninja()
|
||||||
|
if not binaryninja_path:
|
||||||
|
return False
|
||||||
|
|
||||||
|
sys.path.append(binaryninja_path.absolute().as_posix())
|
||||||
|
try:
|
||||||
|
import binaryninja # noqa: F401 unused import
|
||||||
|
|
||||||
|
return True
|
||||||
|
except ImportError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print(find_binja_path())
|
print(find_binaryninja_path_via_subprocess())
|
||||||
|
|||||||
0
capa/features/extractors/cape/__init__.py
Normal file
0
capa/features/extractors/cape/__init__.py
Normal file
64
capa/features/extractors/cape/call.py
Normal file
64
capa/features/extractors/cape/call.py
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Tuple, Iterator
|
||||||
|
|
||||||
|
import capa.features.extractors.helpers
|
||||||
|
from capa.helpers import assert_never
|
||||||
|
from capa.features.insn import API, Number
|
||||||
|
from capa.features.common import String, Feature
|
||||||
|
from capa.features.address import Address
|
||||||
|
from capa.features.extractors.cape.models import Call
|
||||||
|
from capa.features.extractors.base_extractor import CallHandle, ThreadHandle, ProcessHandle
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_call_features(ph: ProcessHandle, th: ThreadHandle, ch: CallHandle) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
"""
|
||||||
|
this method extracts the given call's features (such as API name and arguments),
|
||||||
|
and returns them as API, Number, and String features.
|
||||||
|
|
||||||
|
args:
|
||||||
|
ph: process handle (for defining the extraction scope)
|
||||||
|
th: thread handle (for defining the extraction scope)
|
||||||
|
ch: call handle (for defining the extraction scope)
|
||||||
|
|
||||||
|
yields:
|
||||||
|
Feature, address; where Feature is either: API, Number, or String.
|
||||||
|
"""
|
||||||
|
call: Call = ch.inner
|
||||||
|
|
||||||
|
# list similar to disassembly: arguments right-to-left, call
|
||||||
|
for arg in reversed(call.arguments):
|
||||||
|
value = arg.value
|
||||||
|
if isinstance(value, list) and len(value) == 0:
|
||||||
|
# unsure why CAPE captures arguments as empty lists?
|
||||||
|
continue
|
||||||
|
|
||||||
|
elif isinstance(value, str):
|
||||||
|
yield String(value), ch.address
|
||||||
|
|
||||||
|
elif isinstance(value, int):
|
||||||
|
yield Number(value), ch.address
|
||||||
|
|
||||||
|
else:
|
||||||
|
assert_never(value)
|
||||||
|
|
||||||
|
for name in capa.features.extractors.helpers.generate_symbols("", call.api):
|
||||||
|
yield API(name), ch.address
|
||||||
|
|
||||||
|
|
||||||
|
def extract_features(ph: ProcessHandle, th: ThreadHandle, ch: CallHandle) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
for handler in CALL_HANDLERS:
|
||||||
|
for feature, addr in handler(ph, th, ch):
|
||||||
|
yield feature, addr
|
||||||
|
|
||||||
|
|
||||||
|
CALL_HANDLERS = (extract_call_features,)
|
||||||
153
capa/features/extractors/cape/extractor.py
Normal file
153
capa/features/extractors/cape/extractor.py
Normal file
@@ -0,0 +1,153 @@
|
|||||||
|
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Dict, Tuple, Union, Iterator
|
||||||
|
|
||||||
|
import capa.features.extractors.cape.call
|
||||||
|
import capa.features.extractors.cape.file
|
||||||
|
import capa.features.extractors.cape.thread
|
||||||
|
import capa.features.extractors.cape.global_
|
||||||
|
import capa.features.extractors.cape.process
|
||||||
|
from capa.exceptions import EmptyReportError, UnsupportedFormatError
|
||||||
|
from capa.features.common import Feature, Characteristic
|
||||||
|
from capa.features.address import NO_ADDRESS, Address, AbsoluteVirtualAddress, _NoAddress
|
||||||
|
from capa.features.extractors.cape.models import Call, Static, Process, CapeReport
|
||||||
|
from capa.features.extractors.base_extractor import (
|
||||||
|
CallHandle,
|
||||||
|
SampleHashes,
|
||||||
|
ThreadHandle,
|
||||||
|
ProcessHandle,
|
||||||
|
DynamicFeatureExtractor,
|
||||||
|
)
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
TESTED_VERSIONS = {"2.2-CAPE", "2.4-CAPE"}
|
||||||
|
|
||||||
|
|
||||||
|
class CapeExtractor(DynamicFeatureExtractor):
|
||||||
|
def __init__(self, report: CapeReport):
|
||||||
|
super().__init__(
|
||||||
|
hashes=SampleHashes(
|
||||||
|
md5=report.target.file.md5.lower(),
|
||||||
|
sha1=report.target.file.sha1.lower(),
|
||||||
|
sha256=report.target.file.sha256.lower(),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
self.report: CapeReport = report
|
||||||
|
|
||||||
|
# pre-compute these because we'll yield them at *every* scope.
|
||||||
|
self.global_features = list(capa.features.extractors.cape.global_.extract_features(self.report))
|
||||||
|
|
||||||
|
def get_base_address(self) -> Union[AbsoluteVirtualAddress, _NoAddress, None]:
|
||||||
|
# value according to the PE header, the actual trace may use a different imagebase
|
||||||
|
assert self.report.static is not None and self.report.static.pe is not None
|
||||||
|
return AbsoluteVirtualAddress(self.report.static.pe.imagebase)
|
||||||
|
|
||||||
|
def extract_global_features(self) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
yield from self.global_features
|
||||||
|
|
||||||
|
def extract_file_features(self) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
yield from capa.features.extractors.cape.file.extract_features(self.report)
|
||||||
|
|
||||||
|
def get_processes(self) -> Iterator[ProcessHandle]:
|
||||||
|
yield from capa.features.extractors.cape.file.get_processes(self.report)
|
||||||
|
|
||||||
|
def extract_process_features(self, ph: ProcessHandle) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
yield from capa.features.extractors.cape.process.extract_features(ph)
|
||||||
|
|
||||||
|
def get_process_name(self, ph) -> str:
|
||||||
|
process: Process = ph.inner
|
||||||
|
return process.process_name
|
||||||
|
|
||||||
|
def get_threads(self, ph: ProcessHandle) -> Iterator[ThreadHandle]:
|
||||||
|
yield from capa.features.extractors.cape.process.get_threads(ph)
|
||||||
|
|
||||||
|
def extract_thread_features(self, ph: ProcessHandle, th: ThreadHandle) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
if False:
|
||||||
|
# force this routine to be a generator,
|
||||||
|
# but we don't actually have any elements to generate.
|
||||||
|
yield Characteristic("never"), NO_ADDRESS
|
||||||
|
return
|
||||||
|
|
||||||
|
def get_calls(self, ph: ProcessHandle, th: ThreadHandle) -> Iterator[CallHandle]:
|
||||||
|
yield from capa.features.extractors.cape.thread.get_calls(ph, th)
|
||||||
|
|
||||||
|
def extract_call_features(
|
||||||
|
self, ph: ProcessHandle, th: ThreadHandle, ch: CallHandle
|
||||||
|
) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
yield from capa.features.extractors.cape.call.extract_features(ph, th, ch)
|
||||||
|
|
||||||
|
def get_call_name(self, ph, th, ch) -> str:
|
||||||
|
call: Call = ch.inner
|
||||||
|
|
||||||
|
parts = []
|
||||||
|
parts.append(call.api)
|
||||||
|
parts.append("(")
|
||||||
|
for argument in call.arguments:
|
||||||
|
parts.append(argument.name)
|
||||||
|
parts.append("=")
|
||||||
|
|
||||||
|
if argument.pretty_value:
|
||||||
|
parts.append(argument.pretty_value)
|
||||||
|
else:
|
||||||
|
if isinstance(argument.value, int):
|
||||||
|
parts.append(hex(argument.value))
|
||||||
|
elif isinstance(argument.value, str):
|
||||||
|
parts.append('"')
|
||||||
|
parts.append(argument.value)
|
||||||
|
parts.append('"')
|
||||||
|
elif isinstance(argument.value, list):
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
capa.helpers.assert_never(argument.value)
|
||||||
|
|
||||||
|
parts.append(", ")
|
||||||
|
if call.arguments:
|
||||||
|
# remove the trailing comma
|
||||||
|
parts.pop()
|
||||||
|
parts.append(")")
|
||||||
|
parts.append(" -> ")
|
||||||
|
if call.pretty_return:
|
||||||
|
parts.append(call.pretty_return)
|
||||||
|
else:
|
||||||
|
parts.append(hex(call.return_))
|
||||||
|
|
||||||
|
return "".join(parts)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_report(cls, report: Dict) -> "CapeExtractor":
|
||||||
|
cr = CapeReport.model_validate(report)
|
||||||
|
|
||||||
|
if cr.info.version not in TESTED_VERSIONS:
|
||||||
|
logger.warning("CAPE version '%s' not tested/supported yet", cr.info.version)
|
||||||
|
|
||||||
|
# TODO(mr-tz): support more file types
|
||||||
|
# https://github.com/mandiant/capa/issues/1933
|
||||||
|
if "PE" not in cr.target.file.type:
|
||||||
|
logger.error(
|
||||||
|
"capa currently only supports PE target files, this target file's type is: '%s'.\nPlease report this at: https://github.com/mandiant/capa/issues/1933",
|
||||||
|
cr.target.file.type,
|
||||||
|
)
|
||||||
|
|
||||||
|
# observed in 2.4-CAPE reports from capesandbox.com
|
||||||
|
if cr.static is None and cr.target.file.pe is not None:
|
||||||
|
cr.static = Static()
|
||||||
|
cr.static.pe = cr.target.file.pe
|
||||||
|
|
||||||
|
if cr.static is None:
|
||||||
|
raise UnsupportedFormatError("CAPE report missing static analysis")
|
||||||
|
|
||||||
|
if cr.static.pe is None:
|
||||||
|
raise UnsupportedFormatError("CAPE report missing PE analysis")
|
||||||
|
|
||||||
|
if len(cr.behavior.processes) == 0:
|
||||||
|
raise EmptyReportError("CAPE did not capture any processes")
|
||||||
|
|
||||||
|
return cls(cr)
|
||||||
132
capa/features/extractors/cape/file.py
Normal file
132
capa/features/extractors/cape/file.py
Normal file
@@ -0,0 +1,132 @@
|
|||||||
|
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Tuple, Iterator
|
||||||
|
|
||||||
|
from capa.features.file import Export, Import, Section
|
||||||
|
from capa.features.common import String, Feature
|
||||||
|
from capa.features.address import NO_ADDRESS, Address, ProcessAddress, AbsoluteVirtualAddress
|
||||||
|
from capa.features.extractors.helpers import generate_symbols
|
||||||
|
from capa.features.extractors.cape.models import CapeReport
|
||||||
|
from capa.features.extractors.base_extractor import ProcessHandle
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def get_processes(report: CapeReport) -> Iterator[ProcessHandle]:
|
||||||
|
"""
|
||||||
|
get all the created processes for a sample
|
||||||
|
"""
|
||||||
|
seen_processes = {}
|
||||||
|
for process in report.behavior.processes:
|
||||||
|
addr = ProcessAddress(pid=process.process_id, ppid=process.parent_id)
|
||||||
|
yield ProcessHandle(address=addr, inner=process)
|
||||||
|
|
||||||
|
# check for pid and ppid reuse
|
||||||
|
if addr not in seen_processes:
|
||||||
|
seen_processes[addr] = [process]
|
||||||
|
else:
|
||||||
|
logger.warning(
|
||||||
|
"pid and ppid reuse detected between process %s and process%s: %s",
|
||||||
|
process,
|
||||||
|
"es" if len(seen_processes[addr]) > 1 else "",
|
||||||
|
seen_processes[addr],
|
||||||
|
)
|
||||||
|
seen_processes[addr].append(process)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_import_names(report: CapeReport) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
"""
|
||||||
|
extract imported function names
|
||||||
|
"""
|
||||||
|
assert report.static is not None and report.static.pe is not None
|
||||||
|
imports = report.static.pe.imports
|
||||||
|
|
||||||
|
if isinstance(imports, dict):
|
||||||
|
imports = list(imports.values())
|
||||||
|
|
||||||
|
assert isinstance(imports, list)
|
||||||
|
|
||||||
|
for library in imports:
|
||||||
|
for function in library.imports:
|
||||||
|
if not function.name:
|
||||||
|
continue
|
||||||
|
|
||||||
|
for name in generate_symbols(library.dll, function.name, include_dll=True):
|
||||||
|
yield Import(name), AbsoluteVirtualAddress(function.address)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_export_names(report: CapeReport) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
assert report.static is not None and report.static.pe is not None
|
||||||
|
for function in report.static.pe.exports:
|
||||||
|
yield Export(function.name), AbsoluteVirtualAddress(function.address)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_section_names(report: CapeReport) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
assert report.static is not None and report.static.pe is not None
|
||||||
|
for section in report.static.pe.sections:
|
||||||
|
yield Section(section.name), AbsoluteVirtualAddress(section.virtual_address)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_file_strings(report: CapeReport) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
if report.strings is not None:
|
||||||
|
for string in report.strings:
|
||||||
|
yield String(string), NO_ADDRESS
|
||||||
|
|
||||||
|
|
||||||
|
def extract_used_regkeys(report: CapeReport) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
for regkey in report.behavior.summary.keys:
|
||||||
|
yield String(regkey), NO_ADDRESS
|
||||||
|
|
||||||
|
|
||||||
|
def extract_used_files(report: CapeReport) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
for file in report.behavior.summary.files:
|
||||||
|
yield String(file), NO_ADDRESS
|
||||||
|
|
||||||
|
|
||||||
|
def extract_used_mutexes(report: CapeReport) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
for mutex in report.behavior.summary.mutexes:
|
||||||
|
yield String(mutex), NO_ADDRESS
|
||||||
|
|
||||||
|
|
||||||
|
def extract_used_commands(report: CapeReport) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
for cmd in report.behavior.summary.executed_commands:
|
||||||
|
yield String(cmd), NO_ADDRESS
|
||||||
|
|
||||||
|
|
||||||
|
def extract_used_apis(report: CapeReport) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
for symbol in report.behavior.summary.resolved_apis:
|
||||||
|
yield String(symbol), NO_ADDRESS
|
||||||
|
|
||||||
|
|
||||||
|
def extract_used_services(report: CapeReport) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
for svc in report.behavior.summary.created_services:
|
||||||
|
yield String(svc), NO_ADDRESS
|
||||||
|
for svc in report.behavior.summary.started_services:
|
||||||
|
yield String(svc), NO_ADDRESS
|
||||||
|
|
||||||
|
|
||||||
|
def extract_features(report: CapeReport) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
for handler in FILE_HANDLERS:
|
||||||
|
for feature, addr in handler(report):
|
||||||
|
yield feature, addr
|
||||||
|
|
||||||
|
|
||||||
|
FILE_HANDLERS = (
|
||||||
|
extract_import_names,
|
||||||
|
extract_export_names,
|
||||||
|
extract_section_names,
|
||||||
|
extract_file_strings,
|
||||||
|
extract_used_regkeys,
|
||||||
|
extract_used_files,
|
||||||
|
extract_used_mutexes,
|
||||||
|
extract_used_commands,
|
||||||
|
extract_used_apis,
|
||||||
|
extract_used_services,
|
||||||
|
)
|
||||||
93
capa/features/extractors/cape/global_.py
Normal file
93
capa/features/extractors/cape/global_.py
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Tuple, Iterator
|
||||||
|
|
||||||
|
from capa.features.common import (
|
||||||
|
OS,
|
||||||
|
OS_ANY,
|
||||||
|
OS_LINUX,
|
||||||
|
ARCH_I386,
|
||||||
|
FORMAT_PE,
|
||||||
|
ARCH_AMD64,
|
||||||
|
FORMAT_ELF,
|
||||||
|
OS_WINDOWS,
|
||||||
|
Arch,
|
||||||
|
Format,
|
||||||
|
Feature,
|
||||||
|
)
|
||||||
|
from capa.features.address import NO_ADDRESS, Address
|
||||||
|
from capa.features.extractors.cape.models import CapeReport
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_arch(report: CapeReport) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
if "Intel 80386" in report.target.file.type:
|
||||||
|
yield Arch(ARCH_I386), NO_ADDRESS
|
||||||
|
elif "x86-64" in report.target.file.type:
|
||||||
|
yield Arch(ARCH_AMD64), NO_ADDRESS
|
||||||
|
else:
|
||||||
|
logger.warning("unrecognized Architecture: %s", report.target.file.type)
|
||||||
|
raise ValueError(
|
||||||
|
f"unrecognized Architecture from the CAPE report; output of file command: {report.target.file.type}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_format(report: CapeReport) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
if "PE" in report.target.file.type:
|
||||||
|
yield Format(FORMAT_PE), NO_ADDRESS
|
||||||
|
elif "ELF" in report.target.file.type:
|
||||||
|
yield Format(FORMAT_ELF), NO_ADDRESS
|
||||||
|
else:
|
||||||
|
logger.warning("unknown file format, file command output: %s", report.target.file.type)
|
||||||
|
raise ValueError(
|
||||||
|
f"unrecognized file format from the CAPE report; output of file command: {report.target.file.type}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_os(report: CapeReport) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
# this variable contains the output of the file command
|
||||||
|
file_output = report.target.file.type
|
||||||
|
|
||||||
|
if "windows" in file_output.lower():
|
||||||
|
yield OS(OS_WINDOWS), NO_ADDRESS
|
||||||
|
elif "elf" in file_output.lower():
|
||||||
|
# operating systems recognized by the file command: https://github.com/file/file/blob/master/src/readelf.c#L609
|
||||||
|
if "Linux" in file_output:
|
||||||
|
yield OS(OS_LINUX), NO_ADDRESS
|
||||||
|
elif "Hurd" in file_output:
|
||||||
|
yield OS("hurd"), NO_ADDRESS
|
||||||
|
elif "Solaris" in file_output:
|
||||||
|
yield OS("solaris"), NO_ADDRESS
|
||||||
|
elif "kFreeBSD" in file_output:
|
||||||
|
yield OS("freebsd"), NO_ADDRESS
|
||||||
|
elif "kNetBSD" in file_output:
|
||||||
|
yield OS("netbsd"), NO_ADDRESS
|
||||||
|
else:
|
||||||
|
# if the operating system information is missing from the cape report, it's likely a bug
|
||||||
|
logger.warning("unrecognized OS: %s", file_output)
|
||||||
|
raise ValueError(f"unrecognized OS from the CAPE report; output of file command: {file_output}")
|
||||||
|
else:
|
||||||
|
# the sample is shellcode
|
||||||
|
logger.debug("unsupported file format, file command output: %s", file_output)
|
||||||
|
yield OS(OS_ANY), NO_ADDRESS
|
||||||
|
|
||||||
|
|
||||||
|
def extract_features(report: CapeReport) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
for global_handler in GLOBAL_HANDLER:
|
||||||
|
for feature, addr in global_handler(report):
|
||||||
|
yield feature, addr
|
||||||
|
|
||||||
|
|
||||||
|
GLOBAL_HANDLER = (
|
||||||
|
extract_format,
|
||||||
|
extract_os,
|
||||||
|
extract_arch,
|
||||||
|
)
|
||||||
29
capa/features/extractors/cape/helpers.py
Normal file
29
capa/features/extractors/cape/helpers.py
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
|
||||||
|
from typing import Any, Dict, List
|
||||||
|
|
||||||
|
from capa.features.extractors.base_extractor import ProcessHandle
|
||||||
|
|
||||||
|
|
||||||
|
def find_process(processes: List[Dict[str, Any]], ph: ProcessHandle) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
find a specific process identified by a process handler.
|
||||||
|
|
||||||
|
args:
|
||||||
|
processes: a list of processes extracted by CAPE
|
||||||
|
ph: handle of the sought process
|
||||||
|
|
||||||
|
return:
|
||||||
|
a CAPE-defined dictionary for the sought process' information
|
||||||
|
"""
|
||||||
|
|
||||||
|
for process in processes:
|
||||||
|
if ph.address.ppid == process["parent_id"] and ph.address.pid == process["process_id"]:
|
||||||
|
return process
|
||||||
|
return {}
|
||||||
446
capa/features/extractors/cape/models.py
Normal file
446
capa/features/extractors/cape/models.py
Normal file
@@ -0,0 +1,446 @@
|
|||||||
|
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
import binascii
|
||||||
|
from typing import Any, Dict, List, Union, Literal, Optional
|
||||||
|
|
||||||
|
from pydantic import Field, BaseModel, ConfigDict
|
||||||
|
from typing_extensions import Annotated, TypeAlias
|
||||||
|
from pydantic.functional_validators import BeforeValidator
|
||||||
|
|
||||||
|
|
||||||
|
def validate_hex_int(value):
|
||||||
|
if isinstance(value, str):
|
||||||
|
return int(value, 16) if value.startswith("0x") else int(value, 10)
|
||||||
|
else:
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def validate_hex_bytes(value):
|
||||||
|
return binascii.unhexlify(value) if isinstance(value, str) else value
|
||||||
|
|
||||||
|
|
||||||
|
HexInt = Annotated[int, BeforeValidator(validate_hex_int)]
|
||||||
|
HexBytes = Annotated[bytes, BeforeValidator(validate_hex_bytes)]
|
||||||
|
|
||||||
|
|
||||||
|
# a model that *cannot* have extra fields
|
||||||
|
# if they do, pydantic raises an exception.
|
||||||
|
# use this for models we rely upon and cannot change.
|
||||||
|
#
|
||||||
|
# for things that may be extended and we don't care,
|
||||||
|
# use FlexibleModel.
|
||||||
|
class ExactModel(BaseModel):
|
||||||
|
model_config = ConfigDict(extra="forbid")
|
||||||
|
|
||||||
|
|
||||||
|
# a model that can have extra fields that we ignore.
|
||||||
|
# use this if we don't want to raise an exception for extra
|
||||||
|
# data fields that we didn't expect.
|
||||||
|
class FlexibleModel(BaseModel):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
# use this type to indicate that we won't model this data.
|
||||||
|
# because it's not relevant to our use in capa.
|
||||||
|
#
|
||||||
|
# while its nice to have full coverage of the data shape,
|
||||||
|
# it can easily change and break our parsing.
|
||||||
|
# so we really only want to describe what we'll use.
|
||||||
|
Skip: TypeAlias = Optional[Any]
|
||||||
|
|
||||||
|
|
||||||
|
# mark fields that we haven't seen yet and need to model.
|
||||||
|
# pydantic should raise an error when encountering data
|
||||||
|
# in a field with this type.
|
||||||
|
# then we can update the model with the discovered shape.
|
||||||
|
TODO: TypeAlias = None
|
||||||
|
ListTODO: TypeAlias = List[None]
|
||||||
|
DictTODO: TypeAlias = ExactModel
|
||||||
|
|
||||||
|
EmptyDict: TypeAlias = BaseModel
|
||||||
|
EmptyList: TypeAlias = List[Any]
|
||||||
|
|
||||||
|
|
||||||
|
class Info(FlexibleModel):
|
||||||
|
version: str
|
||||||
|
|
||||||
|
|
||||||
|
class ImportedSymbol(ExactModel):
|
||||||
|
address: HexInt
|
||||||
|
name: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class ImportedDll(ExactModel):
|
||||||
|
dll: str
|
||||||
|
imports: List[ImportedSymbol]
|
||||||
|
|
||||||
|
|
||||||
|
class DirectoryEntry(ExactModel):
|
||||||
|
name: str
|
||||||
|
virtual_address: HexInt
|
||||||
|
size: HexInt
|
||||||
|
|
||||||
|
|
||||||
|
class Section(ExactModel):
|
||||||
|
name: str
|
||||||
|
raw_address: HexInt
|
||||||
|
virtual_address: HexInt
|
||||||
|
virtual_size: HexInt
|
||||||
|
size_of_data: HexInt
|
||||||
|
characteristics: str
|
||||||
|
characteristics_raw: HexInt
|
||||||
|
entropy: float
|
||||||
|
|
||||||
|
|
||||||
|
class Resource(ExactModel):
|
||||||
|
name: str
|
||||||
|
language: Optional[str] = None
|
||||||
|
sublanguage: str
|
||||||
|
filetype: Optional[str]
|
||||||
|
offset: HexInt
|
||||||
|
size: HexInt
|
||||||
|
entropy: float
|
||||||
|
|
||||||
|
|
||||||
|
class DigitalSigner(FlexibleModel):
|
||||||
|
md5_fingerprint: str
|
||||||
|
not_after: str
|
||||||
|
not_before: str
|
||||||
|
serial_number: str
|
||||||
|
sha1_fingerprint: str
|
||||||
|
sha256_fingerprint: str
|
||||||
|
|
||||||
|
issuer_commonName: Optional[str] = None
|
||||||
|
issuer_countryName: Optional[str] = None
|
||||||
|
issuer_localityName: Optional[str] = None
|
||||||
|
issuer_organizationName: Optional[str] = None
|
||||||
|
issuer_stateOrProvinceName: Optional[str] = None
|
||||||
|
|
||||||
|
subject_commonName: Optional[str] = None
|
||||||
|
subject_countryName: Optional[str] = None
|
||||||
|
subject_localityName: Optional[str] = None
|
||||||
|
subject_organizationName: Optional[str] = None
|
||||||
|
subject_stateOrProvinceName: Optional[str] = None
|
||||||
|
|
||||||
|
extensions_authorityInfoAccess_caIssuers: Optional[str] = None
|
||||||
|
extensions_authorityKeyIdentifier: Optional[str] = None
|
||||||
|
extensions_cRLDistributionPoints_0: Optional[str] = None
|
||||||
|
extensions_certificatePolicies_0: Optional[str] = None
|
||||||
|
extensions_subjectAltName_0: Optional[str] = None
|
||||||
|
extensions_subjectKeyIdentifier: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class AuxSigner(ExactModel):
|
||||||
|
name: str
|
||||||
|
issued_to: str = Field(alias="Issued to")
|
||||||
|
issued_by: str = Field(alias="Issued by")
|
||||||
|
expires: str = Field(alias="Expires")
|
||||||
|
sha1_hash: str = Field(alias="SHA1 hash")
|
||||||
|
|
||||||
|
|
||||||
|
class Signer(ExactModel):
|
||||||
|
aux_sha1: Optional[str] = None
|
||||||
|
aux_timestamp: Optional[str] = None
|
||||||
|
aux_valid: Optional[bool] = None
|
||||||
|
aux_error: Optional[bool] = None
|
||||||
|
aux_error_desc: Optional[str] = None
|
||||||
|
aux_signers: Optional[List[AuxSigner]] = None
|
||||||
|
|
||||||
|
|
||||||
|
class Overlay(ExactModel):
|
||||||
|
offset: HexInt
|
||||||
|
size: HexInt
|
||||||
|
|
||||||
|
|
||||||
|
class KV(ExactModel):
|
||||||
|
name: str
|
||||||
|
value: str
|
||||||
|
|
||||||
|
|
||||||
|
class ExportedSymbol(ExactModel):
|
||||||
|
address: HexInt
|
||||||
|
name: str
|
||||||
|
ordinal: int
|
||||||
|
|
||||||
|
|
||||||
|
class PE(ExactModel):
|
||||||
|
peid_signatures: TODO
|
||||||
|
imagebase: HexInt
|
||||||
|
entrypoint: HexInt
|
||||||
|
reported_checksum: HexInt
|
||||||
|
actual_checksum: HexInt
|
||||||
|
osversion: str
|
||||||
|
pdbpath: Optional[str] = None
|
||||||
|
timestamp: str
|
||||||
|
|
||||||
|
# List[ImportedDll], or Dict[basename(dll), ImportedDll]
|
||||||
|
imports: Union[List[ImportedDll], Dict[str, ImportedDll]]
|
||||||
|
imported_dll_count: Optional[int] = None
|
||||||
|
imphash: str
|
||||||
|
|
||||||
|
exported_dll_name: Optional[str] = None
|
||||||
|
exports: List[ExportedSymbol]
|
||||||
|
|
||||||
|
dirents: List[DirectoryEntry]
|
||||||
|
sections: List[Section]
|
||||||
|
|
||||||
|
ep_bytes: Optional[HexBytes] = None
|
||||||
|
|
||||||
|
overlay: Optional[Overlay] = None
|
||||||
|
resources: List[Resource]
|
||||||
|
versioninfo: List[KV]
|
||||||
|
|
||||||
|
# base64 encoded data
|
||||||
|
icon: Optional[str] = None
|
||||||
|
# MD5-like hash
|
||||||
|
icon_hash: Optional[str] = None
|
||||||
|
# MD5-like hash
|
||||||
|
icon_fuzzy: Optional[str] = None
|
||||||
|
# short hex string
|
||||||
|
icon_dhash: Optional[str] = None
|
||||||
|
|
||||||
|
digital_signers: List[DigitalSigner]
|
||||||
|
guest_signers: Signer
|
||||||
|
|
||||||
|
|
||||||
|
# TODO(mr-tz): target.file.dotnet, target.file.extracted_files, target.file.extracted_files_tool,
|
||||||
|
# target.file.extracted_files_time
|
||||||
|
# https://github.com/mandiant/capa/issues/1814
|
||||||
|
class File(FlexibleModel):
|
||||||
|
type: str
|
||||||
|
cape_type_code: Optional[int] = None
|
||||||
|
cape_type: Optional[str] = None
|
||||||
|
|
||||||
|
pid: Optional[Union[int, Literal[""]]] = None
|
||||||
|
name: Union[List[str], str]
|
||||||
|
path: str
|
||||||
|
guest_paths: Union[List[str], str, None]
|
||||||
|
timestamp: Optional[str] = None
|
||||||
|
|
||||||
|
#
|
||||||
|
# hashes
|
||||||
|
#
|
||||||
|
crc32: str
|
||||||
|
md5: str
|
||||||
|
sha1: str
|
||||||
|
sha256: str
|
||||||
|
sha512: str
|
||||||
|
sha3_384: Optional[str] = None
|
||||||
|
ssdeep: str
|
||||||
|
# unsure why this would ever be "False"
|
||||||
|
tlsh: Optional[Union[str, bool]] = None
|
||||||
|
rh_hash: Optional[str] = None
|
||||||
|
|
||||||
|
#
|
||||||
|
# other metadata, static analysis
|
||||||
|
#
|
||||||
|
size: int
|
||||||
|
pe: Optional[PE] = None
|
||||||
|
ep_bytes: Optional[HexBytes] = None
|
||||||
|
entrypoint: Optional[int] = None
|
||||||
|
data: Optional[str] = None
|
||||||
|
strings: Optional[List[str]] = None
|
||||||
|
|
||||||
|
#
|
||||||
|
# detections (skip)
|
||||||
|
#
|
||||||
|
yara: Skip = None
|
||||||
|
cape_yara: Skip = None
|
||||||
|
clamav: Skip = None
|
||||||
|
virustotal: Skip = None
|
||||||
|
|
||||||
|
|
||||||
|
class ProcessFile(File):
|
||||||
|
#
|
||||||
|
# like a File, but also has dynamic analysis results
|
||||||
|
#
|
||||||
|
pid: Optional[int] = None
|
||||||
|
process_path: Optional[str] = None
|
||||||
|
process_name: Optional[str] = None
|
||||||
|
module_path: Optional[str] = None
|
||||||
|
virtual_address: Optional[HexInt] = None
|
||||||
|
target_pid: Optional[Union[int, str]] = None
|
||||||
|
target_path: Optional[str] = None
|
||||||
|
target_process: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class Argument(ExactModel):
|
||||||
|
name: str
|
||||||
|
# unsure why empty list is provided here
|
||||||
|
value: Union[HexInt, int, str, EmptyList]
|
||||||
|
pretty_value: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class Call(ExactModel):
|
||||||
|
timestamp: str
|
||||||
|
thread_id: int
|
||||||
|
category: str
|
||||||
|
|
||||||
|
api: str
|
||||||
|
|
||||||
|
arguments: List[Argument]
|
||||||
|
status: bool
|
||||||
|
return_: HexInt = Field(alias="return")
|
||||||
|
pretty_return: Optional[str] = None
|
||||||
|
|
||||||
|
repeated: int
|
||||||
|
|
||||||
|
# virtual addresses
|
||||||
|
caller: HexInt
|
||||||
|
parentcaller: HexInt
|
||||||
|
|
||||||
|
# index into calls array
|
||||||
|
id: int
|
||||||
|
|
||||||
|
|
||||||
|
class Process(ExactModel):
|
||||||
|
process_id: int
|
||||||
|
process_name: str
|
||||||
|
parent_id: int
|
||||||
|
module_path: str
|
||||||
|
first_seen: str
|
||||||
|
calls: List[Call]
|
||||||
|
threads: List[int]
|
||||||
|
environ: Dict[str, str]
|
||||||
|
|
||||||
|
|
||||||
|
class ProcessTree(ExactModel):
|
||||||
|
name: str
|
||||||
|
pid: int
|
||||||
|
parent_id: int
|
||||||
|
module_path: str
|
||||||
|
threads: List[int]
|
||||||
|
environ: Dict[str, str]
|
||||||
|
children: List["ProcessTree"]
|
||||||
|
|
||||||
|
|
||||||
|
class Summary(ExactModel):
|
||||||
|
files: List[str]
|
||||||
|
read_files: List[str]
|
||||||
|
write_files: List[str]
|
||||||
|
delete_files: List[str]
|
||||||
|
keys: List[str]
|
||||||
|
read_keys: List[str]
|
||||||
|
write_keys: List[str]
|
||||||
|
delete_keys: List[str]
|
||||||
|
executed_commands: List[str]
|
||||||
|
resolved_apis: List[str]
|
||||||
|
mutexes: List[str]
|
||||||
|
created_services: List[str]
|
||||||
|
started_services: List[str]
|
||||||
|
|
||||||
|
|
||||||
|
class EncryptedBuffer(ExactModel):
|
||||||
|
process_name: str
|
||||||
|
pid: int
|
||||||
|
|
||||||
|
api_call: str
|
||||||
|
buffer: str
|
||||||
|
buffer_size: Optional[int] = None
|
||||||
|
crypt_key: Optional[Union[HexInt, str]] = None
|
||||||
|
|
||||||
|
|
||||||
|
class Behavior(ExactModel):
|
||||||
|
summary: Summary
|
||||||
|
|
||||||
|
# list of processes, of threads, of calls
|
||||||
|
processes: List[Process]
|
||||||
|
# tree of processes
|
||||||
|
processtree: List[ProcessTree]
|
||||||
|
|
||||||
|
anomaly: List[str]
|
||||||
|
encryptedbuffers: List[EncryptedBuffer]
|
||||||
|
# these are small objects that describe atomic events,
|
||||||
|
# like file move, registry access.
|
||||||
|
# we'll detect the same with our API call analysis.
|
||||||
|
enhanced: Skip = None
|
||||||
|
|
||||||
|
|
||||||
|
class Target(ExactModel):
|
||||||
|
category: str
|
||||||
|
file: File
|
||||||
|
pe: Optional[PE] = None
|
||||||
|
|
||||||
|
|
||||||
|
class Static(ExactModel):
|
||||||
|
pe: Optional[PE] = None
|
||||||
|
flare_capa: Skip = None
|
||||||
|
|
||||||
|
|
||||||
|
class Cape(ExactModel):
|
||||||
|
payloads: List[ProcessFile]
|
||||||
|
configs: Skip = None
|
||||||
|
|
||||||
|
|
||||||
|
# flexible because there may be more sorts of analysis
|
||||||
|
# but we only care about the ones described here.
|
||||||
|
class CapeReport(FlexibleModel):
|
||||||
|
# the input file, I think
|
||||||
|
target: Target
|
||||||
|
# info about the processing job, like machine and distributed metadata.
|
||||||
|
info: Info
|
||||||
|
|
||||||
|
#
|
||||||
|
# static analysis results
|
||||||
|
#
|
||||||
|
static: Optional[Static] = None
|
||||||
|
strings: Optional[List[str]] = None
|
||||||
|
|
||||||
|
#
|
||||||
|
# dynamic analysis results
|
||||||
|
#
|
||||||
|
# post-processed results: process tree, anomalies, etc
|
||||||
|
behavior: Behavior
|
||||||
|
|
||||||
|
# post-processed results: payloads and extracted configs
|
||||||
|
CAPE: Optional[Union[Cape, List]] = None
|
||||||
|
dropped: Optional[List[File]] = None
|
||||||
|
procdump: Optional[List[ProcessFile]] = None
|
||||||
|
procmemory: ListTODO
|
||||||
|
|
||||||
|
# =========================================================================
|
||||||
|
# information we won't use in capa
|
||||||
|
#
|
||||||
|
|
||||||
|
#
|
||||||
|
# NBIs and HBIs
|
||||||
|
# these are super interesting, but they don't enable use to detect behaviors.
|
||||||
|
# they take a lot of code to model and details to maintain.
|
||||||
|
#
|
||||||
|
# if we come up with a future use for this, go ahead and re-enable!
|
||||||
|
#
|
||||||
|
network: Skip = None
|
||||||
|
suricata: Skip = None
|
||||||
|
curtain: Skip = None
|
||||||
|
sysmon: Skip = None
|
||||||
|
url_analysis: Skip = None
|
||||||
|
|
||||||
|
# screenshot hash values
|
||||||
|
deduplicated_shots: Skip = None
|
||||||
|
# k-v pairs describing the time it took to run each stage.
|
||||||
|
statistics: Skip = None
|
||||||
|
# k-v pairs of ATT&CK ID to signature name or similar.
|
||||||
|
ttps: Skip = None
|
||||||
|
# debug log messages
|
||||||
|
debug: Skip = None
|
||||||
|
|
||||||
|
# various signature matches
|
||||||
|
# we could potentially extend capa to use this info one day,
|
||||||
|
# though it would be quite sandbox-specific,
|
||||||
|
# and more detection-oriented than capability detection.
|
||||||
|
signatures: Skip = None
|
||||||
|
malfamily_tag: Optional[str] = None
|
||||||
|
malscore: float
|
||||||
|
detections: Skip = None
|
||||||
|
detections2pid: Optional[Dict[int, List[str]]] = None
|
||||||
|
# AV detections for the sample.
|
||||||
|
virustotal: Skip = None
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_buf(cls, buf: bytes) -> "CapeReport":
|
||||||
|
return cls.model_validate_json(buf)
|
||||||
48
capa/features/extractors/cape/process.py
Normal file
48
capa/features/extractors/cape/process.py
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import List, Tuple, Iterator
|
||||||
|
|
||||||
|
from capa.features.common import String, Feature
|
||||||
|
from capa.features.address import Address, ThreadAddress
|
||||||
|
from capa.features.extractors.cape.models import Process
|
||||||
|
from capa.features.extractors.base_extractor import ThreadHandle, ProcessHandle
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def get_threads(ph: ProcessHandle) -> Iterator[ThreadHandle]:
|
||||||
|
"""
|
||||||
|
get the threads associated with a given process
|
||||||
|
"""
|
||||||
|
process: Process = ph.inner
|
||||||
|
threads: List[int] = process.threads
|
||||||
|
|
||||||
|
for thread in threads:
|
||||||
|
address: ThreadAddress = ThreadAddress(process=ph.address, tid=thread)
|
||||||
|
yield ThreadHandle(address=address, inner={})
|
||||||
|
|
||||||
|
|
||||||
|
def extract_environ_strings(ph: ProcessHandle) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
"""
|
||||||
|
extract strings from a process' provided environment variables.
|
||||||
|
"""
|
||||||
|
process: Process = ph.inner
|
||||||
|
|
||||||
|
for value in (value for value in process.environ.values() if value):
|
||||||
|
yield String(value), ph.address
|
||||||
|
|
||||||
|
|
||||||
|
def extract_features(ph: ProcessHandle) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
for handler in PROCESS_HANDLERS:
|
||||||
|
for feature, addr in handler(ph):
|
||||||
|
yield feature, addr
|
||||||
|
|
||||||
|
|
||||||
|
PROCESS_HANDLERS = (extract_environ_strings,)
|
||||||
32
capa/features/extractors/cape/thread.py
Normal file
32
capa/features/extractors/cape/thread.py
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Iterator
|
||||||
|
|
||||||
|
from capa.features.address import DynamicCallAddress
|
||||||
|
from capa.features.extractors.helpers import generate_symbols
|
||||||
|
from capa.features.extractors.cape.models import Process
|
||||||
|
from capa.features.extractors.base_extractor import CallHandle, ThreadHandle, ProcessHandle
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def get_calls(ph: ProcessHandle, th: ThreadHandle) -> Iterator[CallHandle]:
|
||||||
|
process: Process = ph.inner
|
||||||
|
|
||||||
|
tid = th.address.tid
|
||||||
|
for call_index, call in enumerate(process.calls):
|
||||||
|
if call.thread_id != tid:
|
||||||
|
continue
|
||||||
|
|
||||||
|
for symbol in generate_symbols("", call.api):
|
||||||
|
call.api = symbol
|
||||||
|
|
||||||
|
addr = DynamicCallAddress(thread=th.address, id=call_index)
|
||||||
|
yield CallHandle(address=addr, inner=call)
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
# Copyright (C) 2021 Mandiant, Inc. All Rights Reserved.
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
# you may not use this file except in compliance with the License.
|
# you may not use this file except in compliance with the License.
|
||||||
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
||||||
@@ -6,6 +6,7 @@
|
|||||||
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
# 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.
|
# See the License for the specific language governing permissions and limitations under the License.
|
||||||
import io
|
import io
|
||||||
|
import re
|
||||||
import logging
|
import logging
|
||||||
import binascii
|
import binascii
|
||||||
import contextlib
|
import contextlib
|
||||||
@@ -41,9 +42,10 @@ logger = logging.getLogger(__name__)
|
|||||||
MATCH_PE = b"MZ"
|
MATCH_PE = b"MZ"
|
||||||
MATCH_ELF = b"\x7fELF"
|
MATCH_ELF = b"\x7fELF"
|
||||||
MATCH_RESULT = b'{"meta":'
|
MATCH_RESULT = b'{"meta":'
|
||||||
|
MATCH_JSON_OBJECT = b'{"'
|
||||||
|
|
||||||
|
|
||||||
def extract_file_strings(buf, **kwargs) -> Iterator[Tuple[String, Address]]:
|
def extract_file_strings(buf: bytes, **kwargs) -> Iterator[Tuple[String, Address]]:
|
||||||
"""
|
"""
|
||||||
extract ASCII and UTF-16 LE strings from file
|
extract ASCII and UTF-16 LE strings from file
|
||||||
"""
|
"""
|
||||||
@@ -54,7 +56,7 @@ def extract_file_strings(buf, **kwargs) -> Iterator[Tuple[String, Address]]:
|
|||||||
yield String(s.s), FileOffsetAddress(s.offset)
|
yield String(s.s), FileOffsetAddress(s.offset)
|
||||||
|
|
||||||
|
|
||||||
def extract_format(buf) -> Iterator[Tuple[Feature, Address]]:
|
def extract_format(buf: bytes) -> Iterator[Tuple[Feature, Address]]:
|
||||||
if buf.startswith(MATCH_PE):
|
if buf.startswith(MATCH_PE):
|
||||||
yield Format(FORMAT_PE), NO_ADDRESS
|
yield Format(FORMAT_PE), NO_ADDRESS
|
||||||
elif buf.startswith(MATCH_ELF):
|
elif buf.startswith(MATCH_ELF):
|
||||||
@@ -63,12 +65,17 @@ def extract_format(buf) -> Iterator[Tuple[Feature, Address]]:
|
|||||||
yield Format(FORMAT_FREEZE), NO_ADDRESS
|
yield Format(FORMAT_FREEZE), NO_ADDRESS
|
||||||
elif buf.startswith(MATCH_RESULT):
|
elif buf.startswith(MATCH_RESULT):
|
||||||
yield Format(FORMAT_RESULT), NO_ADDRESS
|
yield Format(FORMAT_RESULT), NO_ADDRESS
|
||||||
|
elif re.sub(rb"\s", b"", buf[:20]).startswith(MATCH_JSON_OBJECT):
|
||||||
|
# potential start of JSON object data without whitespace
|
||||||
|
# we don't know what it is exactly, but may support it (e.g. a dynamic CAPE sandbox report)
|
||||||
|
# skip verdict here and let subsequent code analyze this further
|
||||||
|
return
|
||||||
else:
|
else:
|
||||||
# we likely end up here:
|
# we likely end up here:
|
||||||
# 1. handling a file format (e.g. macho)
|
# 1. handling a file format (e.g. macho)
|
||||||
#
|
#
|
||||||
# for (1), this logic will need to be updated as the format is implemented.
|
# for (1), this logic will need to be updated as the format is implemented.
|
||||||
logger.debug("unsupported file format: %s", binascii.hexlify(buf[:4]).decode("ascii"))
|
logger.debug("unknown file format: %s", buf[:4].hex())
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
# Copyright (C) 2022 Mandiant, Inc. All Rights Reserved.
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
# you may not use this file except in compliance with the License.
|
# you may not use this file except in compliance with the License.
|
||||||
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
||||||
@@ -22,7 +22,13 @@ import capa.features.extractors.dnfile.function
|
|||||||
from capa.features.common import Feature
|
from capa.features.common import Feature
|
||||||
from capa.features.address import NO_ADDRESS, Address, DNTokenAddress, DNTokenOffsetAddress
|
from capa.features.address import NO_ADDRESS, Address, DNTokenAddress, DNTokenOffsetAddress
|
||||||
from capa.features.extractors.dnfile.types import DnType, DnUnmanagedMethod
|
from capa.features.extractors.dnfile.types import DnType, DnUnmanagedMethod
|
||||||
from capa.features.extractors.base_extractor import BBHandle, InsnHandle, FunctionHandle, FeatureExtractor
|
from capa.features.extractors.base_extractor import (
|
||||||
|
BBHandle,
|
||||||
|
InsnHandle,
|
||||||
|
SampleHashes,
|
||||||
|
FunctionHandle,
|
||||||
|
StaticFeatureExtractor,
|
||||||
|
)
|
||||||
from capa.features.extractors.dnfile.helpers import (
|
from capa.features.extractors.dnfile.helpers import (
|
||||||
get_dotnet_types,
|
get_dotnet_types,
|
||||||
get_dotnet_fields,
|
get_dotnet_fields,
|
||||||
@@ -68,10 +74,10 @@ class DnFileFeatureExtractorCache:
|
|||||||
return self.types.get(token)
|
return self.types.get(token)
|
||||||
|
|
||||||
|
|
||||||
class DnfileFeatureExtractor(FeatureExtractor):
|
class DnfileFeatureExtractor(StaticFeatureExtractor):
|
||||||
def __init__(self, path: Path):
|
def __init__(self, path: Path):
|
||||||
super().__init__()
|
|
||||||
self.pe: dnfile.dnPE = dnfile.dnPE(str(path))
|
self.pe: dnfile.dnPE = dnfile.dnPE(str(path))
|
||||||
|
super().__init__(hashes=SampleHashes.from_bytes(path.read_bytes()))
|
||||||
|
|
||||||
# pre-compute .NET token lookup tables; each .NET method has access to this cache for feature extraction
|
# pre-compute .NET token lookup tables; each .NET method has access to this cache for feature extraction
|
||||||
# most relevant at instruction scope
|
# most relevant at instruction scope
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
# Copyright (C) 2022 Mandiant, Inc. All Rights Reserved.
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
# you may not use this file except in compliance with the License.
|
# you may not use this file except in compliance with the License.
|
||||||
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
# Copyright (C) 2022 Mandiant, Inc. All Rights Reserved.
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
# you may not use this file except in compliance with the License.
|
# you may not use this file except in compliance with the License.
|
||||||
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
# Copyright (C) 2022 Mandiant, Inc. All Rights Reserved.
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
# you may not use this file except in compliance with the License.
|
# you may not use this file except in compliance with the License.
|
||||||
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
||||||
@@ -83,7 +83,7 @@ def read_dotnet_user_string(pe: dnfile.dnPE, token: StringToken) -> Optional[str
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
try:
|
try:
|
||||||
user_string: Optional[dnfile.stream.UserString] = pe.net.user_strings.get_us(token.rid)
|
user_string: Optional[dnfile.stream.UserString] = pe.net.user_strings.get(token.rid)
|
||||||
except UnicodeDecodeError as e:
|
except UnicodeDecodeError as e:
|
||||||
logger.debug("failed to decode #US stream index 0x%08x (%s)", token.rid, e)
|
logger.debug("failed to decode #US stream index 0x%08x (%s)", token.rid, e)
|
||||||
return None
|
return None
|
||||||
@@ -119,22 +119,26 @@ def get_dotnet_managed_imports(pe: dnfile.dnPE) -> Iterator[DnType]:
|
|||||||
access: Optional[str]
|
access: Optional[str]
|
||||||
|
|
||||||
# assume .NET imports starting with get_/set_ are used to access a property
|
# assume .NET imports starting with get_/set_ are used to access a property
|
||||||
if member_ref.Name.startswith("get_"):
|
member_ref_name: str = str(member_ref.Name)
|
||||||
|
if member_ref_name.startswith("get_"):
|
||||||
access = FeatureAccess.READ
|
access = FeatureAccess.READ
|
||||||
elif member_ref.Name.startswith("set_"):
|
elif member_ref_name.startswith("set_"):
|
||||||
access = FeatureAccess.WRITE
|
access = FeatureAccess.WRITE
|
||||||
else:
|
else:
|
||||||
access = None
|
access = None
|
||||||
|
|
||||||
member_ref_name: str = member_ref.Name
|
|
||||||
if member_ref_name.startswith(("get_", "set_")):
|
if member_ref_name.startswith(("get_", "set_")):
|
||||||
# remove get_/set_ from MemberRef name
|
# remove get_/set_ from MemberRef name
|
||||||
member_ref_name = member_ref_name[4:]
|
member_ref_name = member_ref_name[4:]
|
||||||
|
|
||||||
|
typerefnamespace, typerefname = resolve_nested_typeref_name(
|
||||||
|
member_ref.Class.row_index, member_ref.Class.row, pe
|
||||||
|
)
|
||||||
|
|
||||||
yield DnType(
|
yield DnType(
|
||||||
token,
|
token,
|
||||||
member_ref.Class.row.TypeName,
|
typerefname,
|
||||||
namespace=member_ref.Class.row.TypeNamespace,
|
namespace=typerefnamespace,
|
||||||
member=member_ref_name,
|
member=member_ref_name,
|
||||||
access=access,
|
access=access,
|
||||||
)
|
)
|
||||||
@@ -188,6 +192,8 @@ def get_dotnet_managed_methods(pe: dnfile.dnPE) -> Iterator[DnType]:
|
|||||||
TypeNamespace (index into String heap)
|
TypeNamespace (index into String heap)
|
||||||
MethodList (index into MethodDef table; it marks the first of a contiguous run of Methods owned by this Type)
|
MethodList (index into MethodDef table; it marks the first of a contiguous run of Methods owned by this Type)
|
||||||
"""
|
"""
|
||||||
|
nested_class_table = get_dotnet_nested_class_table_index(pe)
|
||||||
|
|
||||||
accessor_map: Dict[int, str] = {}
|
accessor_map: Dict[int, str] = {}
|
||||||
for methoddef, methoddef_access in get_dotnet_methoddef_property_accessors(pe):
|
for methoddef, methoddef_access in get_dotnet_methoddef_property_accessors(pe):
|
||||||
accessor_map[methoddef] = methoddef_access
|
accessor_map[methoddef] = methoddef_access
|
||||||
@@ -206,12 +212,14 @@ def get_dotnet_managed_methods(pe: dnfile.dnPE) -> Iterator[DnType]:
|
|||||||
token: int = calculate_dotnet_token_value(method.table.number, method.row_index)
|
token: int = calculate_dotnet_token_value(method.table.number, method.row_index)
|
||||||
access: Optional[str] = accessor_map.get(token)
|
access: Optional[str] = accessor_map.get(token)
|
||||||
|
|
||||||
method_name: str = method.row.Name
|
method_name: str = str(method.row.Name)
|
||||||
if method_name.startswith(("get_", "set_")):
|
if method_name.startswith(("get_", "set_")):
|
||||||
# remove get_/set_
|
# remove get_/set_
|
||||||
method_name = method_name[4:]
|
method_name = method_name[4:]
|
||||||
|
|
||||||
yield DnType(token, typedef.TypeName, namespace=typedef.TypeNamespace, member=method_name, access=access)
|
typedefnamespace, typedefname = resolve_nested_typedef_name(nested_class_table, rid, typedef, pe)
|
||||||
|
|
||||||
|
yield DnType(token, typedefname, namespace=typedefnamespace, member=method_name, access=access)
|
||||||
|
|
||||||
|
|
||||||
def get_dotnet_fields(pe: dnfile.dnPE) -> Iterator[DnType]:
|
def get_dotnet_fields(pe: dnfile.dnPE) -> Iterator[DnType]:
|
||||||
@@ -225,6 +233,8 @@ def get_dotnet_fields(pe: dnfile.dnPE) -> Iterator[DnType]:
|
|||||||
TypeNamespace (index into String heap)
|
TypeNamespace (index into String heap)
|
||||||
FieldList (index into Field table; it marks the first of a contiguous run of Fields owned by this Type)
|
FieldList (index into Field table; it marks the first of a contiguous run of Fields owned by this Type)
|
||||||
"""
|
"""
|
||||||
|
nested_class_table = get_dotnet_nested_class_table_index(pe)
|
||||||
|
|
||||||
for rid, typedef in iter_dotnet_table(pe, dnfile.mdtable.TypeDef.number):
|
for rid, typedef in iter_dotnet_table(pe, dnfile.mdtable.TypeDef.number):
|
||||||
assert isinstance(typedef, dnfile.mdtable.TypeDefRow)
|
assert isinstance(typedef, dnfile.mdtable.TypeDefRow)
|
||||||
|
|
||||||
@@ -235,8 +245,11 @@ def get_dotnet_fields(pe: dnfile.dnPE) -> Iterator[DnType]:
|
|||||||
if field.row is None:
|
if field.row is None:
|
||||||
logger.debug("TypeDef[0x%X] FieldList[0x%X] row is None", rid, idx)
|
logger.debug("TypeDef[0x%X] FieldList[0x%X] row is None", rid, idx)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
typedefnamespace, typedefname = resolve_nested_typedef_name(nested_class_table, rid, typedef, pe)
|
||||||
|
|
||||||
token: int = calculate_dotnet_token_value(field.table.number, field.row_index)
|
token: int = calculate_dotnet_token_value(field.table.number, field.row_index)
|
||||||
yield DnType(token, typedef.TypeName, namespace=typedef.TypeNamespace, member=field.row.Name)
|
yield DnType(token, typedefname, namespace=typedefnamespace, member=field.row.Name)
|
||||||
|
|
||||||
|
|
||||||
def get_dotnet_managed_method_bodies(pe: dnfile.dnPE) -> Iterator[Tuple[int, CilMethodBody]]:
|
def get_dotnet_managed_method_bodies(pe: dnfile.dnPE) -> Iterator[Tuple[int, CilMethodBody]]:
|
||||||
@@ -276,8 +289,8 @@ def get_dotnet_unmanaged_imports(pe: dnfile.dnPE) -> Iterator[DnUnmanagedMethod]
|
|||||||
logger.debug("ImplMap[0x%X] ImportScope row is None", rid)
|
logger.debug("ImplMap[0x%X] ImportScope row is None", rid)
|
||||||
module = ""
|
module = ""
|
||||||
else:
|
else:
|
||||||
module = impl_map.ImportScope.row.Name
|
module = str(impl_map.ImportScope.row.Name)
|
||||||
method: str = impl_map.ImportName
|
method: str = str(impl_map.ImportName)
|
||||||
|
|
||||||
member_forward_table: int
|
member_forward_table: int
|
||||||
if impl_map.MemberForwarded.table is None:
|
if impl_map.MemberForwarded.table is None:
|
||||||
@@ -300,19 +313,122 @@ def get_dotnet_unmanaged_imports(pe: dnfile.dnPE) -> Iterator[DnUnmanagedMethod]
|
|||||||
yield DnUnmanagedMethod(token, module, method)
|
yield DnUnmanagedMethod(token, module, method)
|
||||||
|
|
||||||
|
|
||||||
|
def get_dotnet_table_row(pe: dnfile.dnPE, table_index: int, row_index: int) -> Optional[dnfile.base.MDTableRow]:
|
||||||
|
assert pe.net is not None
|
||||||
|
assert pe.net.mdtables is not None
|
||||||
|
|
||||||
|
if row_index - 1 <= 0:
|
||||||
|
return None
|
||||||
|
|
||||||
|
table: Optional[dnfile.base.ClrMetaDataTable] = pe.net.mdtables.tables.get(table_index)
|
||||||
|
if table is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
try:
|
||||||
|
return table[row_index - 1]
|
||||||
|
except IndexError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_nested_typedef_name(
|
||||||
|
nested_class_table: dict, index: int, typedef: dnfile.mdtable.TypeDefRow, pe: dnfile.dnPE
|
||||||
|
) -> Tuple[str, Tuple[str, ...]]:
|
||||||
|
"""Resolves all nested TypeDef class names. Returns the namespace as a str and the nested TypeRef name as a tuple"""
|
||||||
|
|
||||||
|
if index in nested_class_table:
|
||||||
|
typedef_name = []
|
||||||
|
name = str(typedef.TypeName)
|
||||||
|
|
||||||
|
# Append the current typedef name
|
||||||
|
typedef_name.append(name)
|
||||||
|
|
||||||
|
while nested_class_table[index] in nested_class_table:
|
||||||
|
# Iterate through the typedef table to resolve the nested name
|
||||||
|
table_row = get_dotnet_table_row(pe, dnfile.mdtable.TypeDef.number, nested_class_table[index])
|
||||||
|
if table_row is None:
|
||||||
|
return str(typedef.TypeNamespace), tuple(typedef_name[::-1])
|
||||||
|
|
||||||
|
name = str(table_row.TypeName)
|
||||||
|
typedef_name.append(name)
|
||||||
|
index = nested_class_table[index]
|
||||||
|
|
||||||
|
# Document the root enclosing details
|
||||||
|
table_row = get_dotnet_table_row(pe, dnfile.mdtable.TypeDef.number, nested_class_table[index])
|
||||||
|
if table_row is None:
|
||||||
|
return str(typedef.TypeNamespace), tuple(typedef_name[::-1])
|
||||||
|
|
||||||
|
enclosing_name = str(table_row.TypeName)
|
||||||
|
typedef_name.append(enclosing_name)
|
||||||
|
|
||||||
|
return str(table_row.TypeNamespace), tuple(typedef_name[::-1])
|
||||||
|
|
||||||
|
else:
|
||||||
|
return str(typedef.TypeNamespace), (str(typedef.TypeName),)
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_nested_typeref_name(
|
||||||
|
index: int, typeref: dnfile.mdtable.TypeRefRow, pe: dnfile.dnPE
|
||||||
|
) -> Tuple[str, Tuple[str, ...]]:
|
||||||
|
"""Resolves all nested TypeRef class names. Returns the namespace as a str and the nested TypeRef name as a tuple"""
|
||||||
|
# If the ResolutionScope decodes to a typeRef type then it is nested
|
||||||
|
if isinstance(typeref.ResolutionScope.table, dnfile.mdtable.TypeRef):
|
||||||
|
typeref_name = []
|
||||||
|
name = str(typeref.TypeName)
|
||||||
|
# Not appending the current typeref name to avoid potential duplicate
|
||||||
|
|
||||||
|
# Validate index
|
||||||
|
table_row = get_dotnet_table_row(pe, dnfile.mdtable.TypeRef.number, index)
|
||||||
|
if table_row is None:
|
||||||
|
return str(typeref.TypeNamespace), (str(typeref.TypeName),)
|
||||||
|
|
||||||
|
while isinstance(table_row.ResolutionScope.table, dnfile.mdtable.TypeRef):
|
||||||
|
# Iterate through the typeref table to resolve the nested name
|
||||||
|
typeref_name.append(name)
|
||||||
|
name = str(table_row.TypeName)
|
||||||
|
table_row = get_dotnet_table_row(pe, dnfile.mdtable.TypeRef.number, table_row.ResolutionScope.row_index)
|
||||||
|
if table_row is None:
|
||||||
|
return str(typeref.TypeNamespace), tuple(typeref_name[::-1])
|
||||||
|
|
||||||
|
# Document the root enclosing details
|
||||||
|
typeref_name.append(str(table_row.TypeName))
|
||||||
|
|
||||||
|
return str(table_row.TypeNamespace), tuple(typeref_name[::-1])
|
||||||
|
|
||||||
|
else:
|
||||||
|
return str(typeref.TypeNamespace), (str(typeref.TypeName),)
|
||||||
|
|
||||||
|
|
||||||
|
def get_dotnet_nested_class_table_index(pe: dnfile.dnPE) -> Dict[int, int]:
|
||||||
|
"""Build index for EnclosingClass based off the NestedClass row index in the nestedclass table"""
|
||||||
|
nested_class_table = {}
|
||||||
|
|
||||||
|
# Used to find nested classes in typedef
|
||||||
|
for _, nestedclass in iter_dotnet_table(pe, dnfile.mdtable.NestedClass.number):
|
||||||
|
assert isinstance(nestedclass, dnfile.mdtable.NestedClassRow)
|
||||||
|
nested_class_table[nestedclass.NestedClass.row_index] = nestedclass.EnclosingClass.row_index
|
||||||
|
|
||||||
|
return nested_class_table
|
||||||
|
|
||||||
|
|
||||||
def get_dotnet_types(pe: dnfile.dnPE) -> Iterator[DnType]:
|
def get_dotnet_types(pe: dnfile.dnPE) -> Iterator[DnType]:
|
||||||
"""get .NET types from TypeDef and TypeRef tables"""
|
"""get .NET types from TypeDef and TypeRef tables"""
|
||||||
|
nested_class_table = get_dotnet_nested_class_table_index(pe)
|
||||||
|
|
||||||
for rid, typedef in iter_dotnet_table(pe, dnfile.mdtable.TypeDef.number):
|
for rid, typedef in iter_dotnet_table(pe, dnfile.mdtable.TypeDef.number):
|
||||||
assert isinstance(typedef, dnfile.mdtable.TypeDefRow)
|
assert isinstance(typedef, dnfile.mdtable.TypeDefRow)
|
||||||
|
|
||||||
|
typedefnamespace, typedefname = resolve_nested_typedef_name(nested_class_table, rid, typedef, pe)
|
||||||
|
|
||||||
typedef_token: int = calculate_dotnet_token_value(dnfile.mdtable.TypeDef.number, rid)
|
typedef_token: int = calculate_dotnet_token_value(dnfile.mdtable.TypeDef.number, rid)
|
||||||
yield DnType(typedef_token, typedef.TypeName, namespace=typedef.TypeNamespace)
|
yield DnType(typedef_token, typedefname, namespace=typedefnamespace)
|
||||||
|
|
||||||
for rid, typeref in iter_dotnet_table(pe, dnfile.mdtable.TypeRef.number):
|
for rid, typeref in iter_dotnet_table(pe, dnfile.mdtable.TypeRef.number):
|
||||||
assert isinstance(typeref, dnfile.mdtable.TypeRefRow)
|
assert isinstance(typeref, dnfile.mdtable.TypeRefRow)
|
||||||
|
|
||||||
|
typerefnamespace, typerefname = resolve_nested_typeref_name(typeref.ResolutionScope.row_index, typeref, pe)
|
||||||
|
|
||||||
typeref_token: int = calculate_dotnet_token_value(dnfile.mdtable.TypeRef.number, rid)
|
typeref_token: int = calculate_dotnet_token_value(dnfile.mdtable.TypeRef.number, rid)
|
||||||
yield DnType(typeref_token, typeref.TypeName, namespace=typeref.TypeNamespace)
|
yield DnType(typeref_token, typerefname, namespace=typerefnamespace)
|
||||||
|
|
||||||
|
|
||||||
def calculate_dotnet_token_value(table: int, rid: int) -> int:
|
def calculate_dotnet_token_value(table: int, rid: int) -> int:
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
# Copyright (C) 2022 Mandiant, Inc. All Rights Reserved.
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
# you may not use this file except in compliance with the License.
|
# you may not use this file except in compliance with the License.
|
||||||
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
# Copyright (C) 2022 Mandiant, Inc. All Rights Reserved.
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
# you may not use this file except in compliance with the License.
|
# you may not use this file except in compliance with the License.
|
||||||
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
||||||
@@ -6,15 +6,17 @@
|
|||||||
# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
# 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.
|
# See the License for the specific language governing permissions and limitations under the License.
|
||||||
|
|
||||||
from typing import Optional
|
from typing import Tuple, Optional
|
||||||
|
|
||||||
|
|
||||||
class DnType:
|
class DnType:
|
||||||
def __init__(self, token: int, class_: str, namespace: str = "", member: str = "", access: Optional[str] = None):
|
def __init__(
|
||||||
|
self, token: int, class_: Tuple[str, ...], namespace: str = "", member: str = "", access: Optional[str] = None
|
||||||
|
):
|
||||||
self.token: int = token
|
self.token: int = token
|
||||||
self.access: Optional[str] = access
|
self.access: Optional[str] = access
|
||||||
self.namespace: str = namespace
|
self.namespace: str = namespace
|
||||||
self.class_: str = class_
|
self.class_: Tuple[str, ...] = class_
|
||||||
|
|
||||||
if member == ".ctor":
|
if member == ".ctor":
|
||||||
member = "ctor"
|
member = "ctor"
|
||||||
@@ -42,9 +44,13 @@ class DnType:
|
|||||||
return str(self)
|
return str(self)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def format_name(class_: str, namespace: str = "", member: str = ""):
|
def format_name(class_: Tuple[str, ...], namespace: str = "", member: str = ""):
|
||||||
|
if len(class_) > 1:
|
||||||
|
class_str = "/".join(class_) # Concat items in tuple, separated by a "/"
|
||||||
|
else:
|
||||||
|
class_str = "".join(class_) # Convert tuple to str
|
||||||
# like File::OpenRead
|
# like File::OpenRead
|
||||||
name: str = f"{class_}::{member}" if member else class_
|
name: str = f"{class_str}::{member}" if member else class_str
|
||||||
if namespace:
|
if namespace:
|
||||||
# like System.IO.File::OpenRead
|
# like System.IO.File::OpenRead
|
||||||
name = f"{namespace}.{name}"
|
name = f"{namespace}.{name}"
|
||||||
|
|||||||
@@ -1,158 +0,0 @@
|
|||||||
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
|
||||||
# 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: [package root]/LICENSE.txt
|
|
||||||
# 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.
|
|
||||||
import logging
|
|
||||||
from typing import Tuple, Iterator
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import dnfile
|
|
||||||
import pefile
|
|
||||||
|
|
||||||
from capa.features.common import (
|
|
||||||
OS,
|
|
||||||
OS_ANY,
|
|
||||||
ARCH_ANY,
|
|
||||||
ARCH_I386,
|
|
||||||
FORMAT_PE,
|
|
||||||
ARCH_AMD64,
|
|
||||||
FORMAT_DOTNET,
|
|
||||||
Arch,
|
|
||||||
Format,
|
|
||||||
Feature,
|
|
||||||
)
|
|
||||||
from capa.features.address import NO_ADDRESS, Address, AbsoluteVirtualAddress
|
|
||||||
from capa.features.extractors.base_extractor import FeatureExtractor
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
def extract_file_format(**kwargs) -> Iterator[Tuple[Feature, Address]]:
|
|
||||||
yield Format(FORMAT_PE), NO_ADDRESS
|
|
||||||
yield Format(FORMAT_DOTNET), NO_ADDRESS
|
|
||||||
|
|
||||||
|
|
||||||
def extract_file_os(**kwargs) -> Iterator[Tuple[Feature, Address]]:
|
|
||||||
yield OS(OS_ANY), NO_ADDRESS
|
|
||||||
|
|
||||||
|
|
||||||
def extract_file_arch(pe: dnfile.dnPE, **kwargs) -> Iterator[Tuple[Feature, Address]]:
|
|
||||||
# to distinguish in more detail, see https://stackoverflow.com/a/23614024/10548020
|
|
||||||
# .NET 4.5 added option: any CPU, 32-bit preferred
|
|
||||||
assert pe.net is not None
|
|
||||||
assert pe.net.Flags is not None
|
|
||||||
|
|
||||||
if pe.net.Flags.CLR_32BITREQUIRED and pe.PE_TYPE == pefile.OPTIONAL_HEADER_MAGIC_PE:
|
|
||||||
yield Arch(ARCH_I386), NO_ADDRESS
|
|
||||||
elif not pe.net.Flags.CLR_32BITREQUIRED and pe.PE_TYPE == pefile.OPTIONAL_HEADER_MAGIC_PE_PLUS:
|
|
||||||
yield Arch(ARCH_AMD64), NO_ADDRESS
|
|
||||||
else:
|
|
||||||
yield Arch(ARCH_ANY), NO_ADDRESS
|
|
||||||
|
|
||||||
|
|
||||||
def extract_file_features(pe: dnfile.dnPE) -> Iterator[Tuple[Feature, Address]]:
|
|
||||||
for file_handler in FILE_HANDLERS:
|
|
||||||
for feature, address in file_handler(pe=pe): # type: ignore
|
|
||||||
yield feature, address
|
|
||||||
|
|
||||||
|
|
||||||
FILE_HANDLERS = (
|
|
||||||
# extract_file_export_names,
|
|
||||||
# extract_file_import_names,
|
|
||||||
# extract_file_section_names,
|
|
||||||
# extract_file_strings,
|
|
||||||
# extract_file_function_names,
|
|
||||||
extract_file_format,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def extract_global_features(pe: dnfile.dnPE) -> Iterator[Tuple[Feature, Address]]:
|
|
||||||
for handler in GLOBAL_HANDLERS:
|
|
||||||
for feature, addr in handler(pe=pe): # type: ignore
|
|
||||||
yield feature, addr
|
|
||||||
|
|
||||||
|
|
||||||
GLOBAL_HANDLERS = (
|
|
||||||
extract_file_os,
|
|
||||||
extract_file_arch,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class DnfileFeatureExtractor(FeatureExtractor):
|
|
||||||
def __init__(self, path: Path):
|
|
||||||
super().__init__()
|
|
||||||
self.path: Path = path
|
|
||||||
self.pe: dnfile.dnPE = dnfile.dnPE(str(path))
|
|
||||||
|
|
||||||
def get_base_address(self) -> AbsoluteVirtualAddress:
|
|
||||||
return AbsoluteVirtualAddress(0x0)
|
|
||||||
|
|
||||||
def get_entry_point(self) -> int:
|
|
||||||
# self.pe.net.Flags.CLT_NATIVE_ENTRYPOINT
|
|
||||||
# True: native EP: Token
|
|
||||||
# False: managed EP: RVA
|
|
||||||
assert self.pe.net is not None
|
|
||||||
assert self.pe.net.struct is not None
|
|
||||||
|
|
||||||
return self.pe.net.struct.EntryPointTokenOrRva
|
|
||||||
|
|
||||||
def extract_global_features(self):
|
|
||||||
yield from extract_global_features(self.pe)
|
|
||||||
|
|
||||||
def extract_file_features(self):
|
|
||||||
yield from extract_file_features(self.pe)
|
|
||||||
|
|
||||||
def is_dotnet_file(self) -> bool:
|
|
||||||
return bool(self.pe.net)
|
|
||||||
|
|
||||||
def is_mixed_mode(self) -> bool:
|
|
||||||
assert self.pe is not None
|
|
||||||
assert self.pe.net is not None
|
|
||||||
assert self.pe.net.Flags is not None
|
|
||||||
|
|
||||||
return not bool(self.pe.net.Flags.CLR_ILONLY)
|
|
||||||
|
|
||||||
def get_runtime_version(self) -> Tuple[int, int]:
|
|
||||||
assert self.pe is not None
|
|
||||||
assert self.pe.net is not None
|
|
||||||
assert self.pe.net.struct is not None
|
|
||||||
|
|
||||||
return self.pe.net.struct.MajorRuntimeVersion, self.pe.net.struct.MinorRuntimeVersion
|
|
||||||
|
|
||||||
def get_meta_version_string(self) -> str:
|
|
||||||
assert self.pe.net is not None
|
|
||||||
assert self.pe.net.metadata is not None
|
|
||||||
assert self.pe.net.metadata.struct is not None
|
|
||||||
assert self.pe.net.metadata.struct.Version is not None
|
|
||||||
|
|
||||||
vbuf = self.pe.net.metadata.struct.Version
|
|
||||||
assert isinstance(vbuf, bytes)
|
|
||||||
|
|
||||||
return vbuf.rstrip(b"\x00").decode("utf-8")
|
|
||||||
|
|
||||||
def get_functions(self):
|
|
||||||
raise NotImplementedError("DnfileFeatureExtractor can only be used to extract file features")
|
|
||||||
|
|
||||||
def extract_function_features(self, f):
|
|
||||||
raise NotImplementedError("DnfileFeatureExtractor can only be used to extract file features")
|
|
||||||
|
|
||||||
def get_basic_blocks(self, f):
|
|
||||||
raise NotImplementedError("DnfileFeatureExtractor can only be used to extract file features")
|
|
||||||
|
|
||||||
def extract_basic_block_features(self, f, bb):
|
|
||||||
raise NotImplementedError("DnfileFeatureExtractor can only be used to extract file features")
|
|
||||||
|
|
||||||
def get_instructions(self, f, bb):
|
|
||||||
raise NotImplementedError("DnfileFeatureExtractor can only be used to extract file features")
|
|
||||||
|
|
||||||
def extract_insn_features(self, f, bb, insn):
|
|
||||||
raise NotImplementedError("DnfileFeatureExtractor can only be used to extract file features")
|
|
||||||
|
|
||||||
def is_library_function(self, va):
|
|
||||||
raise NotImplementedError("DnfileFeatureExtractor can only be used to extract file features")
|
|
||||||
|
|
||||||
def get_function_name(self, va):
|
|
||||||
raise NotImplementedError("DnfileFeatureExtractor can only be used to extract file features")
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
# Copyright (C) 2022 Mandiant, Inc. All Rights Reserved.
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
# you may not use this file except in compliance with the License.
|
# you may not use this file except in compliance with the License.
|
||||||
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
||||||
@@ -31,23 +31,26 @@ from capa.features.common import (
|
|||||||
Characteristic,
|
Characteristic,
|
||||||
)
|
)
|
||||||
from capa.features.address import NO_ADDRESS, Address, DNTokenAddress
|
from capa.features.address import NO_ADDRESS, Address, DNTokenAddress
|
||||||
from capa.features.extractors.base_extractor import FeatureExtractor
|
from capa.features.extractors.dnfile.types import DnType
|
||||||
|
from capa.features.extractors.base_extractor import SampleHashes, StaticFeatureExtractor
|
||||||
from capa.features.extractors.dnfile.helpers import (
|
from capa.features.extractors.dnfile.helpers import (
|
||||||
DnType,
|
|
||||||
iter_dotnet_table,
|
iter_dotnet_table,
|
||||||
is_dotnet_mixed_mode,
|
is_dotnet_mixed_mode,
|
||||||
get_dotnet_managed_imports,
|
get_dotnet_managed_imports,
|
||||||
get_dotnet_managed_methods,
|
get_dotnet_managed_methods,
|
||||||
|
resolve_nested_typedef_name,
|
||||||
|
resolve_nested_typeref_name,
|
||||||
calculate_dotnet_token_value,
|
calculate_dotnet_token_value,
|
||||||
get_dotnet_unmanaged_imports,
|
get_dotnet_unmanaged_imports,
|
||||||
|
get_dotnet_nested_class_table_index,
|
||||||
)
|
)
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def extract_file_format(**kwargs) -> Iterator[Tuple[Format, Address]]:
|
def extract_file_format(**kwargs) -> Iterator[Tuple[Format, Address]]:
|
||||||
yield Format(FORMAT_PE), NO_ADDRESS
|
|
||||||
yield Format(FORMAT_DOTNET), NO_ADDRESS
|
yield Format(FORMAT_DOTNET), NO_ADDRESS
|
||||||
|
yield Format(FORMAT_PE), NO_ADDRESS
|
||||||
|
|
||||||
|
|
||||||
def extract_file_import_names(pe: dnfile.dnPE, **kwargs) -> Iterator[Tuple[Import, Address]]:
|
def extract_file_import_names(pe: dnfile.dnPE, **kwargs) -> Iterator[Tuple[Import, Address]]:
|
||||||
@@ -57,7 +60,7 @@ def extract_file_import_names(pe: dnfile.dnPE, **kwargs) -> Iterator[Tuple[Impor
|
|||||||
|
|
||||||
for imp in get_dotnet_unmanaged_imports(pe):
|
for imp in get_dotnet_unmanaged_imports(pe):
|
||||||
# like kernel32.CreateFileA
|
# like kernel32.CreateFileA
|
||||||
for name in capa.features.extractors.helpers.generate_symbols(imp.module, imp.method):
|
for name in capa.features.extractors.helpers.generate_symbols(imp.module, imp.method, include_dll=True):
|
||||||
yield Import(name), DNTokenAddress(imp.token)
|
yield Import(name), DNTokenAddress(imp.token)
|
||||||
|
|
||||||
|
|
||||||
@@ -75,12 +78,12 @@ def extract_file_namespace_features(pe: dnfile.dnPE, **kwargs) -> Iterator[Tuple
|
|||||||
for _, typedef in iter_dotnet_table(pe, dnfile.mdtable.TypeDef.number):
|
for _, typedef in iter_dotnet_table(pe, dnfile.mdtable.TypeDef.number):
|
||||||
# emit internal .NET namespaces
|
# emit internal .NET namespaces
|
||||||
assert isinstance(typedef, dnfile.mdtable.TypeDefRow)
|
assert isinstance(typedef, dnfile.mdtable.TypeDefRow)
|
||||||
namespaces.add(typedef.TypeNamespace)
|
namespaces.add(str(typedef.TypeNamespace))
|
||||||
|
|
||||||
for _, typeref in iter_dotnet_table(pe, dnfile.mdtable.TypeRef.number):
|
for _, typeref in iter_dotnet_table(pe, dnfile.mdtable.TypeRef.number):
|
||||||
# emit external .NET namespaces
|
# emit external .NET namespaces
|
||||||
assert isinstance(typeref, dnfile.mdtable.TypeRefRow)
|
assert isinstance(typeref, dnfile.mdtable.TypeRefRow)
|
||||||
namespaces.add(typeref.TypeNamespace)
|
namespaces.add(str(typeref.TypeNamespace))
|
||||||
|
|
||||||
# namespaces may be empty, discard
|
# namespaces may be empty, discard
|
||||||
namespaces.discard("")
|
namespaces.discard("")
|
||||||
@@ -92,19 +95,25 @@ def extract_file_namespace_features(pe: dnfile.dnPE, **kwargs) -> Iterator[Tuple
|
|||||||
|
|
||||||
def extract_file_class_features(pe: dnfile.dnPE, **kwargs) -> Iterator[Tuple[Class, Address]]:
|
def extract_file_class_features(pe: dnfile.dnPE, **kwargs) -> Iterator[Tuple[Class, Address]]:
|
||||||
"""emit class features from TypeRef and TypeDef tables"""
|
"""emit class features from TypeRef and TypeDef tables"""
|
||||||
|
nested_class_table = get_dotnet_nested_class_table_index(pe)
|
||||||
|
|
||||||
for rid, typedef in iter_dotnet_table(pe, dnfile.mdtable.TypeDef.number):
|
for rid, typedef in iter_dotnet_table(pe, dnfile.mdtable.TypeDef.number):
|
||||||
# emit internal .NET classes
|
# emit internal .NET classes
|
||||||
assert isinstance(typedef, dnfile.mdtable.TypeDefRow)
|
assert isinstance(typedef, dnfile.mdtable.TypeDefRow)
|
||||||
|
|
||||||
|
typedefnamespace, typedefname = resolve_nested_typedef_name(nested_class_table, rid, typedef, pe)
|
||||||
|
|
||||||
token = calculate_dotnet_token_value(dnfile.mdtable.TypeDef.number, rid)
|
token = calculate_dotnet_token_value(dnfile.mdtable.TypeDef.number, rid)
|
||||||
yield Class(DnType.format_name(typedef.TypeName, namespace=typedef.TypeNamespace)), DNTokenAddress(token)
|
yield Class(DnType.format_name(typedefname, namespace=typedefnamespace)), DNTokenAddress(token)
|
||||||
|
|
||||||
for rid, typeref in iter_dotnet_table(pe, dnfile.mdtable.TypeRef.number):
|
for rid, typeref in iter_dotnet_table(pe, dnfile.mdtable.TypeRef.number):
|
||||||
# emit external .NET classes
|
# emit external .NET classes
|
||||||
assert isinstance(typeref, dnfile.mdtable.TypeRefRow)
|
assert isinstance(typeref, dnfile.mdtable.TypeRefRow)
|
||||||
|
|
||||||
|
typerefnamespace, typerefname = resolve_nested_typeref_name(typeref.ResolutionScope.row_index, typeref, pe)
|
||||||
|
|
||||||
token = calculate_dotnet_token_value(dnfile.mdtable.TypeRef.number, rid)
|
token = calculate_dotnet_token_value(dnfile.mdtable.TypeRef.number, rid)
|
||||||
yield Class(DnType.format_name(typeref.TypeName, namespace=typeref.TypeNamespace)), DNTokenAddress(token)
|
yield Class(DnType.format_name(typerefname, namespace=typerefnamespace)), DNTokenAddress(token)
|
||||||
|
|
||||||
|
|
||||||
def extract_file_os(**kwargs) -> Iterator[Tuple[OS, Address]]:
|
def extract_file_os(**kwargs) -> Iterator[Tuple[OS, Address]]:
|
||||||
@@ -165,9 +174,9 @@ GLOBAL_HANDLERS = (
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class DotnetFileFeatureExtractor(FeatureExtractor):
|
class DotnetFileFeatureExtractor(StaticFeatureExtractor):
|
||||||
def __init__(self, path: Path):
|
def __init__(self, path: Path):
|
||||||
super().__init__()
|
super().__init__(hashes=SampleHashes.from_bytes(path.read_bytes()))
|
||||||
self.path: Path = path
|
self.path: Path = path
|
||||||
self.pe: dnfile.dnPE = dnfile.dnPE(str(path))
|
self.pe: dnfile.dnPE = dnfile.dnPE(str(path))
|
||||||
|
|
||||||
|
|||||||
58
capa/features/extractors/drakvuf/call.py
Normal file
58
capa/features/extractors/drakvuf/call.py
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
# Copyright (C) 2024 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Tuple, Iterator
|
||||||
|
|
||||||
|
import capa.features.extractors.helpers
|
||||||
|
from capa.features.insn import API, Number
|
||||||
|
from capa.features.common import String, Feature
|
||||||
|
from capa.features.address import Address
|
||||||
|
from capa.features.extractors.base_extractor import CallHandle, ThreadHandle, ProcessHandle
|
||||||
|
from capa.features.extractors.drakvuf.models import Call
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_call_features(ph: ProcessHandle, th: ThreadHandle, ch: CallHandle) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
"""
|
||||||
|
This method extracts the given call's features (such as API name and arguments),
|
||||||
|
and returns them as API, Number, and String features.
|
||||||
|
|
||||||
|
args:
|
||||||
|
ph: process handle (for defining the extraction scope)
|
||||||
|
th: thread handle (for defining the extraction scope)
|
||||||
|
ch: call handle (for defining the extraction scope)
|
||||||
|
|
||||||
|
yields:
|
||||||
|
Feature, address; where Feature is either: API, Number, or String.
|
||||||
|
"""
|
||||||
|
call: Call = ch.inner
|
||||||
|
|
||||||
|
# list similar to disassembly: arguments right-to-left, call
|
||||||
|
for arg_value in reversed(call.arguments.values()):
|
||||||
|
try:
|
||||||
|
yield Number(int(arg_value, 0)), ch.address
|
||||||
|
except ValueError:
|
||||||
|
# DRAKVUF automatically resolves the contents of memory addresses, (e.g. Arg1="0xc6f217efe0:\"ntdll.dll\"").
|
||||||
|
# For those cases we yield the entire string as it, since yielding the address only would
|
||||||
|
# likely not provide any matches, and yielding just the memory contentswould probably be misleading,
|
||||||
|
# but yielding the entire string would be helpful for an analyst looking at the verbose output
|
||||||
|
yield String(arg_value), ch.address
|
||||||
|
|
||||||
|
for name in capa.features.extractors.helpers.generate_symbols("", call.name):
|
||||||
|
yield API(name), ch.address
|
||||||
|
|
||||||
|
|
||||||
|
def extract_features(ph: ProcessHandle, th: ThreadHandle, ch: CallHandle) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
for handler in CALL_HANDLERS:
|
||||||
|
for feature, addr in handler(ph, th, ch):
|
||||||
|
yield feature, addr
|
||||||
|
|
||||||
|
|
||||||
|
CALL_HANDLERS = (extract_call_features,)
|
||||||
96
capa/features/extractors/drakvuf/extractor.py
Normal file
96
capa/features/extractors/drakvuf/extractor.py
Normal file
@@ -0,0 +1,96 @@
|
|||||||
|
# Copyright (C) 2024 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Dict, List, Tuple, Union, Iterator
|
||||||
|
|
||||||
|
import capa.features.extractors.drakvuf.call
|
||||||
|
import capa.features.extractors.drakvuf.file
|
||||||
|
import capa.features.extractors.drakvuf.thread
|
||||||
|
import capa.features.extractors.drakvuf.global_
|
||||||
|
import capa.features.extractors.drakvuf.process
|
||||||
|
from capa.features.common import Feature, Characteristic
|
||||||
|
from capa.features.address import NO_ADDRESS, Address, ThreadAddress, ProcessAddress, AbsoluteVirtualAddress, _NoAddress
|
||||||
|
from capa.features.extractors.base_extractor import (
|
||||||
|
CallHandle,
|
||||||
|
SampleHashes,
|
||||||
|
ThreadHandle,
|
||||||
|
ProcessHandle,
|
||||||
|
DynamicFeatureExtractor,
|
||||||
|
)
|
||||||
|
from capa.features.extractors.drakvuf.models import Call, DrakvufReport
|
||||||
|
from capa.features.extractors.drakvuf.helpers import index_calls
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class DrakvufExtractor(DynamicFeatureExtractor):
|
||||||
|
def __init__(self, report: DrakvufReport):
|
||||||
|
super().__init__(
|
||||||
|
# DRAKVUF currently does not yield hash information about the sample in its output
|
||||||
|
hashes=SampleHashes(md5="", sha1="", sha256="")
|
||||||
|
)
|
||||||
|
|
||||||
|
self.report: DrakvufReport = report
|
||||||
|
|
||||||
|
# sort the api calls to prevent going through the entire list each time
|
||||||
|
self.sorted_calls: Dict[ProcessAddress, Dict[ThreadAddress, List[Call]]] = index_calls(report)
|
||||||
|
|
||||||
|
# pre-compute these because we'll yield them at *every* scope.
|
||||||
|
self.global_features = list(capa.features.extractors.drakvuf.global_.extract_features(self.report))
|
||||||
|
|
||||||
|
def get_base_address(self) -> Union[AbsoluteVirtualAddress, _NoAddress, None]:
|
||||||
|
# DRAKVUF currently does not yield information about the PE's address
|
||||||
|
return NO_ADDRESS
|
||||||
|
|
||||||
|
def extract_global_features(self) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
yield from self.global_features
|
||||||
|
|
||||||
|
def extract_file_features(self) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
yield from capa.features.extractors.drakvuf.file.extract_features(self.report)
|
||||||
|
|
||||||
|
def get_processes(self) -> Iterator[ProcessHandle]:
|
||||||
|
yield from capa.features.extractors.drakvuf.file.get_processes(self.sorted_calls)
|
||||||
|
|
||||||
|
def extract_process_features(self, ph: ProcessHandle) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
yield from capa.features.extractors.drakvuf.process.extract_features(ph)
|
||||||
|
|
||||||
|
def get_process_name(self, ph: ProcessHandle) -> str:
|
||||||
|
return ph.inner["process_name"]
|
||||||
|
|
||||||
|
def get_threads(self, ph: ProcessHandle) -> Iterator[ThreadHandle]:
|
||||||
|
yield from capa.features.extractors.drakvuf.process.get_threads(self.sorted_calls, ph)
|
||||||
|
|
||||||
|
def extract_thread_features(self, ph: ProcessHandle, th: ThreadHandle) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
if False:
|
||||||
|
# force this routine to be a generator,
|
||||||
|
# but we don't actually have any elements to generate.
|
||||||
|
yield Characteristic("never"), NO_ADDRESS
|
||||||
|
return
|
||||||
|
|
||||||
|
def get_calls(self, ph: ProcessHandle, th: ThreadHandle) -> Iterator[CallHandle]:
|
||||||
|
yield from capa.features.extractors.drakvuf.thread.get_calls(self.sorted_calls, ph, th)
|
||||||
|
|
||||||
|
def get_call_name(self, ph: ProcessHandle, th: ThreadHandle, ch: CallHandle) -> str:
|
||||||
|
call: Call = ch.inner
|
||||||
|
call_name = "{}({}){}".format(
|
||||||
|
call.name,
|
||||||
|
", ".join(f"{arg_name}={arg_value}" for arg_name, arg_value in call.arguments.items()),
|
||||||
|
(f" -> {getattr(call, 'return_value', '')}"), # SysCalls don't have a return value, while WinApi calls do
|
||||||
|
)
|
||||||
|
return call_name
|
||||||
|
|
||||||
|
def extract_call_features(
|
||||||
|
self, ph: ProcessHandle, th: ThreadHandle, ch: CallHandle
|
||||||
|
) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
yield from capa.features.extractors.drakvuf.call.extract_features(ph, th, ch)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_report(cls, report: Iterator[Dict]) -> "DrakvufExtractor":
|
||||||
|
dr = DrakvufReport.from_raw_report(report)
|
||||||
|
return DrakvufExtractor(report=dr)
|
||||||
56
capa/features/extractors/drakvuf/file.py
Normal file
56
capa/features/extractors/drakvuf/file.py
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
# Copyright (C) 2024 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Dict, List, Tuple, Iterator
|
||||||
|
|
||||||
|
from capa.features.file import Import
|
||||||
|
from capa.features.common import Feature
|
||||||
|
from capa.features.address import Address, ThreadAddress, ProcessAddress, AbsoluteVirtualAddress
|
||||||
|
from capa.features.extractors.helpers import generate_symbols
|
||||||
|
from capa.features.extractors.base_extractor import ProcessHandle
|
||||||
|
from capa.features.extractors.drakvuf.models import Call, DrakvufReport
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def get_processes(calls: Dict[ProcessAddress, Dict[ThreadAddress, List[Call]]]) -> Iterator[ProcessHandle]:
|
||||||
|
"""
|
||||||
|
Get all the created processes for a sample.
|
||||||
|
"""
|
||||||
|
for proc_addr, calls_per_thread in calls.items():
|
||||||
|
sample_call = next(iter(calls_per_thread.values()))[0] # get process name
|
||||||
|
yield ProcessHandle(proc_addr, inner={"process_name": sample_call.process_name})
|
||||||
|
|
||||||
|
|
||||||
|
def extract_import_names(report: DrakvufReport) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
"""
|
||||||
|
Extract imported function names.
|
||||||
|
"""
|
||||||
|
if report.loaded_dlls is None:
|
||||||
|
return
|
||||||
|
dlls = report.loaded_dlls
|
||||||
|
|
||||||
|
for dll in dlls:
|
||||||
|
dll_base_name = dll.name.split("\\")[-1]
|
||||||
|
for function_name, function_address in dll.imports.items():
|
||||||
|
for name in generate_symbols(dll_base_name, function_name, include_dll=True):
|
||||||
|
yield Import(name), AbsoluteVirtualAddress(function_address)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_features(report: DrakvufReport) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
for handler in FILE_HANDLERS:
|
||||||
|
for feature, addr in handler(report):
|
||||||
|
yield feature, addr
|
||||||
|
|
||||||
|
|
||||||
|
FILE_HANDLERS = (
|
||||||
|
# TODO(yelhamer): extract more file features from other DRAKVUF plugins
|
||||||
|
# https://github.com/mandiant/capa/issues/2169
|
||||||
|
extract_import_names,
|
||||||
|
)
|
||||||
44
capa/features/extractors/drakvuf/global_.py
Normal file
44
capa/features/extractors/drakvuf/global_.py
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
# Copyright (C) 2024 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Tuple, Iterator
|
||||||
|
|
||||||
|
from capa.features.common import OS, FORMAT_PE, ARCH_AMD64, OS_WINDOWS, Arch, Format, Feature
|
||||||
|
from capa.features.address import NO_ADDRESS, Address
|
||||||
|
from capa.features.extractors.drakvuf.models import DrakvufReport
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_format(report: DrakvufReport) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
# DRAKVUF sandbox currently supports only Windows as the guest: https://drakvuf-sandbox.readthedocs.io/en/latest/usage/getting_started.html
|
||||||
|
yield Format(FORMAT_PE), NO_ADDRESS
|
||||||
|
|
||||||
|
|
||||||
|
def extract_os(report: DrakvufReport) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
# DRAKVUF sandbox currently supports only PE files: https://drakvuf-sandbox.readthedocs.io/en/latest/usage/getting_started.html
|
||||||
|
yield OS(OS_WINDOWS), NO_ADDRESS
|
||||||
|
|
||||||
|
|
||||||
|
def extract_arch(report: DrakvufReport) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
# DRAKVUF sandbox currently supports only x64 Windows as the guest: https://drakvuf-sandbox.readthedocs.io/en/latest/usage/getting_started.html
|
||||||
|
yield Arch(ARCH_AMD64), NO_ADDRESS
|
||||||
|
|
||||||
|
|
||||||
|
def extract_features(report: DrakvufReport) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
for global_handler in GLOBAL_HANDLER:
|
||||||
|
for feature, addr in global_handler(report):
|
||||||
|
yield feature, addr
|
||||||
|
|
||||||
|
|
||||||
|
GLOBAL_HANDLER = (
|
||||||
|
extract_format,
|
||||||
|
extract_os,
|
||||||
|
extract_arch,
|
||||||
|
)
|
||||||
39
capa/features/extractors/drakvuf/helpers.py
Normal file
39
capa/features/extractors/drakvuf/helpers.py
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
# Copyright (C) 2024 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
|
||||||
|
import itertools
|
||||||
|
from typing import Dict, List
|
||||||
|
|
||||||
|
from capa.features.address import ThreadAddress, ProcessAddress
|
||||||
|
from capa.features.extractors.drakvuf.models import Call, DrakvufReport
|
||||||
|
|
||||||
|
|
||||||
|
def index_calls(report: DrakvufReport) -> Dict[ProcessAddress, Dict[ThreadAddress, List[Call]]]:
|
||||||
|
# this method organizes calls into processes and threads, and then sorts them based on
|
||||||
|
# timestamp so that we can address individual calls per index (CallAddress requires call index)
|
||||||
|
result: Dict[ProcessAddress, Dict[ThreadAddress, List[Call]]] = {}
|
||||||
|
for call in itertools.chain(report.syscalls, report.apicalls):
|
||||||
|
if call.pid == 0:
|
||||||
|
# DRAKVUF captures api/native calls from all processes running on the system.
|
||||||
|
# we ignore the pid 0 since it's a system process and it's unlikely for it to
|
||||||
|
# be hijacked or so on, in addition to capa addresses not supporting null pids
|
||||||
|
continue
|
||||||
|
proc_addr = ProcessAddress(pid=call.pid, ppid=call.ppid)
|
||||||
|
thread_addr = ThreadAddress(process=proc_addr, tid=call.tid)
|
||||||
|
if proc_addr not in result:
|
||||||
|
result[proc_addr] = {}
|
||||||
|
if thread_addr not in result[proc_addr]:
|
||||||
|
result[proc_addr][thread_addr] = []
|
||||||
|
|
||||||
|
result[proc_addr][thread_addr].append(call)
|
||||||
|
|
||||||
|
for proc, threads in result.items():
|
||||||
|
for thread in threads:
|
||||||
|
result[proc][thread].sort(key=lambda call: call.timestamp)
|
||||||
|
|
||||||
|
return result
|
||||||
137
capa/features/extractors/drakvuf/models.py
Normal file
137
capa/features/extractors/drakvuf/models.py
Normal file
@@ -0,0 +1,137 @@
|
|||||||
|
# Copyright (C) 2024 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
import logging
|
||||||
|
from typing import Any, Dict, List, Iterator
|
||||||
|
|
||||||
|
from pydantic import Field, BaseModel, ConfigDict, model_validator
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
REQUIRED_SYSCALL_FIELD_NAMES = {
|
||||||
|
"Plugin",
|
||||||
|
"TimeStamp",
|
||||||
|
"PID",
|
||||||
|
"PPID",
|
||||||
|
"TID",
|
||||||
|
"UserName",
|
||||||
|
"UserId",
|
||||||
|
"ProcessName",
|
||||||
|
"Method",
|
||||||
|
"EventUID",
|
||||||
|
"Module",
|
||||||
|
"vCPU",
|
||||||
|
"CR3",
|
||||||
|
"Syscall",
|
||||||
|
"NArgs",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class ConciseModel(BaseModel):
|
||||||
|
ConfigDict(extra="ignore")
|
||||||
|
|
||||||
|
|
||||||
|
class DiscoveredDLL(ConciseModel):
|
||||||
|
plugin_name: str = Field(alias="Plugin")
|
||||||
|
event: str = Field(alias="Event")
|
||||||
|
name: str = Field(alias="DllName")
|
||||||
|
pid: int = Field(alias="PID")
|
||||||
|
|
||||||
|
|
||||||
|
class LoadedDLL(ConciseModel):
|
||||||
|
plugin_name: str = Field(alias="Plugin")
|
||||||
|
event: str = Field(alias="Event")
|
||||||
|
name: str = Field(alias="DllName")
|
||||||
|
imports: Dict[str, int] = Field(alias="Rva")
|
||||||
|
|
||||||
|
|
||||||
|
class Call(ConciseModel):
|
||||||
|
plugin_name: str = Field(alias="Plugin")
|
||||||
|
timestamp: str = Field(alias="TimeStamp")
|
||||||
|
process_name: str = Field(alias="ProcessName")
|
||||||
|
ppid: int = Field(alias="PPID")
|
||||||
|
pid: int = Field(alias="PID")
|
||||||
|
tid: int = Field(alias="TID")
|
||||||
|
name: str = Field(alias="Method")
|
||||||
|
arguments: Dict[str, str]
|
||||||
|
|
||||||
|
|
||||||
|
class WinApiCall(Call):
|
||||||
|
# This class models Windows API calls captured by DRAKVUF (DLLs, etc.).
|
||||||
|
arguments: Dict[str, str] = Field(alias="Arguments")
|
||||||
|
event: str = Field(alias="Event")
|
||||||
|
return_value: str = Field(alias="ReturnValue")
|
||||||
|
|
||||||
|
@model_validator(mode="before")
|
||||||
|
@classmethod
|
||||||
|
def build_arguments(cls, values: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
|
args = values["Arguments"]
|
||||||
|
values["Arguments"] = dict(arg.split("=", 1) for arg in args)
|
||||||
|
return values
|
||||||
|
|
||||||
|
|
||||||
|
class SystemCall(Call):
|
||||||
|
# This class models native Windows API calls captured by DRAKVUF.
|
||||||
|
# Schema: {
|
||||||
|
# "Plugin": "syscall",
|
||||||
|
# "TimeStamp": "1716999134.582553",
|
||||||
|
# "PID": 3888, "PPID": 2852, "TID": 368, "UserName": "SessionID", "UserId": 2,
|
||||||
|
# "ProcessName": "\\Device\\HarddiskVolume2\\Windows\\explorer.exe",
|
||||||
|
# "Method": "NtSetIoCompletionEx",
|
||||||
|
# "EventUID": "0x27",
|
||||||
|
# "Module": "nt",
|
||||||
|
# "vCPU": 0,
|
||||||
|
# "CR3": "0x119b1002",
|
||||||
|
# "Syscall": 419,
|
||||||
|
# "NArgs": 6,
|
||||||
|
# "IoCompletionHandle": "0xffffffff80001ac0", "IoCompletionReserveHandle": "0xffffffff8000188c",
|
||||||
|
# "KeyContext": "0x0", "ApcContext": "0x2", "IoStatus": "0x7ffb00000000", "IoStatusInformation": "0x0"
|
||||||
|
# }
|
||||||
|
# The keys up until "NArgs" are common to all the native calls that DRAKVUF reports, with
|
||||||
|
# the remaining keys representing the call's specific arguments.
|
||||||
|
syscall_number: int = Field(alias="Syscall")
|
||||||
|
module: str = Field(alias="Module")
|
||||||
|
nargs: int = Field(alias="NArgs")
|
||||||
|
|
||||||
|
@model_validator(mode="before")
|
||||||
|
@classmethod
|
||||||
|
def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
|
# DRAKVUF stores argument names and values as entries in the syscall's entry.
|
||||||
|
# This model validator collects those arguments into a list in the model.
|
||||||
|
values["arguments"] = {
|
||||||
|
name: value for name, value in values.items() if name not in REQUIRED_SYSCALL_FIELD_NAMES
|
||||||
|
}
|
||||||
|
return values
|
||||||
|
|
||||||
|
|
||||||
|
class DrakvufReport(ConciseModel):
|
||||||
|
syscalls: List[SystemCall] = []
|
||||||
|
apicalls: List[WinApiCall] = []
|
||||||
|
discovered_dlls: List[DiscoveredDLL] = []
|
||||||
|
loaded_dlls: List[LoadedDLL] = []
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def from_raw_report(cls, entries: Iterator[Dict]) -> "DrakvufReport":
|
||||||
|
report = cls()
|
||||||
|
|
||||||
|
for entry in entries:
|
||||||
|
plugin = entry.get("Plugin")
|
||||||
|
# TODO(yelhamer): add support for more DRAKVUF plugins
|
||||||
|
# https://github.com/mandiant/capa/issues/2181
|
||||||
|
if plugin == "syscall":
|
||||||
|
report.syscalls.append(SystemCall(**entry))
|
||||||
|
elif plugin == "apimon":
|
||||||
|
event = entry.get("Event")
|
||||||
|
if event == "api_called":
|
||||||
|
report.apicalls.append(WinApiCall(**entry))
|
||||||
|
elif event == "dll_loaded":
|
||||||
|
report.loaded_dlls.append(LoadedDLL(**entry))
|
||||||
|
elif event == "dll_discovered":
|
||||||
|
report.discovered_dlls.append(DiscoveredDLL(**entry))
|
||||||
|
|
||||||
|
return report
|
||||||
40
capa/features/extractors/drakvuf/process.py
Normal file
40
capa/features/extractors/drakvuf/process.py
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
# Copyright (C) 2024 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Dict, List, Tuple, Iterator
|
||||||
|
|
||||||
|
from capa.features.common import String, Feature
|
||||||
|
from capa.features.address import Address, ThreadAddress, ProcessAddress
|
||||||
|
from capa.features.extractors.base_extractor import ThreadHandle, ProcessHandle
|
||||||
|
from capa.features.extractors.drakvuf.models import Call
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def get_threads(
|
||||||
|
calls: Dict[ProcessAddress, Dict[ThreadAddress, List[Call]]], ph: ProcessHandle
|
||||||
|
) -> Iterator[ThreadHandle]:
|
||||||
|
"""
|
||||||
|
Get the threads associated with a given process.
|
||||||
|
"""
|
||||||
|
for thread_addr in calls[ph.address]:
|
||||||
|
yield ThreadHandle(address=thread_addr, inner={})
|
||||||
|
|
||||||
|
|
||||||
|
def extract_process_name(ph: ProcessHandle) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
yield String(ph.inner["process_name"]), ph.address
|
||||||
|
|
||||||
|
|
||||||
|
def extract_features(ph: ProcessHandle) -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
for handler in PROCESS_HANDLERS:
|
||||||
|
for feature, addr in handler(ph):
|
||||||
|
yield feature, addr
|
||||||
|
|
||||||
|
|
||||||
|
PROCESS_HANDLERS = (extract_process_name,)
|
||||||
24
capa/features/extractors/drakvuf/thread.py
Normal file
24
capa/features/extractors/drakvuf/thread.py
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
# Copyright (C) 2024 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from typing import Dict, List, Iterator
|
||||||
|
|
||||||
|
from capa.features.address import ThreadAddress, ProcessAddress, DynamicCallAddress
|
||||||
|
from capa.features.extractors.base_extractor import CallHandle, ThreadHandle, ProcessHandle
|
||||||
|
from capa.features.extractors.drakvuf.models import Call
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def get_calls(
|
||||||
|
sorted_calls: Dict[ProcessAddress, Dict[ThreadAddress, List[Call]]], ph: ProcessHandle, th: ThreadHandle
|
||||||
|
) -> Iterator[CallHandle]:
|
||||||
|
for i, call in enumerate(sorted_calls[ph.address][th.address]):
|
||||||
|
call_addr = DynamicCallAddress(thread=th.address, id=i)
|
||||||
|
yield CallHandle(address=call_addr, inner=call)
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
# Copyright (C) 2021 Mandiant, Inc. All Rights Reserved.
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
# you may not use this file except in compliance with the License.
|
# you may not use this file except in compliance with the License.
|
||||||
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
||||||
@@ -10,9 +10,10 @@ import logging
|
|||||||
import itertools
|
import itertools
|
||||||
import collections
|
import collections
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
from typing import Set, Dict, List, Tuple, BinaryIO, Iterator, Optional
|
from typing import TYPE_CHECKING, Set, Dict, List, Tuple, BinaryIO, Iterator, Optional
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
import Elf # from vivisect
|
import Elf # from vivisect
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
@@ -57,6 +58,10 @@ class OS(str, Enum):
|
|||||||
SYLLABLE = "syllable"
|
SYLLABLE = "syllable"
|
||||||
NACL = "nacl"
|
NACL = "nacl"
|
||||||
ANDROID = "android"
|
ANDROID = "android"
|
||||||
|
DRAGONFLYBSD = "dragonfly BSD"
|
||||||
|
ILLUMOS = "illumos"
|
||||||
|
ZOS = "z/os"
|
||||||
|
UNIX = "unix"
|
||||||
|
|
||||||
|
|
||||||
# via readelf: https://github.com/bminor/binutils-gdb/blob/c0e94211e1ac05049a4ce7c192c9d14d1764eb3e/binutils/readelf.c#L19635-L19658
|
# via readelf: https://github.com/bminor/binutils-gdb/blob/c0e94211e1ac05049a4ce7c192c9d14d1764eb3e/binutils/readelf.c#L19635-L19658
|
||||||
@@ -80,6 +85,8 @@ class Phdr:
|
|||||||
paddr: int
|
paddr: int
|
||||||
filesz: int
|
filesz: int
|
||||||
buf: bytes
|
buf: bytes
|
||||||
|
flags: int
|
||||||
|
memsz: int
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
@@ -108,6 +115,9 @@ class Shdr:
|
|||||||
buf,
|
buf,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def get_name(self, elf: "ELF") -> str:
|
||||||
|
return elf.shstrtab.buf[self.name :].partition(b"\x00")[0].decode("ascii")
|
||||||
|
|
||||||
|
|
||||||
class ELF:
|
class ELF:
|
||||||
def __init__(self, f: BinaryIO):
|
def __init__(self, f: BinaryIO):
|
||||||
@@ -120,6 +130,7 @@ class ELF:
|
|||||||
self.e_phnum: int
|
self.e_phnum: int
|
||||||
self.e_shentsize: int
|
self.e_shentsize: int
|
||||||
self.e_shnum: int
|
self.e_shnum: int
|
||||||
|
self.e_shstrndx: int
|
||||||
self.phbuf: bytes
|
self.phbuf: bytes
|
||||||
self.shbuf: bytes
|
self.shbuf: bytes
|
||||||
|
|
||||||
@@ -151,11 +162,15 @@ class ELF:
|
|||||||
if self.bitness == 32:
|
if self.bitness == 32:
|
||||||
e_phoff, e_shoff = struct.unpack_from(self.endian + "II", self.file_header, 0x1C)
|
e_phoff, e_shoff = struct.unpack_from(self.endian + "II", self.file_header, 0x1C)
|
||||||
self.e_phentsize, self.e_phnum = struct.unpack_from(self.endian + "HH", self.file_header, 0x2A)
|
self.e_phentsize, self.e_phnum = struct.unpack_from(self.endian + "HH", self.file_header, 0x2A)
|
||||||
self.e_shentsize, self.e_shnum = struct.unpack_from(self.endian + "HH", self.file_header, 0x2E)
|
self.e_shentsize, self.e_shnum, self.e_shstrndx = struct.unpack_from(
|
||||||
|
self.endian + "HHH", self.file_header, 0x2E
|
||||||
|
)
|
||||||
elif self.bitness == 64:
|
elif self.bitness == 64:
|
||||||
e_phoff, e_shoff = struct.unpack_from(self.endian + "QQ", self.file_header, 0x20)
|
e_phoff, e_shoff = struct.unpack_from(self.endian + "QQ", self.file_header, 0x20)
|
||||||
self.e_phentsize, self.e_phnum = struct.unpack_from(self.endian + "HH", self.file_header, 0x36)
|
self.e_phentsize, self.e_phnum = struct.unpack_from(self.endian + "HH", self.file_header, 0x36)
|
||||||
self.e_shentsize, self.e_shnum = struct.unpack_from(self.endian + "HH", self.file_header, 0x3A)
|
self.e_shentsize, self.e_shnum, self.e_shstrndx = struct.unpack_from(
|
||||||
|
self.endian + "HHH", self.file_header, 0x3A
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
raise NotImplementedError()
|
raise NotImplementedError()
|
||||||
|
|
||||||
@@ -197,7 +212,7 @@ class ELF:
|
|||||||
15: OS.AROS,
|
15: OS.AROS,
|
||||||
16: OS.FENIXOS,
|
16: OS.FENIXOS,
|
||||||
17: OS.CLOUD,
|
17: OS.CLOUD,
|
||||||
# 53: "SORTFIX", # i can't find any reference to this OS, i dont think it exists
|
# 53: "SORTFIX", # i can't find any reference to this OS, i don't think it exists
|
||||||
# 64: "ARM_AEABI", # not an OS
|
# 64: "ARM_AEABI", # not an OS
|
||||||
# 97: "ARM", # not an OS
|
# 97: "ARM", # not an OS
|
||||||
# 255: "STANDALONE", # not an OS
|
# 255: "STANDALONE", # not an OS
|
||||||
@@ -295,6 +310,9 @@ class ELF:
|
|||||||
98: "TPC",
|
98: "TPC",
|
||||||
99: "SNP1K",
|
99: "SNP1K",
|
||||||
100: "ST200",
|
100: "ST200",
|
||||||
|
# https://www.sco.com/developers/gabi/latest/ch4.eheader.html
|
||||||
|
183: "aarch64",
|
||||||
|
243: "riscv",
|
||||||
}
|
}
|
||||||
|
|
||||||
@property
|
@property
|
||||||
@@ -306,24 +324,23 @@ class ELF:
|
|||||||
phent_offset = i * self.e_phentsize
|
phent_offset = i * self.e_phentsize
|
||||||
phent = self.phbuf[phent_offset : phent_offset + self.e_phentsize]
|
phent = self.phbuf[phent_offset : phent_offset + self.e_phentsize]
|
||||||
|
|
||||||
(p_type,) = struct.unpack_from(self.endian + "I", phent, 0x0)
|
|
||||||
logger.debug("ph:p_type: 0x%04x", p_type)
|
|
||||||
|
|
||||||
if self.bitness == 32:
|
if self.bitness == 32:
|
||||||
p_offset, p_vaddr, p_paddr, p_filesz = struct.unpack_from(self.endian + "IIII", phent, 0x4)
|
p_type, p_offset, p_vaddr, p_paddr, p_filesz, p_memsz, p_flags = struct.unpack_from(
|
||||||
|
self.endian + "IIIIIII", phent, 0x0
|
||||||
|
)
|
||||||
elif self.bitness == 64:
|
elif self.bitness == 64:
|
||||||
p_offset, p_vaddr, p_paddr, p_filesz = struct.unpack_from(self.endian + "QQQQ", phent, 0x8)
|
p_type, p_flags, p_offset, p_vaddr, p_paddr, p_filesz, p_memsz = struct.unpack_from(
|
||||||
|
self.endian + "IIQQQQQ", phent, 0x0
|
||||||
|
)
|
||||||
else:
|
else:
|
||||||
raise NotImplementedError()
|
raise NotImplementedError()
|
||||||
|
|
||||||
logger.debug("ph:p_offset: 0x%02x p_filesz: 0x%04x", p_offset, p_filesz)
|
|
||||||
|
|
||||||
self.f.seek(p_offset)
|
self.f.seek(p_offset)
|
||||||
buf = self.f.read(p_filesz)
|
buf = self.f.read(p_filesz)
|
||||||
if len(buf) != p_filesz:
|
if len(buf) != p_filesz:
|
||||||
raise ValueError("failed to read program header content")
|
raise ValueError("failed to read program header content")
|
||||||
|
|
||||||
return Phdr(p_type, p_offset, p_vaddr, p_paddr, p_filesz, buf)
|
return Phdr(p_type, p_offset, p_vaddr, p_paddr, p_filesz, buf, p_flags, p_memsz)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def program_headers(self):
|
def program_headers(self):
|
||||||
@@ -348,8 +365,6 @@ class ELF:
|
|||||||
else:
|
else:
|
||||||
raise NotImplementedError()
|
raise NotImplementedError()
|
||||||
|
|
||||||
logger.debug("sh:sh_offset: 0x%02x sh_size: 0x%04x", sh_offset, sh_size)
|
|
||||||
|
|
||||||
self.f.seek(sh_offset)
|
self.f.seek(sh_offset)
|
||||||
buf = self.f.read(sh_size)
|
buf = self.f.read(sh_size)
|
||||||
if len(buf) != sh_size:
|
if len(buf) != sh_size:
|
||||||
@@ -365,6 +380,10 @@ class ELF:
|
|||||||
except ValueError:
|
except ValueError:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
@property
|
||||||
|
def shstrtab(self) -> Shdr:
|
||||||
|
return self.parse_section_header(self.e_shstrndx)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def linker(self):
|
def linker(self):
|
||||||
PT_INTERP = 0x3
|
PT_INTERP = 0x3
|
||||||
@@ -712,7 +731,7 @@ class SymTab:
|
|||||||
yield from self.symbols
|
yield from self.symbols
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_viv(cls, elf: Elf.Elf) -> Optional["SymTab"]:
|
def from_viv(cls, elf: "Elf.Elf") -> Optional["SymTab"]:
|
||||||
endian = "<" if elf.getEndian() == 0 else ">"
|
endian = "<" if elf.getEndian() == 0 else ">"
|
||||||
bitness = elf.bits
|
bitness = elf.bits
|
||||||
|
|
||||||
@@ -816,6 +835,52 @@ def guess_os_from_sh_notes(elf: ELF) -> Optional[OS]:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def guess_os_from_ident_directive(elf: ELF) -> Optional[OS]:
|
||||||
|
# GCC inserts the GNU version via an .ident directive
|
||||||
|
# that gets stored in a section named ".comment".
|
||||||
|
# look at the version and recognize common OSes.
|
||||||
|
#
|
||||||
|
# assume the GCC version matches the target OS version,
|
||||||
|
# which I guess could be wrong during cross-compilation?
|
||||||
|
# therefore, don't rely on this if possible.
|
||||||
|
#
|
||||||
|
# https://stackoverflow.com/q/6263425
|
||||||
|
# https://gcc.gnu.org/onlinedocs/cpp/Other-Directives.html
|
||||||
|
|
||||||
|
SHT_PROGBITS = 0x1
|
||||||
|
for shdr in elf.section_headers:
|
||||||
|
if shdr.type != SHT_PROGBITS:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if shdr.get_name(elf) != ".comment":
|
||||||
|
continue
|
||||||
|
|
||||||
|
try:
|
||||||
|
comment = shdr.buf.decode("utf-8")
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if "GCC:" not in comment:
|
||||||
|
continue
|
||||||
|
|
||||||
|
logger.debug(".ident: %s", comment)
|
||||||
|
|
||||||
|
# these values come from our testfiles, like:
|
||||||
|
# rg -a "GCC: " tests/data/
|
||||||
|
if "Debian" in comment:
|
||||||
|
return OS.LINUX
|
||||||
|
elif "Ubuntu" in comment:
|
||||||
|
return OS.LINUX
|
||||||
|
elif "Red Hat" in comment:
|
||||||
|
return OS.LINUX
|
||||||
|
elif "Alpine" in comment:
|
||||||
|
return OS.LINUX
|
||||||
|
elif "Android" in comment:
|
||||||
|
return OS.ANDROID
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def guess_os_from_linker(elf: ELF) -> Optional[OS]:
|
def guess_os_from_linker(elf: ELF) -> Optional[OS]:
|
||||||
# search for recognizable dynamic linkers (interpreters)
|
# search for recognizable dynamic linkers (interpreters)
|
||||||
# for example, on linux, we see file paths like: /lib64/ld-linux-x86-64.so.2
|
# for example, on linux, we see file paths like: /lib64/ld-linux-x86-64.so.2
|
||||||
@@ -851,8 +916,10 @@ def guess_os_from_abi_versions_needed(elf: ELF) -> Optional[OS]:
|
|||||||
return OS.HURD
|
return OS.HURD
|
||||||
|
|
||||||
else:
|
else:
|
||||||
# we don't have any good guesses based on versions needed
|
# in practice, Hurd isn't a common/viable OS,
|
||||||
pass
|
# so this is almost certain to be Linux,
|
||||||
|
# so lets just make that guess.
|
||||||
|
return OS.LINUX
|
||||||
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@@ -865,6 +932,8 @@ def guess_os_from_needed_dependencies(elf: ELF) -> Optional[OS]:
|
|||||||
return OS.HURD
|
return OS.HURD
|
||||||
if needed.startswith("libandroid.so"):
|
if needed.startswith("libandroid.so"):
|
||||||
return OS.ANDROID
|
return OS.ANDROID
|
||||||
|
if needed.startswith("liblog.so"):
|
||||||
|
return OS.ANDROID
|
||||||
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
@@ -891,11 +960,506 @@ def guess_os_from_symtab(elf: ELF) -> Optional[OS]:
|
|||||||
|
|
||||||
for os, hints in keywords.items():
|
for os, hints in keywords.items():
|
||||||
if any(hint in sym_name for hint in hints):
|
if any(hint in sym_name for hint in hints):
|
||||||
|
logger.debug("symtab: %s looks like %s", sym_name, os)
|
||||||
return os
|
return os
|
||||||
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def is_go_binary(elf: ELF) -> bool:
|
||||||
|
for shdr in elf.section_headers:
|
||||||
|
if shdr.get_name(elf) == ".note.go.buildid":
|
||||||
|
logger.debug("go buildinfo: found section .note.go.buildid")
|
||||||
|
return True
|
||||||
|
|
||||||
|
# The `go version` command enumerates sections for the name `.go.buildinfo`
|
||||||
|
# (in addition to looking for the BUILDINFO_MAGIC) to check if an executable is go or not.
|
||||||
|
# See references to the `errNotGoExe` error here:
|
||||||
|
# https://github.com/golang/go/blob/master/src/debug/buildinfo/buildinfo.go#L41
|
||||||
|
for shdr in elf.section_headers:
|
||||||
|
if shdr.get_name(elf) == ".go.buildinfo":
|
||||||
|
logger.debug("go buildinfo: found section .go.buildinfo")
|
||||||
|
return True
|
||||||
|
|
||||||
|
# other strategy used by FLOSS: search for known runtime strings.
|
||||||
|
# https://github.com/mandiant/flare-floss/blob/b2ca8adfc5edf278861dd6bff67d73da39683b46/floss/language/identify.py#L88
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def get_go_buildinfo_data(elf: ELF) -> Optional[bytes]:
|
||||||
|
for shdr in elf.section_headers:
|
||||||
|
if shdr.get_name(elf) == ".go.buildinfo":
|
||||||
|
logger.debug("go buildinfo: found section .go.buildinfo")
|
||||||
|
return shdr.buf
|
||||||
|
|
||||||
|
PT_LOAD = 0x1
|
||||||
|
PF_X = 1
|
||||||
|
PF_W = 2
|
||||||
|
for phdr in elf.program_headers:
|
||||||
|
if phdr.type != PT_LOAD:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if (phdr.flags & (PF_X | PF_W)) == PF_W:
|
||||||
|
logger.debug("go buildinfo: found data segment")
|
||||||
|
return phdr.buf
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def read_data(elf: ELF, rva: int, size: int) -> Optional[bytes]:
|
||||||
|
# ELF segments are for runtime data,
|
||||||
|
# ELF sections are for link-time data.
|
||||||
|
# So we want to read Program Headers/Segments.
|
||||||
|
for phdr in elf.program_headers:
|
||||||
|
if phdr.vaddr <= rva < phdr.vaddr + phdr.memsz:
|
||||||
|
segment_data = phdr.buf
|
||||||
|
|
||||||
|
# pad the section with NULLs
|
||||||
|
# assume page alignment is already handled.
|
||||||
|
# might need more hardening here.
|
||||||
|
if len(segment_data) < phdr.memsz:
|
||||||
|
segment_data += b"\x00" * (phdr.memsz - len(segment_data))
|
||||||
|
|
||||||
|
segment_offset = rva - phdr.vaddr
|
||||||
|
return segment_data[segment_offset : segment_offset + size]
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def read_go_slice(elf: ELF, rva: int) -> Optional[bytes]:
|
||||||
|
if elf.bitness == 32:
|
||||||
|
struct_size = 8
|
||||||
|
struct_format = elf.endian + "II"
|
||||||
|
elif elf.bitness == 64:
|
||||||
|
struct_size = 16
|
||||||
|
struct_format = elf.endian + "QQ"
|
||||||
|
else:
|
||||||
|
raise ValueError("invalid psize")
|
||||||
|
|
||||||
|
struct_buf = read_data(elf, rva, struct_size)
|
||||||
|
if not struct_buf:
|
||||||
|
return None
|
||||||
|
|
||||||
|
addr, length = struct.unpack_from(struct_format, struct_buf, 0)
|
||||||
|
|
||||||
|
return read_data(elf, addr, length)
|
||||||
|
|
||||||
|
|
||||||
|
def guess_os_from_go_buildinfo(elf: ELF) -> Optional[OS]:
|
||||||
|
"""
|
||||||
|
In a binary compiled by Go, the buildinfo structure may contain
|
||||||
|
metadata about the build environment, including the configured
|
||||||
|
GOOS, which specifies the target operating system.
|
||||||
|
|
||||||
|
Search for and parse the buildinfo structure,
|
||||||
|
which may be found in the .go.buildinfo section,
|
||||||
|
and often contains this metadata inline. Otherwise,
|
||||||
|
follow a few byte slices to the relevant information.
|
||||||
|
|
||||||
|
This strategy is derived from GoReSym.
|
||||||
|
"""
|
||||||
|
buf = get_go_buildinfo_data(elf)
|
||||||
|
if not buf:
|
||||||
|
logger.debug("go buildinfo: no buildinfo section")
|
||||||
|
return None
|
||||||
|
|
||||||
|
assert isinstance(buf, bytes)
|
||||||
|
|
||||||
|
# The build info blob left by the linker is identified by
|
||||||
|
# a 16-byte header, consisting of:
|
||||||
|
# - buildInfoMagic (14 bytes),
|
||||||
|
# - the binary's pointer size (1 byte), and
|
||||||
|
# - whether the binary is big endian (1 byte).
|
||||||
|
#
|
||||||
|
# Then:
|
||||||
|
# - virtual address to Go string: runtime.buildVersion
|
||||||
|
# - virtual address to Go string: runtime.modinfo
|
||||||
|
#
|
||||||
|
# On 32-bit platforms, the last 8 bytes are unused.
|
||||||
|
#
|
||||||
|
# If the endianness has the 2 bit set, then the pointers are zero,
|
||||||
|
# and the 32-byte header is followed by varint-prefixed string data
|
||||||
|
# for the two string values we care about.
|
||||||
|
# https://github.com/mandiant/GoReSym/blob/0860a1b1b4f3495e9fb7e71eb4386bf3e0a7c500/buildinfo/buildinfo.go#L185-L193
|
||||||
|
BUILDINFO_MAGIC = b"\xFF Go buildinf:"
|
||||||
|
|
||||||
|
try:
|
||||||
|
index = buf.index(BUILDINFO_MAGIC)
|
||||||
|
except ValueError:
|
||||||
|
logger.debug("go buildinfo: no buildinfo magic")
|
||||||
|
return None
|
||||||
|
|
||||||
|
psize, flags = struct.unpack_from("<bb", buf, index + len(BUILDINFO_MAGIC))
|
||||||
|
assert psize in (4, 8)
|
||||||
|
is_big_endian = flags & 0b01
|
||||||
|
has_inline_strings = flags & 0b10
|
||||||
|
logger.debug("go buildinfo: psize: %d big endian: %s inline: %s", psize, is_big_endian, has_inline_strings)
|
||||||
|
|
||||||
|
GOOS_TO_OS = {
|
||||||
|
b"aix": OS.AIX,
|
||||||
|
b"android": OS.ANDROID,
|
||||||
|
b"dragonfly": OS.DRAGONFLYBSD,
|
||||||
|
b"freebsd": OS.FREEBSD,
|
||||||
|
b"hurd": OS.HURD,
|
||||||
|
b"illumos": OS.ILLUMOS,
|
||||||
|
b"linux": OS.LINUX,
|
||||||
|
b"netbsd": OS.NETBSD,
|
||||||
|
b"openbsd": OS.OPENBSD,
|
||||||
|
b"solaris": OS.SOLARIS,
|
||||||
|
b"zos": OS.ZOS,
|
||||||
|
b"windows": None, # PE format
|
||||||
|
b"plan9": None, # a.out format
|
||||||
|
b"ios": None, # Mach-O format
|
||||||
|
b"darwin": None, # Mach-O format
|
||||||
|
b"nacl": None, # dropped in GO 1.14
|
||||||
|
b"js": None,
|
||||||
|
}
|
||||||
|
|
||||||
|
if has_inline_strings:
|
||||||
|
# This is the common case/path. Most samples will have an inline GOOS string.
|
||||||
|
#
|
||||||
|
# To find samples on VT, use these VTGrep searches:
|
||||||
|
#
|
||||||
|
# content: {ff 20 47 6f 20 62 75 69 6c 64 69 6e 66 3a 04 02}
|
||||||
|
# content: {ff 20 47 6f 20 62 75 69 6c 64 69 6e 66 3a 08 02}
|
||||||
|
|
||||||
|
# If present, the GOOS key will be found within
|
||||||
|
# the current buildinfo data region.
|
||||||
|
#
|
||||||
|
# Brute force the k-v pair, like `GOOS=linux`,
|
||||||
|
# rather than try to parse the data, which would be fragile.
|
||||||
|
for key, os in GOOS_TO_OS.items():
|
||||||
|
if (b"GOOS=" + key) in buf:
|
||||||
|
logger.debug("go buildinfo: found os: %s", os)
|
||||||
|
return os
|
||||||
|
else:
|
||||||
|
# This is the uncommon path. Most samples will have an inline GOOS string.
|
||||||
|
#
|
||||||
|
# To find samples on VT, use the referenced VTGrep content searches.
|
||||||
|
info_format = {
|
||||||
|
# content: {ff 20 47 6f 20 62 75 69 6c 64 69 6e 66 3a 04 00}
|
||||||
|
# like: 71e617e5cc7fda89bf67422ff60f437e9d54622382c5ed6ff31f75e601f9b22e
|
||||||
|
# in which the modinfo doesn't have GOOS.
|
||||||
|
(4, False): "<II",
|
||||||
|
# content: {ff 20 47 6f 20 62 75 69 6c 64 69 6e 66 3a 08 00}
|
||||||
|
# like: 93d3b3e2a904c6c909e20f2f76c3c2e8d0c81d535eb46e5493b5701f461816c3
|
||||||
|
# in which the modinfo doesn't have GOOS.
|
||||||
|
(8, False): "<QQ",
|
||||||
|
# content: {ff 20 47 6f 20 62 75 69 6c 64 69 6e 66 3a 04 01}
|
||||||
|
# (no matches on VT today)
|
||||||
|
(4, True): ">II",
|
||||||
|
# content: {ff 20 47 6f 20 62 75 69 6c 64 69 6e 66 3a 08 01}
|
||||||
|
# like: d44ba497964050c0e3dd2a192c511e4c3c4f17717f0322a554d64b797ee4690a
|
||||||
|
# in which the modinfo doesn't have GOOS.
|
||||||
|
(8, True): ">QQ",
|
||||||
|
}
|
||||||
|
|
||||||
|
build_version_address, modinfo_address = struct.unpack_from(
|
||||||
|
info_format[(psize, is_big_endian)], buf, index + 0x10
|
||||||
|
)
|
||||||
|
logger.debug("go buildinfo: build version address: 0x%x", build_version_address)
|
||||||
|
logger.debug("go buildinfo: modinfo address: 0x%x", modinfo_address)
|
||||||
|
|
||||||
|
build_version = read_go_slice(elf, build_version_address)
|
||||||
|
if build_version:
|
||||||
|
logger.debug("go buildinfo: build version: %s", build_version.decode("utf-8"))
|
||||||
|
|
||||||
|
modinfo = read_go_slice(elf, modinfo_address)
|
||||||
|
if modinfo:
|
||||||
|
if modinfo[-0x11] == ord("\n"):
|
||||||
|
# Strip module framing: sentinel strings delimiting the module info.
|
||||||
|
# These are cmd/go/internal/modload/build.infoStart and infoEnd.
|
||||||
|
# Which should probably be:
|
||||||
|
# infoStart, _ = hex.DecodeString("3077af0c9274080241e1c107e6d618e6")
|
||||||
|
# infoEnd, _ = hex.DecodeString("f932433186182072008242104116d8f2")
|
||||||
|
modinfo = modinfo[0x10:-0x10]
|
||||||
|
logger.debug("go buildinfo: modinfo: %s", modinfo.decode("utf-8"))
|
||||||
|
|
||||||
|
if not modinfo:
|
||||||
|
return None
|
||||||
|
|
||||||
|
for key, os in GOOS_TO_OS.items():
|
||||||
|
# Brute force the k-v pair, like `GOOS=linux`,
|
||||||
|
# rather than try to parse the data, which would be fragile.
|
||||||
|
if (b"GOOS=" + key) in modinfo:
|
||||||
|
logger.debug("go buildinfo: found os: %s", os)
|
||||||
|
return os
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def guess_os_from_go_source(elf: ELF) -> Optional[OS]:
|
||||||
|
"""
|
||||||
|
In a binary compiled by Go, runtime metadata may contain
|
||||||
|
references to the source filenames, including the
|
||||||
|
src/runtime/os_* files, whose name indicates the
|
||||||
|
target operating system.
|
||||||
|
|
||||||
|
Confirm the given ELF seems to be built by Go,
|
||||||
|
and then look for strings that look like
|
||||||
|
Go source filenames.
|
||||||
|
|
||||||
|
This strategy is derived from GoReSym.
|
||||||
|
"""
|
||||||
|
if not is_go_binary(elf):
|
||||||
|
return None
|
||||||
|
|
||||||
|
for phdr in elf.program_headers:
|
||||||
|
buf = phdr.buf
|
||||||
|
NEEDLE_OS = b"/src/runtime/os_"
|
||||||
|
try:
|
||||||
|
index = buf.index(NEEDLE_OS)
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
|
||||||
|
rest = buf[index + len(NEEDLE_OS) : index + len(NEEDLE_OS) + 32]
|
||||||
|
filename = rest.partition(b".go")[0].decode("utf-8")
|
||||||
|
logger.debug("go source: filename: /src/runtime/os_%s.go", filename)
|
||||||
|
|
||||||
|
# via: https://cs.opensource.google/go/go/+/master:src/runtime/;bpv=1;bpt=0
|
||||||
|
# candidates today:
|
||||||
|
# - aix
|
||||||
|
# - android
|
||||||
|
# - darwin
|
||||||
|
# - darwin_arm64
|
||||||
|
# - dragonfly
|
||||||
|
# - freebsd
|
||||||
|
# - freebsd2
|
||||||
|
# - freebsd_amd64
|
||||||
|
# - freebsd_arm
|
||||||
|
# - freebsd_arm64
|
||||||
|
# - freebsd_noauxv
|
||||||
|
# - freebsd_riscv64
|
||||||
|
# - illumos
|
||||||
|
# - js
|
||||||
|
# - linux
|
||||||
|
# - linux_arm
|
||||||
|
# - linux_arm64
|
||||||
|
# - linux_be64
|
||||||
|
# - linux_generic
|
||||||
|
# - linux_loong64
|
||||||
|
# - linux_mips64x
|
||||||
|
# - linux_mipsx
|
||||||
|
# - linux_noauxv
|
||||||
|
# - linux_novdso
|
||||||
|
# - linux_ppc64x
|
||||||
|
# - linux_riscv64
|
||||||
|
# - linux_s390x
|
||||||
|
# - linux_x86
|
||||||
|
# - netbsd
|
||||||
|
# - netbsd_386
|
||||||
|
# - netbsd_amd64
|
||||||
|
# - netbsd_arm
|
||||||
|
# - netbsd_arm64
|
||||||
|
# - nonopenbsd
|
||||||
|
# - only_solaris
|
||||||
|
# - openbsd
|
||||||
|
# - openbsd_arm
|
||||||
|
# - openbsd_arm64
|
||||||
|
# - openbsd_libc
|
||||||
|
# - openbsd_mips64
|
||||||
|
# - openbsd_syscall
|
||||||
|
# - openbsd_syscall1
|
||||||
|
# - openbsd_syscall2
|
||||||
|
# - plan9
|
||||||
|
# - plan9_arm
|
||||||
|
# - solaris
|
||||||
|
# - unix
|
||||||
|
# - unix_nonlinux
|
||||||
|
# - wasip1
|
||||||
|
# - wasm
|
||||||
|
# - windows
|
||||||
|
# - windows_arm
|
||||||
|
# - windows_arm64
|
||||||
|
|
||||||
|
OS_FILENAME_TO_OS = {
|
||||||
|
"aix": OS.AIX,
|
||||||
|
"android": OS.ANDROID,
|
||||||
|
"dragonfly": OS.DRAGONFLYBSD,
|
||||||
|
"freebsd": OS.FREEBSD,
|
||||||
|
"freebsd2": OS.FREEBSD,
|
||||||
|
"freebsd_": OS.FREEBSD,
|
||||||
|
"illumos": OS.ILLUMOS,
|
||||||
|
"linux": OS.LINUX,
|
||||||
|
"netbsd": OS.NETBSD,
|
||||||
|
"only_solaris": OS.SOLARIS,
|
||||||
|
"openbsd": OS.OPENBSD,
|
||||||
|
"solaris": OS.SOLARIS,
|
||||||
|
"unix_nonlinux": OS.UNIX,
|
||||||
|
}
|
||||||
|
|
||||||
|
for prefix, os in OS_FILENAME_TO_OS.items():
|
||||||
|
if filename.startswith(prefix):
|
||||||
|
return os
|
||||||
|
|
||||||
|
for phdr in elf.program_headers:
|
||||||
|
buf = phdr.buf
|
||||||
|
NEEDLE_RT0 = b"/src/runtime/rt0_"
|
||||||
|
try:
|
||||||
|
index = buf.index(NEEDLE_RT0)
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
|
||||||
|
rest = buf[index + len(NEEDLE_RT0) : index + len(NEEDLE_RT0) + 32]
|
||||||
|
filename = rest.partition(b".s")[0].decode("utf-8")
|
||||||
|
logger.debug("go source: filename: /src/runtime/rt0_%s.s", filename)
|
||||||
|
|
||||||
|
# via: https://cs.opensource.google/go/go/+/master:src/runtime/;bpv=1;bpt=0
|
||||||
|
# candidates today:
|
||||||
|
# - aix_ppc64
|
||||||
|
# - android_386
|
||||||
|
# - android_amd64
|
||||||
|
# - android_arm
|
||||||
|
# - android_arm64
|
||||||
|
# - darwin_amd64
|
||||||
|
# - darwin_arm64
|
||||||
|
# - dragonfly_amd64
|
||||||
|
# - freebsd_386
|
||||||
|
# - freebsd_amd64
|
||||||
|
# - freebsd_arm
|
||||||
|
# - freebsd_arm64
|
||||||
|
# - freebsd_riscv64
|
||||||
|
# - illumos_amd64
|
||||||
|
# - ios_amd64
|
||||||
|
# - ios_arm64
|
||||||
|
# - js_wasm
|
||||||
|
# - linux_386
|
||||||
|
# - linux_amd64
|
||||||
|
# - linux_arm
|
||||||
|
# - linux_arm64
|
||||||
|
# - linux_loong64
|
||||||
|
# - linux_mips64x
|
||||||
|
# - linux_mipsx
|
||||||
|
# - linux_ppc64
|
||||||
|
# - linux_ppc64le
|
||||||
|
# - linux_riscv64
|
||||||
|
# - linux_s390x
|
||||||
|
# - netbsd_386
|
||||||
|
# - netbsd_amd64
|
||||||
|
# - netbsd_arm
|
||||||
|
# - netbsd_arm64
|
||||||
|
# - openbsd_386
|
||||||
|
# - openbsd_amd64
|
||||||
|
# - openbsd_arm
|
||||||
|
# - openbsd_arm64
|
||||||
|
# - openbsd_mips64
|
||||||
|
# - openbsd_ppc64
|
||||||
|
# - openbsd_riscv64
|
||||||
|
# - plan9_386
|
||||||
|
# - plan9_amd64
|
||||||
|
# - plan9_arm
|
||||||
|
# - solaris_amd64
|
||||||
|
# - wasip1_wasm
|
||||||
|
# - windows_386
|
||||||
|
# - windows_amd64
|
||||||
|
# - windows_arm
|
||||||
|
# - windows_arm64
|
||||||
|
|
||||||
|
RT0_FILENAME_TO_OS = {
|
||||||
|
"aix": OS.AIX,
|
||||||
|
"android": OS.ANDROID,
|
||||||
|
"dragonfly": OS.DRAGONFLYBSD,
|
||||||
|
"freebsd": OS.FREEBSD,
|
||||||
|
"illumos": OS.ILLUMOS,
|
||||||
|
"linux": OS.LINUX,
|
||||||
|
"netbsd": OS.NETBSD,
|
||||||
|
"openbsd": OS.OPENBSD,
|
||||||
|
"solaris": OS.SOLARIS,
|
||||||
|
}
|
||||||
|
|
||||||
|
for prefix, os in RT0_FILENAME_TO_OS.items():
|
||||||
|
if filename.startswith(prefix):
|
||||||
|
return os
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def guess_os_from_vdso_strings(elf: ELF) -> Optional[OS]:
|
||||||
|
"""
|
||||||
|
The "vDSO" (virtual dynamic shared object) is a small shared
|
||||||
|
library that the kernel automatically maps into the address space
|
||||||
|
of all user-space applications.
|
||||||
|
|
||||||
|
Some statically linked executables include small dynamic linker
|
||||||
|
routines that finds these vDSO symbols, using the ASCII
|
||||||
|
symbol name and version. We can therefore recognize the pairs
|
||||||
|
(symbol, version) to guess the binary targets Linux.
|
||||||
|
"""
|
||||||
|
for phdr in elf.program_headers:
|
||||||
|
buf = phdr.buf
|
||||||
|
|
||||||
|
# We don't really use the arch, but its interesting for documentation
|
||||||
|
# I suppose we could restrict the arch here to what's in the ELF header,
|
||||||
|
# but that's even more work. Let's see if this is sufficient.
|
||||||
|
for arch, symbol, version in (
|
||||||
|
# via: https://man7.org/linux/man-pages/man7/vdso.7.html
|
||||||
|
("arm", b"__vdso_gettimeofday", b"LINUX_2.6"),
|
||||||
|
("arm", b"__vdso_clock_gettime", b"LINUX_2.6"),
|
||||||
|
("aarch64", b"__kernel_rt_sigreturn", b"LINUX_2.6.39"),
|
||||||
|
("aarch64", b"__kernel_gettimeofday", b"LINUX_2.6.39"),
|
||||||
|
("aarch64", b"__kernel_clock_gettime", b"LINUX_2.6.39"),
|
||||||
|
("aarch64", b"__kernel_clock_getres", b"LINUX_2.6.39"),
|
||||||
|
("mips", b"__kernel_gettimeofday", b"LINUX_2.6"),
|
||||||
|
("mips", b"__kernel_clock_gettime", b"LINUX_2.6"),
|
||||||
|
("ia64", b"__kernel_sigtramp", b"LINUX_2.5"),
|
||||||
|
("ia64", b"__kernel_syscall_via_break", b"LINUX_2.5"),
|
||||||
|
("ia64", b"__kernel_syscall_via_epc", b"LINUX_2.5"),
|
||||||
|
("ppc/32", b"__kernel_clock_getres", b"LINUX_2.6.15"),
|
||||||
|
("ppc/32", b"__kernel_clock_gettime", b"LINUX_2.6.15"),
|
||||||
|
("ppc/32", b"__kernel_clock_gettime64", b"LINUX_5.11"),
|
||||||
|
("ppc/32", b"__kernel_datapage_offset", b"LINUX_2.6.15"),
|
||||||
|
("ppc/32", b"__kernel_get_syscall_map", b"LINUX_2.6.15"),
|
||||||
|
("ppc/32", b"__kernel_get_tbfreq", b"LINUX_2.6.15"),
|
||||||
|
("ppc/32", b"__kernel_getcpu", b"LINUX_2.6.15"),
|
||||||
|
("ppc/32", b"__kernel_gettimeofday", b"LINUX_2.6.15"),
|
||||||
|
("ppc/32", b"__kernel_sigtramp_rt32", b"LINUX_2.6.15"),
|
||||||
|
("ppc/32", b"__kernel_sigtramp32", b"LINUX_2.6.15"),
|
||||||
|
("ppc/32", b"__kernel_sync_dicache", b"LINUX_2.6.15"),
|
||||||
|
("ppc/32", b"__kernel_sync_dicache_p5", b"LINUX_2.6.15"),
|
||||||
|
("ppc/64", b"__kernel_clock_getres", b"LINUX_2.6.15"),
|
||||||
|
("ppc/64", b"__kernel_clock_gettime", b"LINUX_2.6.15"),
|
||||||
|
("ppc/64", b"__kernel_datapage_offset", b"LINUX_2.6.15"),
|
||||||
|
("ppc/64", b"__kernel_get_syscall_map", b"LINUX_2.6.15"),
|
||||||
|
("ppc/64", b"__kernel_get_tbfreq", b"LINUX_2.6.15"),
|
||||||
|
("ppc/64", b"__kernel_getcpu", b"LINUX_2.6.15"),
|
||||||
|
("ppc/64", b"__kernel_gettimeofday", b"LINUX_2.6.15"),
|
||||||
|
("ppc/64", b"__kernel_sigtramp_rt64", b"LINUX_2.6.15"),
|
||||||
|
("ppc/64", b"__kernel_sync_dicache", b"LINUX_2.6.15"),
|
||||||
|
("ppc/64", b"__kernel_sync_dicache_p5", b"LINUX_2.6.15"),
|
||||||
|
("riscv", b"__vdso_rt_sigreturn", b"LINUX_4.15"),
|
||||||
|
("riscv", b"__vdso_gettimeofday", b"LINUX_4.15"),
|
||||||
|
("riscv", b"__vdso_clock_gettime", b"LINUX_4.15"),
|
||||||
|
("riscv", b"__vdso_clock_getres", b"LINUX_4.15"),
|
||||||
|
("riscv", b"__vdso_getcpu", b"LINUX_4.15"),
|
||||||
|
("riscv", b"__vdso_flush_icache", b"LINUX_4.15"),
|
||||||
|
("s390", b"__kernel_clock_getres", b"LINUX_2.6.29"),
|
||||||
|
("s390", b"__kernel_clock_gettime", b"LINUX_2.6.29"),
|
||||||
|
("s390", b"__kernel_gettimeofday", b"LINUX_2.6.29"),
|
||||||
|
("superh", b"__kernel_rt_sigreturn", b"LINUX_2.6"),
|
||||||
|
("superh", b"__kernel_sigreturn", b"LINUX_2.6"),
|
||||||
|
("superh", b"__kernel_vsyscall", b"LINUX_2.6"),
|
||||||
|
("i386", b"__kernel_sigreturn", b"LINUX_2.5"),
|
||||||
|
("i386", b"__kernel_rt_sigreturn", b"LINUX_2.5"),
|
||||||
|
("i386", b"__kernel_vsyscall", b"LINUX_2.5"),
|
||||||
|
("i386", b"__vdso_clock_gettime", b"LINUX_2.6"),
|
||||||
|
("i386", b"__vdso_gettimeofday", b"LINUX_2.6"),
|
||||||
|
("i386", b"__vdso_time", b"LINUX_2.6"),
|
||||||
|
("x86-64", b"__vdso_clock_gettime", b"LINUX_2.6"),
|
||||||
|
("x86-64", b"__vdso_getcpu", b"LINUX_2.6"),
|
||||||
|
("x86-64", b"__vdso_gettimeofday", b"LINUX_2.6"),
|
||||||
|
("x86-64", b"__vdso_time", b"LINUX_2.6"),
|
||||||
|
("x86/32", b"__vdso_clock_gettime", b"LINUX_2.6"),
|
||||||
|
("x86/32", b"__vdso_getcpu", b"LINUX_2.6"),
|
||||||
|
("x86/32", b"__vdso_gettimeofday", b"LINUX_2.6"),
|
||||||
|
("x86/32", b"__vdso_time", b"LINUX_2.6"),
|
||||||
|
):
|
||||||
|
if symbol in buf and version in buf:
|
||||||
|
logger.debug("vdso string: %s %s %s", arch, symbol.decode("ascii"), version.decode("ascii"))
|
||||||
|
return OS.LINUX
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def detect_elf_os(f) -> str:
|
def detect_elf_os(f) -> str:
|
||||||
"""
|
"""
|
||||||
f: type Union[BinaryIO, IDAIO, GHIDRAIO]
|
f: type Union[BinaryIO, IDAIO, GHIDRAIO]
|
||||||
@@ -927,6 +1491,13 @@ def detect_elf_os(f) -> str:
|
|||||||
logger.warning("Error guessing OS from section header notes: %s", e)
|
logger.warning("Error guessing OS from section header notes: %s", e)
|
||||||
sh_notes_guess = None
|
sh_notes_guess = None
|
||||||
|
|
||||||
|
try:
|
||||||
|
ident_guess = guess_os_from_ident_directive(elf)
|
||||||
|
logger.debug("guess: .ident: %s", ident_guess)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Error guessing OS from .ident directive: %s", e)
|
||||||
|
ident_guess = None
|
||||||
|
|
||||||
try:
|
try:
|
||||||
linker_guess = guess_os_from_linker(elf)
|
linker_guess = guess_os_from_linker(elf)
|
||||||
logger.debug("guess: linker: %s", linker_guess)
|
logger.debug("guess: linker: %s", linker_guess)
|
||||||
@@ -955,6 +1526,27 @@ def detect_elf_os(f) -> str:
|
|||||||
logger.warning("Error guessing OS from symbol table: %s", e)
|
logger.warning("Error guessing OS from symbol table: %s", e)
|
||||||
symtab_guess = None
|
symtab_guess = None
|
||||||
|
|
||||||
|
try:
|
||||||
|
goos_guess = guess_os_from_go_buildinfo(elf)
|
||||||
|
logger.debug("guess: Go buildinfo: %s", goos_guess)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Error guessing OS from Go buildinfo: %s", e)
|
||||||
|
goos_guess = None
|
||||||
|
|
||||||
|
try:
|
||||||
|
gosrc_guess = guess_os_from_go_source(elf)
|
||||||
|
logger.debug("guess: Go source: %s", gosrc_guess)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Error guessing OS from Go source path: %s", e)
|
||||||
|
gosrc_guess = None
|
||||||
|
|
||||||
|
try:
|
||||||
|
vdso_guess = guess_os_from_vdso_strings(elf)
|
||||||
|
logger.debug("guess: vdso strings: %s", vdso_guess)
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Error guessing OS from vdso strings: %s", e)
|
||||||
|
symtab_guess = None
|
||||||
|
|
||||||
ret = None
|
ret = None
|
||||||
|
|
||||||
if osabi_guess:
|
if osabi_guess:
|
||||||
@@ -978,6 +1570,24 @@ def detect_elf_os(f) -> str:
|
|||||||
elif symtab_guess:
|
elif symtab_guess:
|
||||||
ret = symtab_guess
|
ret = symtab_guess
|
||||||
|
|
||||||
|
elif goos_guess:
|
||||||
|
ret = goos_guess
|
||||||
|
|
||||||
|
elif gosrc_guess:
|
||||||
|
# prefer goos_guess to this method,
|
||||||
|
# which is just string interpretation.
|
||||||
|
ret = gosrc_guess
|
||||||
|
|
||||||
|
elif ident_guess:
|
||||||
|
# at the bottom because we don't trust this too much
|
||||||
|
# due to potential for bugs with cross-compilation.
|
||||||
|
ret = ident_guess
|
||||||
|
|
||||||
|
elif vdso_guess:
|
||||||
|
# at the bottom because this is just scanning strings,
|
||||||
|
# which isn't very authoritative.
|
||||||
|
ret = vdso_guess
|
||||||
|
|
||||||
return ret.value if ret is not None else "unknown"
|
return ret.value if ret is not None else "unknown"
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
# Copyright (C) 2021 Mandiant, Inc. All Rights Reserved.
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
# you may not use this file except in compliance with the License.
|
# you may not use this file except in compliance with the License.
|
||||||
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
||||||
@@ -10,14 +10,13 @@ import logging
|
|||||||
from typing import Tuple, Iterator
|
from typing import Tuple, Iterator
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from elftools.elf.elffile import ELFFile, SymbolTableSection
|
from elftools.elf.elffile import ELFFile, DynamicSegment, SymbolTableSection
|
||||||
from elftools.elf.relocation import RelocationSection
|
|
||||||
|
|
||||||
import capa.features.extractors.common
|
import capa.features.extractors.common
|
||||||
from capa.features.file import Export, Import, Section
|
from capa.features.file import Export, Import, Section
|
||||||
from capa.features.common import OS, FORMAT_ELF, Arch, Format, Feature
|
from capa.features.common import OS, FORMAT_ELF, Arch, Format, Feature
|
||||||
from capa.features.address import NO_ADDRESS, FileOffsetAddress, AbsoluteVirtualAddress
|
from capa.features.address import NO_ADDRESS, FileOffsetAddress, AbsoluteVirtualAddress
|
||||||
from capa.features.extractors.base_extractor import FeatureExtractor
|
from capa.features.extractors.base_extractor import SampleHashes, StaticFeatureExtractor
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -47,17 +46,47 @@ def extract_file_export_names(elf: ELFFile, **kwargs):
|
|||||||
|
|
||||||
yield Export(symbol.name), AbsoluteVirtualAddress(symbol.entry.st_value)
|
yield Export(symbol.name), AbsoluteVirtualAddress(symbol.entry.st_value)
|
||||||
|
|
||||||
|
for segment in elf.iter_segments():
|
||||||
|
if not isinstance(segment, DynamicSegment):
|
||||||
|
continue
|
||||||
|
|
||||||
|
tab_ptr, tab_offset = segment.get_table_offset("DT_SYMTAB")
|
||||||
|
if tab_ptr is None or tab_offset is None:
|
||||||
|
logger.debug("Dynamic segment doesn't contain DT_SYMTAB")
|
||||||
|
continue
|
||||||
|
|
||||||
|
logger.debug("Dynamic segment contains %s symbols: ", segment.num_symbols())
|
||||||
|
|
||||||
|
for symbol in segment.iter_symbols():
|
||||||
|
# The following conditions are based on the following article
|
||||||
|
# http://www.m4b.io/elf/export/binary/analysis/2015/05/25/what-is-an-elf-export.html
|
||||||
|
if not symbol.name:
|
||||||
|
continue
|
||||||
|
if symbol.entry.st_info.type not in ["STT_FUNC", "STT_OBJECT", "STT_IFUNC"]:
|
||||||
|
continue
|
||||||
|
if symbol.entry.st_value == 0:
|
||||||
|
continue
|
||||||
|
if symbol.entry.st_shndx == "SHN_UNDEF":
|
||||||
|
continue
|
||||||
|
|
||||||
|
yield Export(symbol.name), AbsoluteVirtualAddress(symbol.entry.st_value)
|
||||||
|
|
||||||
|
|
||||||
def extract_file_import_names(elf: ELFFile, **kwargs):
|
def extract_file_import_names(elf: ELFFile, **kwargs):
|
||||||
# Create a dictionary to store symbol names by their index
|
# Create a dictionary to store symbol names by their index
|
||||||
symbol_names = {}
|
symbol_names = {}
|
||||||
|
|
||||||
# Extract symbol names and store them in the dictionary
|
# Extract symbol names and store them in the dictionary
|
||||||
for section in elf.iter_sections():
|
for segment in elf.iter_segments():
|
||||||
if not isinstance(section, SymbolTableSection):
|
if not isinstance(segment, DynamicSegment):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
for _, symbol in enumerate(section.iter_symbols()):
|
tab_ptr, tab_offset = segment.get_table_offset("DT_SYMTAB")
|
||||||
|
if tab_ptr is None or tab_offset is None:
|
||||||
|
logger.debug("Dynamic segment doesn't contain DT_SYMTAB")
|
||||||
|
continue
|
||||||
|
|
||||||
|
for _, symbol in enumerate(segment.iter_symbols()):
|
||||||
# The following conditions are based on the following article
|
# The following conditions are based on the following article
|
||||||
# http://www.m4b.io/elf/export/binary/analysis/2015/05/25/what-is-an-elf-export.html
|
# http://www.m4b.io/elf/export/binary/analysis/2015/05/25/what-is-an-elf-export.html
|
||||||
if not symbol.name:
|
if not symbol.name:
|
||||||
@@ -73,17 +102,24 @@ def extract_file_import_names(elf: ELFFile, **kwargs):
|
|||||||
|
|
||||||
symbol_names[_] = symbol.name
|
symbol_names[_] = symbol.name
|
||||||
|
|
||||||
for section in elf.iter_sections():
|
for segment in elf.iter_segments():
|
||||||
if not isinstance(section, RelocationSection):
|
if not isinstance(segment, DynamicSegment):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if section["sh_entsize"] == 0:
|
relocation_tables = segment.get_relocation_tables()
|
||||||
logger.debug("Symbol table '%s' has a sh_entsize of zero!", section.name)
|
logger.debug("Dynamic Segment contains %s relocation tables:", len(relocation_tables))
|
||||||
continue
|
|
||||||
|
|
||||||
logger.debug("Symbol table '%s' contains %s entries:", section.name, section.num_relocations())
|
for relocation_table in relocation_tables.values():
|
||||||
|
relocations = []
|
||||||
|
for i in range(relocation_table.num_relocations()):
|
||||||
|
try:
|
||||||
|
relocations.append(relocation_table.get_relocation(i))
|
||||||
|
except TypeError:
|
||||||
|
# ELF is corrupt and the relocation table is invalid,
|
||||||
|
# so stop processing it.
|
||||||
|
break
|
||||||
|
|
||||||
for relocation in section.iter_relocations():
|
for relocation in relocations:
|
||||||
# Extract the symbol name from the symbol table using the symbol index in the relocation
|
# Extract the symbol name from the symbol table using the symbol index in the relocation
|
||||||
if relocation["r_info_sym"] not in symbol_names:
|
if relocation["r_info_sym"] not in symbol_names:
|
||||||
continue
|
continue
|
||||||
@@ -122,6 +158,10 @@ def extract_file_arch(elf: ELFFile, **kwargs):
|
|||||||
yield Arch("i386"), NO_ADDRESS
|
yield Arch("i386"), NO_ADDRESS
|
||||||
elif arch == "x64":
|
elif arch == "x64":
|
||||||
yield Arch("amd64"), NO_ADDRESS
|
yield Arch("amd64"), NO_ADDRESS
|
||||||
|
elif arch == "ARM":
|
||||||
|
yield Arch("arm"), NO_ADDRESS
|
||||||
|
elif arch == "AArch64":
|
||||||
|
yield Arch("aarch64"), NO_ADDRESS
|
||||||
else:
|
else:
|
||||||
logger.warning("unsupported architecture: %s", arch)
|
logger.warning("unsupported architecture: %s", arch)
|
||||||
|
|
||||||
@@ -154,9 +194,9 @@ GLOBAL_HANDLERS = (
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class ElfFeatureExtractor(FeatureExtractor):
|
class ElfFeatureExtractor(StaticFeatureExtractor):
|
||||||
def __init__(self, path: Path):
|
def __init__(self, path: Path):
|
||||||
super().__init__()
|
super().__init__(SampleHashes.from_bytes(path.read_bytes()))
|
||||||
self.path: Path = path
|
self.path: Path = path
|
||||||
self.elf = ELFFile(io.BytesIO(path.read_bytes()))
|
self.elf = ELFFile(io.BytesIO(path.read_bytes()))
|
||||||
|
|
||||||
|
|||||||
@@ -14,14 +14,32 @@ import capa.features.extractors.ghidra.function
|
|||||||
import capa.features.extractors.ghidra.basicblock
|
import capa.features.extractors.ghidra.basicblock
|
||||||
from capa.features.common import Feature
|
from capa.features.common import Feature
|
||||||
from capa.features.address import Address, AbsoluteVirtualAddress
|
from capa.features.address import Address, AbsoluteVirtualAddress
|
||||||
from capa.features.extractors.base_extractor import BBHandle, InsnHandle, FunctionHandle, FeatureExtractor
|
from capa.features.extractors.base_extractor import (
|
||||||
|
BBHandle,
|
||||||
|
InsnHandle,
|
||||||
|
SampleHashes,
|
||||||
|
FunctionHandle,
|
||||||
|
StaticFeatureExtractor,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class GhidraFeatureExtractor(FeatureExtractor):
|
class GhidraFeatureExtractor(StaticFeatureExtractor):
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
super().__init__()
|
|
||||||
import capa.features.extractors.ghidra.helpers as ghidra_helpers
|
import capa.features.extractors.ghidra.helpers as ghidra_helpers
|
||||||
|
|
||||||
|
super().__init__(
|
||||||
|
SampleHashes(
|
||||||
|
md5=capa.ghidra.helpers.get_file_md5(),
|
||||||
|
# ghidra doesn't expose this hash.
|
||||||
|
# https://ghidra.re/ghidra_docs/api/ghidra/program/model/listing/Program.html
|
||||||
|
#
|
||||||
|
# the hashes are stored in the database, not computed on the fly,
|
||||||
|
# so it's probably not trivial to add SHA1.
|
||||||
|
sha1="",
|
||||||
|
sha256=capa.ghidra.helpers.get_file_sha256(),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
self.global_features: List[Tuple[Feature, Address]] = []
|
self.global_features: List[Tuple[Feature, Address]] = []
|
||||||
self.global_features.extend(capa.features.extractors.ghidra.file.extract_file_format())
|
self.global_features.extend(capa.features.extractors.ghidra.file.extract_file_format())
|
||||||
self.global_features.extend(capa.features.extractors.ghidra.global_.extract_os())
|
self.global_features.extend(capa.features.extractors.ghidra.global_.extract_os())
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ def find_embedded_pe(block_bytez: bytes, mz_xor: List[Tuple[bytes, bytes, int]])
|
|||||||
for match in re.finditer(re.escape(mzx), block_bytez):
|
for match in re.finditer(re.escape(mzx), block_bytez):
|
||||||
todo.append((match.start(), mzx, pex, i))
|
todo.append((match.start(), mzx, pex, i))
|
||||||
|
|
||||||
seg_max = len(block_bytez) # type: ignore [name-defined] # noqa: F821
|
seg_max = len(block_bytez) # noqa: F821
|
||||||
while len(todo):
|
while len(todo):
|
||||||
off, mzx, pex, i = todo.pop()
|
off, mzx, pex, i = todo.pop()
|
||||||
|
|
||||||
@@ -112,7 +112,7 @@ def extract_file_import_names() -> Iterator[Tuple[Feature, Address]]:
|
|||||||
if "Ordinal_" in fstr[1]:
|
if "Ordinal_" in fstr[1]:
|
||||||
fstr[1] = f"#{fstr[1].split('_')[1]}"
|
fstr[1] = f"#{fstr[1].split('_')[1]}"
|
||||||
|
|
||||||
for name in capa.features.extractors.helpers.generate_symbols(fstr[0][:-4], fstr[1]):
|
for name in capa.features.extractors.helpers.generate_symbols(fstr[0][:-4], fstr[1], include_dll=True):
|
||||||
yield Import(name), AbsoluteVirtualAddress(addr)
|
yield Import(name), AbsoluteVirtualAddress(addr)
|
||||||
|
|
||||||
|
|
||||||
@@ -127,7 +127,9 @@ def extract_file_strings() -> Iterator[Tuple[Feature, Address]]:
|
|||||||
"""extract ASCII and UTF-16 LE strings"""
|
"""extract ASCII and UTF-16 LE strings"""
|
||||||
|
|
||||||
for block in currentProgram().getMemory().getBlocks(): # type: ignore [name-defined] # noqa: F821
|
for block in currentProgram().getMemory().getBlocks(): # type: ignore [name-defined] # noqa: F821
|
||||||
if block.isInitialized():
|
if not block.isInitialized():
|
||||||
|
continue
|
||||||
|
|
||||||
p_bytes = capa.features.extractors.ghidra.helpers.get_block_bytes(block)
|
p_bytes = capa.features.extractors.ghidra.helpers.get_block_bytes(block)
|
||||||
|
|
||||||
for s in capa.features.extractors.strings.extract_ascii_strings(p_bytes):
|
for s in capa.features.extractors.strings.extract_ascii_strings(p_bytes):
|
||||||
|
|||||||
@@ -260,7 +260,7 @@ def dereference_ptr(insn: ghidra.program.database.code.InstructionDB):
|
|||||||
if thfunc and thfunc.isThunk():
|
if thfunc and thfunc.isThunk():
|
||||||
return handle_thunk(to_deref)
|
return handle_thunk(to_deref)
|
||||||
else:
|
else:
|
||||||
# if it doesn't poin to a thunk, it's usually a jmp to a label
|
# if it doesn't point to a thunk, it's usually a jmp to a label
|
||||||
return to_deref
|
return to_deref
|
||||||
if not dat:
|
if not dat:
|
||||||
return to_deref
|
return to_deref
|
||||||
@@ -275,3 +275,27 @@ def dereference_ptr(insn: ghidra.program.database.code.InstructionDB):
|
|||||||
return addr
|
return addr
|
||||||
else:
|
else:
|
||||||
return to_deref
|
return to_deref
|
||||||
|
|
||||||
|
|
||||||
|
def find_data_references_from_insn(insn, max_depth: int = 10):
|
||||||
|
"""yield data references from given instruction"""
|
||||||
|
for reference in insn.getReferencesFrom():
|
||||||
|
if not reference.getReferenceType().isData():
|
||||||
|
# only care about data references
|
||||||
|
continue
|
||||||
|
|
||||||
|
to_addr = reference.getToAddress()
|
||||||
|
|
||||||
|
for _ in range(max_depth - 1):
|
||||||
|
data = getDataAt(to_addr) # type: ignore [name-defined] # noqa: F821
|
||||||
|
if data and data.isPointer():
|
||||||
|
ptr_value = data.getValue()
|
||||||
|
|
||||||
|
if ptr_value is None:
|
||||||
|
break
|
||||||
|
|
||||||
|
to_addr = ptr_value
|
||||||
|
else:
|
||||||
|
break
|
||||||
|
|
||||||
|
yield to_addr
|
||||||
|
|||||||
@@ -23,6 +23,9 @@ from capa.features.extractors.base_extractor import BBHandle, InsnHandle, Functi
|
|||||||
SECURITY_COOKIE_BYTES_DELTA = 0x40
|
SECURITY_COOKIE_BYTES_DELTA = 0x40
|
||||||
|
|
||||||
|
|
||||||
|
OPERAND_TYPE_DYNAMIC_ADDRESS = OperandType.DYNAMIC | OperandType.ADDRESS
|
||||||
|
|
||||||
|
|
||||||
def get_imports(ctx: Dict[str, Any]) -> Dict[int, Any]:
|
def get_imports(ctx: Dict[str, Any]) -> Dict[int, Any]:
|
||||||
"""Populate the import cache for this context"""
|
"""Populate the import cache for this context"""
|
||||||
if "imports_cache" not in ctx:
|
if "imports_cache" not in ctx:
|
||||||
@@ -82,7 +85,7 @@ def check_for_api_call(
|
|||||||
if not capa.features.extractors.ghidra.helpers.check_addr_for_api(addr_ref, fakes, imports, externs):
|
if not capa.features.extractors.ghidra.helpers.check_addr_for_api(addr_ref, fakes, imports, externs):
|
||||||
return
|
return
|
||||||
ref = addr_ref.getOffset()
|
ref = addr_ref.getOffset()
|
||||||
elif ref_type == OperandType.DYNAMIC | OperandType.ADDRESS or ref_type == OperandType.DYNAMIC:
|
elif ref_type == OPERAND_TYPE_DYNAMIC_ADDRESS or ref_type == OperandType.DYNAMIC:
|
||||||
return # cannot resolve dynamics statically
|
return # cannot resolve dynamics statically
|
||||||
else:
|
else:
|
||||||
# pure address does not need to get dereferenced/ handled
|
# pure address does not need to get dereferenced/ handled
|
||||||
@@ -195,46 +198,39 @@ def extract_insn_offset_features(fh: FunctionHandle, bb: BBHandle, ih: InsnHandl
|
|||||||
if insn.getMnemonicString().startswith("LEA"):
|
if insn.getMnemonicString().startswith("LEA"):
|
||||||
return
|
return
|
||||||
|
|
||||||
# ignore any stack references
|
if capa.features.extractors.ghidra.helpers.is_stack_referenced(insn):
|
||||||
if not capa.features.extractors.ghidra.helpers.is_stack_referenced(insn):
|
# ignore stack references
|
||||||
|
return
|
||||||
|
|
||||||
# Ghidra stores operands in 2D arrays if they contain offsets
|
# Ghidra stores operands in 2D arrays if they contain offsets
|
||||||
for i in range(insn.getNumOperands()):
|
for i in range(insn.getNumOperands()):
|
||||||
if insn.getOperandType(i) == OperandType.DYNAMIC: # e.g. [esi + 4]
|
if insn.getOperandType(i) == OperandType.DYNAMIC: # e.g. [esi + 4]
|
||||||
# manual extraction, since the default api calls only work on the 1st dimension of the array
|
# manual extraction, since the default api calls only work on the 1st dimension of the array
|
||||||
op_objs = insn.getOpObjects(i)
|
op_objs = insn.getOpObjects(i)
|
||||||
|
if not op_objs:
|
||||||
|
continue
|
||||||
|
|
||||||
if isinstance(op_objs[-1], ghidra.program.model.scalar.Scalar):
|
if isinstance(op_objs[-1], ghidra.program.model.scalar.Scalar):
|
||||||
op_off = op_objs[-1].getValue()
|
op_off = op_objs[-1].getValue()
|
||||||
|
else:
|
||||||
|
op_off = 0
|
||||||
|
|
||||||
yield Offset(op_off), ih.address
|
yield Offset(op_off), ih.address
|
||||||
yield OperandOffset(i, op_off), ih.address
|
yield OperandOffset(i, op_off), ih.address
|
||||||
else:
|
|
||||||
yield Offset(0), ih.address
|
|
||||||
yield OperandOffset(i, 0), ih.address
|
|
||||||
|
|
||||||
|
|
||||||
def extract_insn_bytes_features(fh: FunctionHandle, bb: BBHandle, ih: InsnHandle) -> Iterator[Tuple[Feature, Address]]:
|
def extract_insn_bytes_features(fh: FunctionHandle, bb: BBHandle, ih: InsnHandle) -> Iterator[Tuple[Feature, Address]]:
|
||||||
"""
|
"""
|
||||||
parse referenced byte sequences
|
parse referenced byte sequences
|
||||||
|
|
||||||
example:
|
example:
|
||||||
push offset iid_004118d4_IShellLinkA ; riid
|
push offset iid_004118d4_IShellLinkA ; riid
|
||||||
"""
|
"""
|
||||||
insn: ghidra.program.database.code.InstructionDB = ih.inner
|
for addr in capa.features.extractors.ghidra.helpers.find_data_references_from_insn(ih.inner):
|
||||||
|
data = getDataAt(addr) # type: ignore [name-defined] # noqa: F821
|
||||||
if capa.features.extractors.ghidra.helpers.is_call_or_jmp(insn):
|
if data and not data.hasStringValue():
|
||||||
return
|
extracted_bytes = capa.features.extractors.ghidra.helpers.get_bytes(addr, MAX_BYTES_FEATURE_SIZE)
|
||||||
|
|
||||||
ref = insn.getAddress() # init to insn addr
|
|
||||||
for i in range(insn.getNumOperands()):
|
|
||||||
if OperandType.isAddress(insn.getOperandType(i)):
|
|
||||||
ref = insn.getAddress(i) # pulls pointer if there is one
|
|
||||||
|
|
||||||
if ref != insn.getAddress(): # bail out if there's no pointer
|
|
||||||
ghidra_dat = getDataAt(ref) # type: ignore [name-defined] # noqa: F821
|
|
||||||
if (
|
|
||||||
ghidra_dat and not ghidra_dat.hasStringValue() and not ghidra_dat.isPointer()
|
|
||||||
): # avoid if the data itself is a pointer
|
|
||||||
extracted_bytes = capa.features.extractors.ghidra.helpers.get_bytes(ref, MAX_BYTES_FEATURE_SIZE)
|
|
||||||
if extracted_bytes and not capa.features.extractors.helpers.all_zeros(extracted_bytes):
|
if extracted_bytes and not capa.features.extractors.helpers.all_zeros(extracted_bytes):
|
||||||
# don't extract byte features for obvious strings
|
|
||||||
yield Bytes(extracted_bytes), ih.address
|
yield Bytes(extracted_bytes), ih.address
|
||||||
|
|
||||||
|
|
||||||
@@ -245,24 +241,10 @@ def extract_insn_string_features(fh: FunctionHandle, bb: BBHandle, ih: InsnHandl
|
|||||||
example:
|
example:
|
||||||
push offset aAcr ; "ACR > "
|
push offset aAcr ; "ACR > "
|
||||||
"""
|
"""
|
||||||
insn: ghidra.program.database.code.InstructionDB = ih.inner
|
for addr in capa.features.extractors.ghidra.helpers.find_data_references_from_insn(ih.inner):
|
||||||
dyn_addr = OperandType.DYNAMIC | OperandType.ADDRESS
|
data = getDataAt(addr) # type: ignore [name-defined] # noqa: F821
|
||||||
|
if data and data.hasStringValue():
|
||||||
ref = insn.getAddress()
|
yield String(data.getValue()), ih.address
|
||||||
for i in range(insn.getNumOperands()):
|
|
||||||
if OperandType.isScalarAsAddress(insn.getOperandType(i)):
|
|
||||||
ref = insn.getAddress(i)
|
|
||||||
# strings are also referenced dynamically via pointers & arrays, so we need to deref them
|
|
||||||
if insn.getOperandType(i) == dyn_addr:
|
|
||||||
ref = insn.getAddress(i)
|
|
||||||
dat = getDataAt(ref) # type: ignore [name-defined] # noqa: F821
|
|
||||||
if dat and dat.isPointer():
|
|
||||||
ref = dat.getValue()
|
|
||||||
|
|
||||||
if ref != insn.getAddress():
|
|
||||||
ghidra_dat = getDataAt(ref) # type: ignore [name-defined] # noqa: F821
|
|
||||||
if ghidra_dat and ghidra_dat.hasStringValue():
|
|
||||||
yield String(ghidra_dat.getValue()), ih.address
|
|
||||||
|
|
||||||
|
|
||||||
def extract_insn_mnemonic_features(
|
def extract_insn_mnemonic_features(
|
||||||
@@ -359,7 +341,7 @@ def extract_insn_cross_section_cflow(
|
|||||||
ref = capa.features.extractors.ghidra.helpers.dereference_ptr(insn)
|
ref = capa.features.extractors.ghidra.helpers.dereference_ptr(insn)
|
||||||
if capa.features.extractors.ghidra.helpers.check_addr_for_api(ref, fakes, imports, externs):
|
if capa.features.extractors.ghidra.helpers.check_addr_for_api(ref, fakes, imports, externs):
|
||||||
return
|
return
|
||||||
elif ref_type == OperandType.DYNAMIC | OperandType.ADDRESS or ref_type == OperandType.DYNAMIC:
|
elif ref_type == OPERAND_TYPE_DYNAMIC_ADDRESS or ref_type == OperandType.DYNAMIC:
|
||||||
return # cannot resolve dynamics statically
|
return # cannot resolve dynamics statically
|
||||||
else:
|
else:
|
||||||
# pure address does not need to get dereferenced/ handled
|
# pure address does not need to get dereferenced/ handled
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
# Copyright (C) 2020 Mandiant, Inc. All Rights Reserved.
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
# you may not use this file except in compliance with the License.
|
# you may not use this file except in compliance with the License.
|
||||||
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
||||||
@@ -41,19 +41,32 @@ def is_ordinal(symbol: str) -> bool:
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def generate_symbols(dll: str, symbol: str) -> Iterator[str]:
|
def generate_symbols(dll: str, symbol: str, include_dll=False) -> Iterator[str]:
|
||||||
"""
|
"""
|
||||||
for a given dll and symbol name, generate variants.
|
for a given dll and symbol name, generate variants.
|
||||||
we over-generate features to make matching easier.
|
we over-generate features to make matching easier.
|
||||||
these include:
|
these include:
|
||||||
- kernel32.CreateFileA
|
|
||||||
- kernel32.CreateFile
|
|
||||||
- CreateFileA
|
- CreateFileA
|
||||||
- CreateFile
|
- CreateFile
|
||||||
|
- ws2_32.#1
|
||||||
|
|
||||||
|
note that since capa v7 only `import` features and APIs called via ordinal include DLL names:
|
||||||
|
- kernel32.CreateFileA
|
||||||
|
- kernel32.CreateFile
|
||||||
|
- ws2_32.#1
|
||||||
|
|
||||||
|
for `api` features dll names are good for documentation but not used during matching
|
||||||
"""
|
"""
|
||||||
# normalize dll name
|
# normalize dll name
|
||||||
dll = dll.lower()
|
dll = dll.lower()
|
||||||
|
|
||||||
|
# trim extensions observed in dynamic traces
|
||||||
|
dll = dll[0:-4] if dll.endswith(".dll") else dll
|
||||||
|
dll = dll[0:-4] if dll.endswith(".drv") else dll
|
||||||
|
dll = dll[0:-3] if dll.endswith(".so") else dll
|
||||||
|
|
||||||
|
if include_dll or is_ordinal(symbol):
|
||||||
|
# ws2_32.#1
|
||||||
# kernel32.CreateFileA
|
# kernel32.CreateFileA
|
||||||
yield f"{dll}.{symbol}"
|
yield f"{dll}.{symbol}"
|
||||||
|
|
||||||
@@ -62,17 +75,17 @@ def generate_symbols(dll: str, symbol: str) -> Iterator[str]:
|
|||||||
yield symbol
|
yield symbol
|
||||||
|
|
||||||
if is_aw_function(symbol):
|
if is_aw_function(symbol):
|
||||||
|
if include_dll:
|
||||||
# kernel32.CreateFile
|
# kernel32.CreateFile
|
||||||
yield f"{dll}.{symbol[:-1]}"
|
yield f"{dll}.{symbol[:-1]}"
|
||||||
|
|
||||||
if not is_ordinal(symbol):
|
|
||||||
# CreateFile
|
# CreateFile
|
||||||
yield symbol[:-1]
|
yield symbol[:-1]
|
||||||
|
|
||||||
|
|
||||||
def reformat_forwarded_export_name(forwarded_name: str) -> str:
|
def reformat_forwarded_export_name(forwarded_name: str) -> str:
|
||||||
"""
|
"""
|
||||||
a forwarded export has a DLL name/path an symbol name.
|
a forwarded export has a DLL name/path and symbol name.
|
||||||
we want the former to be lowercase, and the latter to be verbatim.
|
we want the former to be lowercase, and the latter to be verbatim.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
# Copyright (C) 2020 Mandiant, Inc. All Rights Reserved.
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
# you may not use this file except in compliance with the License.
|
# you may not use this file except in compliance with the License.
|
||||||
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
# Copyright (C) 2021 Mandiant, Inc. All Rights Reserved.
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
# you may not use this file except in compliance with the License.
|
# you may not use this file except in compliance with the License.
|
||||||
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
||||||
@@ -18,12 +18,24 @@ import capa.features.extractors.ida.function
|
|||||||
import capa.features.extractors.ida.basicblock
|
import capa.features.extractors.ida.basicblock
|
||||||
from capa.features.common import Feature
|
from capa.features.common import Feature
|
||||||
from capa.features.address import Address, AbsoluteVirtualAddress
|
from capa.features.address import Address, AbsoluteVirtualAddress
|
||||||
from capa.features.extractors.base_extractor import BBHandle, InsnHandle, FunctionHandle, FeatureExtractor
|
from capa.features.extractors.base_extractor import (
|
||||||
|
BBHandle,
|
||||||
|
InsnHandle,
|
||||||
|
SampleHashes,
|
||||||
|
FunctionHandle,
|
||||||
|
StaticFeatureExtractor,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class IdaFeatureExtractor(FeatureExtractor):
|
class IdaFeatureExtractor(StaticFeatureExtractor):
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
super().__init__()
|
super().__init__(
|
||||||
|
hashes=SampleHashes(
|
||||||
|
md5=capa.ida.helpers.retrieve_input_file_md5(),
|
||||||
|
sha1="(unknown)",
|
||||||
|
sha256=capa.ida.helpers.retrieve_input_file_sha256(),
|
||||||
|
)
|
||||||
|
)
|
||||||
self.global_features: List[Tuple[Feature, Address]] = []
|
self.global_features: List[Tuple[Feature, Address]] = []
|
||||||
self.global_features.extend(capa.features.extractors.ida.file.extract_file_format())
|
self.global_features.extend(capa.features.extractors.ida.file.extract_file_format())
|
||||||
self.global_features.extend(capa.features.extractors.ida.global_.extract_os())
|
self.global_features.extend(capa.features.extractors.ida.global_.extract_os())
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
# Copyright (C) 2020 Mandiant, Inc. All Rights Reserved.
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
# you may not use this file except in compliance with the License.
|
# you may not use this file except in compliance with the License.
|
||||||
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
||||||
@@ -14,6 +14,7 @@ import idaapi
|
|||||||
import idautils
|
import idautils
|
||||||
import ida_entry
|
import ida_entry
|
||||||
|
|
||||||
|
import capa.ida.helpers
|
||||||
import capa.features.extractors.common
|
import capa.features.extractors.common
|
||||||
import capa.features.extractors.helpers
|
import capa.features.extractors.helpers
|
||||||
import capa.features.extractors.strings
|
import capa.features.extractors.strings
|
||||||
@@ -110,7 +111,7 @@ def extract_file_import_names() -> Iterator[Tuple[Feature, Address]]:
|
|||||||
if info[1] and info[2]:
|
if info[1] and info[2]:
|
||||||
# e.g. in mimikatz: ('cabinet', 'FCIAddFile', 11L)
|
# e.g. in mimikatz: ('cabinet', 'FCIAddFile', 11L)
|
||||||
# extract by name here and by ordinal below
|
# extract by name here and by ordinal below
|
||||||
for name in capa.features.extractors.helpers.generate_symbols(info[0], info[1]):
|
for name in capa.features.extractors.helpers.generate_symbols(info[0], info[1], include_dll=True):
|
||||||
yield Import(name), addr
|
yield Import(name), addr
|
||||||
dll = info[0]
|
dll = info[0]
|
||||||
symbol = f"#{info[2]}"
|
symbol = f"#{info[2]}"
|
||||||
@@ -123,7 +124,7 @@ def extract_file_import_names() -> Iterator[Tuple[Feature, Address]]:
|
|||||||
else:
|
else:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
for name in capa.features.extractors.helpers.generate_symbols(dll, symbol):
|
for name in capa.features.extractors.helpers.generate_symbols(dll, symbol, include_dll=True):
|
||||||
yield Import(name), addr
|
yield Import(name), addr
|
||||||
|
|
||||||
for ea, info in capa.features.extractors.ida.helpers.get_file_externs().items():
|
for ea, info in capa.features.extractors.ida.helpers.get_file_externs().items():
|
||||||
@@ -177,17 +178,17 @@ def extract_file_function_names() -> Iterator[Tuple[Feature, Address]]:
|
|||||||
|
|
||||||
|
|
||||||
def extract_file_format() -> Iterator[Tuple[Feature, Address]]:
|
def extract_file_format() -> Iterator[Tuple[Feature, Address]]:
|
||||||
file_info = idaapi.get_inf_structure()
|
filetype = capa.ida.helpers.get_filetype()
|
||||||
|
|
||||||
if file_info.filetype in (idaapi.f_PE, idaapi.f_COFF):
|
if filetype in (idaapi.f_PE, idaapi.f_COFF):
|
||||||
yield Format(FORMAT_PE), NO_ADDRESS
|
yield Format(FORMAT_PE), NO_ADDRESS
|
||||||
elif file_info.filetype == idaapi.f_ELF:
|
elif filetype == idaapi.f_ELF:
|
||||||
yield Format(FORMAT_ELF), NO_ADDRESS
|
yield Format(FORMAT_ELF), NO_ADDRESS
|
||||||
elif file_info.filetype == idaapi.f_BIN:
|
elif filetype == idaapi.f_BIN:
|
||||||
# no file type to return when processing a binary file, but we want to continue processing
|
# no file type to return when processing a binary file, but we want to continue processing
|
||||||
return
|
return
|
||||||
else:
|
else:
|
||||||
raise NotImplementedError(f"unexpected file format: {file_info.filetype}")
|
raise NotImplementedError(f"unexpected file format: {filetype}")
|
||||||
|
|
||||||
|
|
||||||
def extract_features() -> Iterator[Tuple[Feature, Address]]:
|
def extract_features() -> Iterator[Tuple[Feature, Address]]:
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
# Copyright (C) 2020 Mandiant, Inc. All Rights Reserved.
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
# you may not use this file except in compliance with the License.
|
# you may not use this file except in compliance with the License.
|
||||||
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
# Copyright (C) 2021 Mandiant, Inc. All Rights Reserved.
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
# you may not use this file except in compliance with the License.
|
# you may not use this file except in compliance with the License.
|
||||||
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
||||||
@@ -9,7 +9,6 @@ import logging
|
|||||||
import contextlib
|
import contextlib
|
||||||
from typing import Tuple, Iterator
|
from typing import Tuple, Iterator
|
||||||
|
|
||||||
import idaapi
|
|
||||||
import ida_loader
|
import ida_loader
|
||||||
|
|
||||||
import capa.ida.helpers
|
import capa.ida.helpers
|
||||||
@@ -48,12 +47,12 @@ def extract_os() -> Iterator[Tuple[Feature, Address]]:
|
|||||||
|
|
||||||
|
|
||||||
def extract_arch() -> Iterator[Tuple[Feature, Address]]:
|
def extract_arch() -> Iterator[Tuple[Feature, Address]]:
|
||||||
info: idaapi.idainfo = idaapi.get_inf_structure()
|
procname = capa.ida.helpers.get_processor_name()
|
||||||
if info.procname == "metapc" and info.is_64bit():
|
if procname == "metapc" and capa.ida.helpers.is_64bit():
|
||||||
yield Arch(ARCH_AMD64), NO_ADDRESS
|
yield Arch(ARCH_AMD64), NO_ADDRESS
|
||||||
elif info.procname == "metapc" and info.is_32bit():
|
elif procname == "metapc" and capa.ida.helpers.is_32bit():
|
||||||
yield Arch(ARCH_I386), NO_ADDRESS
|
yield Arch(ARCH_I386), NO_ADDRESS
|
||||||
elif info.procname == "metapc":
|
elif procname == "metapc":
|
||||||
logger.debug("unsupported architecture: non-32-bit nor non-64-bit intel")
|
logger.debug("unsupported architecture: non-32-bit nor non-64-bit intel")
|
||||||
return
|
return
|
||||||
else:
|
else:
|
||||||
@@ -61,5 +60,5 @@ def extract_arch() -> Iterator[Tuple[Feature, Address]]:
|
|||||||
# 1. handling a new architecture (e.g. aarch64)
|
# 1. handling a new architecture (e.g. aarch64)
|
||||||
#
|
#
|
||||||
# for (1), this logic will need to be updated as the format is implemented.
|
# for (1), this logic will need to be updated as the format is implemented.
|
||||||
logger.debug("unsupported architecture: %s", info.procname)
|
logger.debug("unsupported architecture: %s", procname)
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
# Copyright (C) 2020 Mandiant, Inc. All Rights Reserved.
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
# you may not use this file except in compliance with the License.
|
# you may not use this file except in compliance with the License.
|
||||||
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
||||||
@@ -10,6 +10,7 @@ from typing import Any, Dict, Tuple, Iterator, Optional
|
|||||||
|
|
||||||
import idc
|
import idc
|
||||||
import idaapi
|
import idaapi
|
||||||
|
import ida_nalt
|
||||||
import idautils
|
import idautils
|
||||||
import ida_bytes
|
import ida_bytes
|
||||||
import ida_segment
|
import ida_segment
|
||||||
@@ -17,7 +18,37 @@ import ida_segment
|
|||||||
from capa.features.address import AbsoluteVirtualAddress
|
from capa.features.address import AbsoluteVirtualAddress
|
||||||
from capa.features.extractors.base_extractor import FunctionHandle
|
from capa.features.extractors.base_extractor import FunctionHandle
|
||||||
|
|
||||||
|
IDA_NALT_ENCODING = ida_nalt.get_default_encoding_idx(ida_nalt.BPU_1B) # use one byte-per-character encoding
|
||||||
|
|
||||||
|
|
||||||
|
if hasattr(ida_bytes, "parse_binpat_str"):
|
||||||
|
# TODO (mr): use find_bytes
|
||||||
|
# https://github.com/mandiant/capa/issues/2339
|
||||||
|
def find_byte_sequence(start: int, end: int, seq: bytes) -> Iterator[int]:
|
||||||
|
"""yield all ea of a given byte sequence
|
||||||
|
|
||||||
|
args:
|
||||||
|
start: min virtual address
|
||||||
|
end: max virtual address
|
||||||
|
seq: bytes to search e.g. b"\x01\x03"
|
||||||
|
"""
|
||||||
|
patterns = ida_bytes.compiled_binpat_vec_t()
|
||||||
|
|
||||||
|
seqstr = " ".join([f"{b:02x}" for b in seq])
|
||||||
|
err = ida_bytes.parse_binpat_str(patterns, 0, seqstr, 16, IDA_NALT_ENCODING)
|
||||||
|
|
||||||
|
if err:
|
||||||
|
return
|
||||||
|
|
||||||
|
while True:
|
||||||
|
ea, _ = ida_bytes.bin_search(start, end, patterns, ida_bytes.BIN_SEARCH_FORWARD)
|
||||||
|
if ea == idaapi.BADADDR:
|
||||||
|
break
|
||||||
|
start = ea + 1
|
||||||
|
yield ea
|
||||||
|
|
||||||
|
else:
|
||||||
|
# for IDA 7.5 and older; using deprecated find_binary instead of bin_search
|
||||||
def find_byte_sequence(start: int, end: int, seq: bytes) -> Iterator[int]:
|
def find_byte_sequence(start: int, end: int, seq: bytes) -> Iterator[int]:
|
||||||
"""yield all ea of a given byte sequence
|
"""yield all ea of a given byte sequence
|
||||||
|
|
||||||
@@ -28,8 +59,6 @@ def find_byte_sequence(start: int, end: int, seq: bytes) -> Iterator[int]:
|
|||||||
"""
|
"""
|
||||||
seqstr = " ".join([f"{b:02x}" for b in seq])
|
seqstr = " ".join([f"{b:02x}" for b in seq])
|
||||||
while True:
|
while True:
|
||||||
# TODO(mike-hunhoff): find_binary is deprecated. Please use ida_bytes.bin_search() instead.
|
|
||||||
# https://github.com/mandiant/capa/issues/1606
|
|
||||||
ea = idaapi.find_binary(start, end, seqstr, 0, idaapi.SEARCH_DOWN)
|
ea = idaapi.find_binary(start, end, seqstr, 0, idaapi.SEARCH_DOWN)
|
||||||
if ea == idaapi.BADADDR:
|
if ea == idaapi.BADADDR:
|
||||||
break
|
break
|
||||||
|
|||||||
117
capa/features/extractors/ida/idalib.py
Normal file
117
capa/features/extractors/ida/idalib.py
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
# Copyright (C) 2024 Mandiant, Inc. All Rights Reserved.
|
||||||
|
# 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: [package root]/LICENSE.txt
|
||||||
|
# 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.
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import importlib.util
|
||||||
|
from typing import Optional
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def is_idalib_installed() -> bool:
|
||||||
|
try:
|
||||||
|
return importlib.util.find_spec("idapro") is not None
|
||||||
|
except ModuleNotFoundError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def get_idalib_user_config_path() -> Optional[Path]:
|
||||||
|
"""Get the path to the user's config file based on platform following IDA's user directories."""
|
||||||
|
# derived from `py-activate-idalib.py` from IDA v9.0 Beta 4
|
||||||
|
|
||||||
|
if sys.platform == "win32":
|
||||||
|
# On Windows, use the %APPDATA%\Hex-Rays\IDA Pro directory
|
||||||
|
config_dir = Path(os.getenv("APPDATA")) / "Hex-Rays" / "IDA Pro"
|
||||||
|
else:
|
||||||
|
# On macOS and Linux, use ~/.idapro
|
||||||
|
config_dir = Path.home() / ".idapro"
|
||||||
|
|
||||||
|
# Return the full path to the config file (now in JSON format)
|
||||||
|
user_config_path = config_dir / "ida-config.json"
|
||||||
|
if not user_config_path.exists():
|
||||||
|
return None
|
||||||
|
return user_config_path
|
||||||
|
|
||||||
|
|
||||||
|
def find_idalib() -> Optional[Path]:
|
||||||
|
config_path = get_idalib_user_config_path()
|
||||||
|
if not config_path:
|
||||||
|
logger.error("IDA Pro user configuration does not exist, please make sure you've installed idalib properly.")
|
||||||
|
return None
|
||||||
|
|
||||||
|
config = json.loads(config_path.read_text(encoding="utf-8"))
|
||||||
|
|
||||||
|
try:
|
||||||
|
ida_install_dir = Path(config["Paths"]["ida-install-dir"])
|
||||||
|
except KeyError:
|
||||||
|
logger.error(
|
||||||
|
"IDA Pro user configuration does not contain location of IDA Pro installation, please make sure you've installed idalib properly."
|
||||||
|
)
|
||||||
|
return None
|
||||||
|
|
||||||
|
if not ida_install_dir.exists():
|
||||||
|
return None
|
||||||
|
|
||||||
|
libname = {
|
||||||
|
"win32": "idalib.dll",
|
||||||
|
"linux": "libidalib.so",
|
||||||
|
"linux2": "libidalib.so",
|
||||||
|
"darwin": "libidalib.dylib",
|
||||||
|
}[sys.platform]
|
||||||
|
|
||||||
|
if not (ida_install_dir / "ida.hlp").is_file():
|
||||||
|
return None
|
||||||
|
|
||||||
|
if not (ida_install_dir / libname).is_file():
|
||||||
|
return None
|
||||||
|
|
||||||
|
idalib_path = ida_install_dir / "idalib" / "python"
|
||||||
|
if not idalib_path.exists():
|
||||||
|
return None
|
||||||
|
|
||||||
|
if not (idalib_path / "idapro" / "__init__.py").is_file():
|
||||||
|
return None
|
||||||
|
|
||||||
|
return idalib_path
|
||||||
|
|
||||||
|
|
||||||
|
def has_idalib() -> bool:
|
||||||
|
if is_idalib_installed():
|
||||||
|
logger.debug("found installed IDA idalib API")
|
||||||
|
return True
|
||||||
|
|
||||||
|
logger.debug("IDA idalib API not installed, searching...")
|
||||||
|
|
||||||
|
idalib_path = find_idalib()
|
||||||
|
if not idalib_path:
|
||||||
|
logger.debug("failed to find IDA idalib installation")
|
||||||
|
|
||||||
|
logger.debug("found IDA idalib API: %s", idalib_path)
|
||||||
|
return idalib_path is not None
|
||||||
|
|
||||||
|
|
||||||
|
def load_idalib() -> bool:
|
||||||
|
try:
|
||||||
|
import idapro
|
||||||
|
|
||||||
|
return True
|
||||||
|
except ImportError:
|
||||||
|
idalib_path = find_idalib()
|
||||||
|
if not idalib_path:
|
||||||
|
return False
|
||||||
|
|
||||||
|
sys.path.append(idalib_path.absolute().as_posix())
|
||||||
|
try:
|
||||||
|
import idapro # noqa: F401 unused import
|
||||||
|
|
||||||
|
return True
|
||||||
|
except ImportError:
|
||||||
|
return False
|
||||||
@@ -1,13 +1,15 @@
|
|||||||
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
# Copyright (C) 2020 Mandiant, Inc. All Rights Reserved.
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
# you may not use this file except in compliance with the License.
|
# you may not use this file except in compliance with the License.
|
||||||
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
||||||
# Unless required by applicable law or agreed to in writing, software distributed under the License
|
# 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.
|
# 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.
|
# See the License for the specific language governing permissions and limitations under the License.
|
||||||
from typing import Any, Dict, Tuple, Iterator
|
import re
|
||||||
|
from typing import Any, Dict, Tuple, Iterator, Optional
|
||||||
|
|
||||||
import idc
|
import idc
|
||||||
|
import ida_ua
|
||||||
import idaapi
|
import idaapi
|
||||||
import idautils
|
import idautils
|
||||||
|
|
||||||
@@ -35,9 +37,9 @@ def get_externs(ctx: Dict[str, Any]) -> Dict[int, Any]:
|
|||||||
return ctx["externs_cache"]
|
return ctx["externs_cache"]
|
||||||
|
|
||||||
|
|
||||||
def check_for_api_call(insn: idaapi.insn_t, funcs: Dict[int, Any]) -> Iterator[Any]:
|
def check_for_api_call(insn: idaapi.insn_t, funcs: Dict[int, Any]) -> Optional[Tuple[str, str]]:
|
||||||
"""check instruction for API call"""
|
"""check instruction for API call"""
|
||||||
info = ()
|
info = None
|
||||||
ref = insn.ea
|
ref = insn.ea
|
||||||
|
|
||||||
# attempt to resolve API calls by following chained thunks to a reasonable depth
|
# attempt to resolve API calls by following chained thunks to a reasonable depth
|
||||||
@@ -52,7 +54,7 @@ def check_for_api_call(insn: idaapi.insn_t, funcs: Dict[int, Any]) -> Iterator[A
|
|||||||
except IndexError:
|
except IndexError:
|
||||||
break
|
break
|
||||||
|
|
||||||
info = funcs.get(ref, ())
|
info = funcs.get(ref)
|
||||||
if info:
|
if info:
|
||||||
break
|
break
|
||||||
|
|
||||||
@@ -60,8 +62,7 @@ def check_for_api_call(insn: idaapi.insn_t, funcs: Dict[int, Any]) -> Iterator[A
|
|||||||
if not f or not (f.flags & idaapi.FUNC_THUNK):
|
if not f or not (f.flags & idaapi.FUNC_THUNK):
|
||||||
break
|
break
|
||||||
|
|
||||||
if info:
|
return info
|
||||||
yield info
|
|
||||||
|
|
||||||
|
|
||||||
def extract_insn_api_features(fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle) -> Iterator[Tuple[Feature, Address]]:
|
def extract_insn_api_features(fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle) -> Iterator[Tuple[Feature, Address]]:
|
||||||
@@ -76,16 +77,39 @@ def extract_insn_api_features(fh: FunctionHandle, bbh: BBHandle, ih: InsnHandle)
|
|||||||
if insn.get_canon_mnem() not in ("call", "jmp"):
|
if insn.get_canon_mnem() not in ("call", "jmp"):
|
||||||
return
|
return
|
||||||
|
|
||||||
# check calls to imported functions
|
# check call to imported functions
|
||||||
for api in check_for_api_call(insn, get_imports(fh.ctx)):
|
api = check_for_api_call(insn, get_imports(fh.ctx))
|
||||||
|
if api:
|
||||||
# tuple (<module>, <function>, <ordinal>)
|
# tuple (<module>, <function>, <ordinal>)
|
||||||
for name in capa.features.extractors.helpers.generate_symbols(api[0], api[1]):
|
for name in capa.features.extractors.helpers.generate_symbols(api[0], api[1]):
|
||||||
yield API(name), ih.address
|
yield API(name), ih.address
|
||||||
|
# a call instruction should only call one function, stop if a call to an import is extracted
|
||||||
|
return
|
||||||
|
|
||||||
# check calls to extern functions
|
# check call to extern functions
|
||||||
for api in check_for_api_call(insn, get_externs(fh.ctx)):
|
api = check_for_api_call(insn, get_externs(fh.ctx))
|
||||||
|
if api:
|
||||||
# tuple (<module>, <function>, <ordinal>)
|
# tuple (<module>, <function>, <ordinal>)
|
||||||
yield API(api[1]), ih.address
|
yield API(api[1]), ih.address
|
||||||
|
# a call instruction should only call one function, stop if a call to an extern is extracted
|
||||||
|
return
|
||||||
|
|
||||||
|
# extract dynamically resolved APIs stored in renamed globals (renamed for example using `renimp.idc`)
|
||||||
|
# examples: `CreateProcessA`, `HttpSendRequestA`
|
||||||
|
if insn.Op1.type == ida_ua.o_mem:
|
||||||
|
op_addr = insn.Op1.addr
|
||||||
|
op_name = idaapi.get_name(op_addr)
|
||||||
|
# when renaming a global using an API name, IDA assigns it the function type
|
||||||
|
# ensure we do not extract something wrong by checking that the address has a name and a type
|
||||||
|
# we could check that the type is a function definition, but that complicates the code
|
||||||
|
if (not op_name.startswith("off_")) and idc.get_type(op_addr):
|
||||||
|
# Remove suffix used in repeated names, for example _0 in VirtualFree_0
|
||||||
|
match = re.match(r"(.+)_\d+", op_name)
|
||||||
|
if match:
|
||||||
|
op_name = match.group(1)
|
||||||
|
# the global name does not include the DLL name, so we can't extract it
|
||||||
|
for name in capa.features.extractors.helpers.generate_symbols("", op_name):
|
||||||
|
yield API(name), ih.address
|
||||||
|
|
||||||
# extract IDA/FLIRT recognized API functions
|
# extract IDA/FLIRT recognized API functions
|
||||||
targets = tuple(idautils.CodeRefsFrom(insn.ea, False))
|
targets = tuple(idautils.CodeRefsFrom(insn.ea, False))
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# Copyright (C) 2023 Mandiant, Inc. All Rights Reserved.
|
# Copyright (C) 2020 Mandiant, Inc. All Rights Reserved.
|
||||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
# you may not use this file except in compliance with the License.
|
# you may not use this file except in compliance with the License.
|
||||||
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
# You may obtain a copy of the License at: [package root]/LICENSE.txt
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user