├── .gitignore
├── .gitmodules
├── Features_for_Malware_Detection.pdf
├── LICENSE
├── Prelim_Results_Malware_Detection.pdf
├── README.md
├── combine_features.py
├── config-template.ini
├── extract_apk.sh
├── extract_apks_parallel.sh
├── find_top_features.py
├── get_dates.py
├── get_samples.py
├── match_features.py
├── parse_disassembled.py
├── parse_maline_output.py
├── parse_ssdeep.py
├── parse_xml.py
├── plot_data.py
├── possibly_helpful_papers.txt
├── requirements.txt
├── run_trials.sh
├── sklearn_forest.py
├── sklearn_svm.py
├── sklearn_tree.py
├── sort_malicious.py
└── tensorflow_learn.py
/.gitignore:
--------------------------------------------------------------------------------
1 | config.ini
2 | all_apks/
3 | malicious_apk/
4 | benign_apk/
5 | invalid_andrototal_responses
6 | *.json
7 | *.csv
8 | *.png
9 | *.apk
10 | results_*
11 |
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "tools"]
2 | path = tools
3 | url = https://bitbucket.org/andrototal/tools/
4 | [submodule "paper"]
5 | path = paper
6 | url = https://git.overleaf.com/5092766fjzhxz
7 |
--------------------------------------------------------------------------------
/Features_for_Malware_Detection.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mwleeds/android-malware-analysis/84ff131cfdf14c627aa48ae405d3fe09a266f2e1/Features_for_Malware_Detection.pdf
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Prelim_Results_Malware_Detection.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mwleeds/android-malware-analysis/84ff131cfdf14c627aa48ae405d3fe09a266f2e1/Prelim_Results_Malware_Detection.pdf
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Getting an API Key
2 | AndroTotal has simplified the process for getting an API Key. Login/Create an Account at http://andrototal.org/ and you will then be able to view your profile settings. There is an API Tab which contains your key.
3 |
4 | This repository contains a set of scripts to automate the process of
5 | gathering data from malware samples, training a machine learning model
6 | on that data, and plotting its classification accuracy.
7 |
8 | 0. Make a copy of config-template.ini called config.ini and edit it.
9 |
10 | 1. Ensure that the "tools" subdirectory has been initialized ("`$ git submodule update --init tools`")
11 |
12 | 2. Either use `get_samples.py` to download samples or copy them into "all_apks" from another source.
13 | If you're using `get_samples.py`, you can monitor it in another shell by running `watch "ls -l *.apk | wc -l"`
14 |
15 | 3. `sort_malicious.py` uses andrototal.org to sort them into "malicious_apk" and "benign_apk" folders.
16 | You can monitor it in another shell by running `watch "ls -l benign_apk/*.apk | wc -l && ls -l malicious_apk/*.apk | wc -l"`
17 |
18 | 4. `extract_apks_parallel.sh` unpacks the .apk files into folders and processes some of the data therein.
19 | You can monitor it in another shell by running `watch "wc -l benign_apk/valid_apks.txt; wc -l malicious_apk/valid_apks.txt"`
20 |
21 | 5. Run one of the following scripts to generate feature vectors:
22 | * `parse_xml.py` for permissions. "app_permission_vectors.json" is generated
23 | * `parse_maline_output.py` for syscalls. "app_syscall_vectors.json" is generated. You will have to run [maline](https://github.com/soarlab/maline) first for this to work.
24 | * `parse_disassembled.py` for API calls. "app_method_vectors.json" is generated
25 | * `parse_ssdeep.py` for fuzzy hashes. "app_hash_vectors.json" is generated. You will have to run [ssdeep](http://ssdeep.sourceforge.net/) first for this to work.
26 | * `combine_features.py` for a combination of the top weighted features. "app_feature_vectors.json" is generated. This only works if you've previously trained a network on the specified features, and the feature weights files are named appropriately.
27 |
28 | 6. Run `$ run_trials.sh app_feature_vectors.json` (or whichever json you want) which runs the `tensorflow_learn.py` script (where the ML happens) a number of times and puts the results into a folder. It also runs `plot_data.py` and `match_features.py` to create a plot and create a list of top weighted features, respectively.
29 |
30 | 7. Change the parameters or input data and repeat step 6. It should be non-destructive so you can compare the results of different runs.
31 |
32 | Note: If you want to use a SVM instead of a neural network, use `sklearn_svm.py` in place of `tensorflow_learn.py`. You can also use `sklearn_tree.py` to use a decision tree.
33 |
--------------------------------------------------------------------------------
/combine_features.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """
4 | This script reads JSON files for different features (permissions, system calls, etc.)
5 | with data on a set of apps, and reads the features' weights from a trained model, and
6 | makes a dataset with the most heavily weighted features of each type.
7 |
8 | The output data format is as follows:
9 | {"features": ["ANDROID.PERMISSION.READ_PHONE_STATE", "java/security/Signature",...],
10 | "apps": {"999eca2457729e371355aea5faa38e14.apk": {"vector": [0,0,0,1], "malicious": [0,1]}, ...}}
11 | """
12 |
13 | from configparser import ConfigParser
14 | import json
15 |
16 | __author__='mwleeds'
17 |
18 | def main():
19 | config = ConfigParser()
20 | config.read('config.ini')
21 | FEATURES = config.get('AMA', 'FEATURES').split(',')
22 | TOP_N_FEATURES = config.getint('AMA', 'TOP_N_FEATURES')
23 | INCLUDE_DATES = config.getboolean('AMA', 'INCLUDE_DATES')
24 |
25 | all_features = [] # list of strings naming each feature used in the combined dataset
26 | app_feature_map = {} # mapping from android app names to lists of features
27 | app_malicious_map = {} # mapping from android app names to 1 or 0 for malware or goodware
28 | for feature in FEATURES:
29 | with open(feature + '_weights.json') as weights:
30 | feature_weights = json.load(weights)
31 | print('Found ' + str(len(feature_weights)) + ' sets of weights for ' + feature)
32 | # no need to look at benign weights; they're complementary
33 | malicious_weights = [weight[0] for weight in feature_weights]
34 | malicious_indices = sorted(range(len(malicious_weights)), key=lambda k: malicious_weights[k], reverse=True)
35 | with open('app_' + feature + '_vectors.json') as vectors:
36 | feature_data = json.load(vectors)
37 | feature_names = feature_data['features']
38 | print('Selecting ' + str(TOP_N_FEATURES) + ' top features of ' + str(len(feature_names)))
39 | for i in range(min(int(len(malicious_indices) / 2), int(TOP_N_FEATURES / 2))):
40 | index = malicious_indices[i]
41 | all_features.append(feature_names[index])
42 | for i in range(min(int(len(malicious_indices) / 2), int(TOP_N_FEATURES / 2))):
43 | index = malicious_indices[-i]
44 | all_features.append(feature_names[index])
45 | # The date feature has equal numbers of apps in each range to avoid it
46 | # being used as a feature directly, so only use those apps
47 | if INCLUDE_DATES:
48 | with open('app_date_vectors.json') as vectors:
49 | feature_data = json.load(vectors)
50 | date_buckets = feature_data['features']
51 | all_features += date_buckets
52 | date_apps = feature_data['apps']
53 | for app in date_apps:
54 | if app not in app_malicious_map:
55 | app_malicious_map[app] = date_apps[app]['malicious']
56 | if app not in app_feature_map:
57 | app_feature_map[app] = []
58 | for bucket in date_buckets:
59 | index = date_buckets.index(bucket)
60 | if date_apps[app]['vector'][index] == 1:
61 | app_feature_map[app].append(bucket)
62 | for feature in FEATURES:
63 | with open('app_' + feature + '_vectors.json') as vectors:
64 | feature_data = json.load(vectors)
65 | feature_names = feature_data['features']
66 | feature_apps = feature_data['apps']
67 | print('Found ' + str(len(feature_apps)) + ' apps for ' + feature)
68 | for app in feature_apps:
69 | if INCLUDE_DATES and app not in date_apps:
70 | continue
71 | if app not in app_malicious_map:
72 | app_malicious_map[app] = feature_apps[app]['malicious']
73 | if app not in app_feature_map:
74 | app_feature_map[app] = []
75 | for feature_name in all_features:
76 | if feature_name in feature_names:
77 | index = feature_names.index(feature_name)
78 | if feature_apps[app]['vector'][index] == 1:
79 | app_feature_map[app].append(feature_name)
80 | all_apps = {} # mapping combining app_feature_map and app_malicious_map using bits
81 | for app_name in app_feature_map:
82 | bit_vector = [1 if p in app_feature_map[app_name] else 0 for p in all_features]
83 | all_apps[app_name] = {'vector': bit_vector, 'malicious': app_malicious_map[app_name]}
84 | with open('app_feature_vectors.json', 'w') as outfile:
85 | json.dump({'features': all_features, 'apps': all_apps}, outfile)
86 | print('Wrote data on ' + str(len(all_features)) + ' features and ' + str(len(all_apps)) + ' apps to a file.')
87 |
88 | if __name__=='__main__':
89 | main()
90 |
--------------------------------------------------------------------------------
/config-template.ini:
--------------------------------------------------------------------------------
1 | [AMA]
2 | API_KEY = your_api_key
3 | START_DATE = 20160401:0000
4 | END_DATE = 20161001:0000
5 | LEARNING_RATE = 0.01
6 | NUM_CHUNKS = 20
7 | FEATURES = permission,syscall,method
8 | TOP_N_FEATURES = 30
9 | SHUFFLE_CHUNKS = True
10 | DECAY_RATE = 0.975
11 | NUM_DATE_BUCKETS = 20
12 | INCLUDE_DATES = False
13 |
--------------------------------------------------------------------------------
/extract_apk.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | #
4 | # This script is called by extract_apks_paprellel.sh with an apk filename,
5 | # and does several things:
6 | # 1. The apk is extracted into a folder
7 | # 2. The AndroidManifest.xml files are converted from binary to ASCII
8 | # 3. The classes.dex file is converted to classes-dex2jar.jar
9 | # 4. The classes in the jar file are printed to classes.list
10 | # 5. The jar file is disassembled to disassembled.code
11 | #
12 | # Dependencies: unzip, java, javap, xmllint, dex2jar
13 | #
14 |
15 | if [ -z "$1" ]; then
16 | echo "Usage: extract_apk.sh /path/to/apk"
17 | exit 1
18 | fi
19 |
20 | apk="$1"
21 | folder="${apk::-4}"
22 | mkdir -p "$folder"
23 | echo "Extracting $apk"
24 | unzip -u -d "$folder" "$apk" 1>/dev/null
25 | if [ $(ls -l "$folder" | wc -l) -gt 1 ]; then
26 | echo `basename $apk` >> valid_apks.txt
27 | cd "$folder"
28 | if [ -e "AndroidManifest.xml" ] && [ ! -e "AndroidManifest_ascii.xml" ]; then
29 | echo "Converting $folder/AndroidManifest.xml to ASCII"
30 | cp AndroidManifest.xml AndroidManifest_bin.xml
31 | java -jar ~/AXMLPrinter2.jar AndroidManifest_bin.xml > AndroidManifest_ascii.xml
32 | echo "Cleaning up $folder/AndroidManifest.xml"
33 | xmllint AndroidManifest_ascii.xml > AndroidManifest.xml
34 | if [ $? -ne 0 ]; then
35 | echo `basename $apk` >> ../malformed_xml.txt
36 | fi
37 | fi
38 | if [ -e "classes.dex" ] && [ ! -e "classes.list" ]; then
39 | echo "Converting $folder/classes.dex to jar format"
40 | d2j-dex2jar.sh classes.dex
41 | if [ $? -ne 0 ]; then
42 | echo `basename $apk` >> ../malformed_dex.txt
43 | else
44 | jar -tf classes-dex2jar.jar > classes.list
45 | javap -c -classpath classes-dex2jar.jar $(jar -tf classes-dex2jar.jar | grep "class$" | sed s/\.class$//) > disassembled.code
46 | fi
47 | fi
48 | cd ..
49 | fi
50 |
--------------------------------------------------------------------------------
/extract_apks_parallel.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | #
4 | # This script calls the extract_apk.sh script many times in parallel
5 | # for each of the sorted applications to unpack apk files and parse
6 | # their contents.
7 | #
8 |
9 | original_dir=$(pwd)
10 | for dir in malicious_apk benign_apk; do
11 | echo "Entering $dir"
12 | cd $dir
13 | cpus=$(ls -d /sys/devices/system/cpu/cpu[[:digit:]]* | wc -w)
14 | cpus=$(expr $cpus - 2)
15 | find `pwd` -type f -name "*.apk" | xargs --max-args=1 --max-procs=$cpus ../extract_apk.sh
16 | cat valid_apks.txt | sort | uniq > valid_apks.txt
17 | cat malformed_xml.txt | sort | uniq > malformed_xml.txt
18 | cat malformed_dex.txt | sort | uniq > malformed_dex.txt
19 | cd $original_dir
20 | done
21 |
--------------------------------------------------------------------------------
/find_top_features.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """
4 | This script prints each feature in the given JSON file along with
5 | how many apps use it, and how many of each type (malicious or benign).
6 | """
7 |
8 | import sys
9 | import json
10 |
11 | def main():
12 | with open(sys.argv[1]) as f:
13 | j = json.load(f)
14 | all_features = j['features']
15 | num_apps_each = {}
16 | for app in j['apps']:
17 | for i,bit in enumerate(j['apps'][app]['vector']):
18 | if bit == 1:
19 | if j['apps'][app]['malicious'] == [1,0]:
20 | if all_features[i] in num_apps_each:
21 | num_apps_each[all_features[i]][0] += 1
22 | else:
23 | num_apps_each[all_features[i]] = [1,0]
24 | else:
25 | if all_features[i] in num_apps_each:
26 | num_apps_each[all_features[i]][1] += 1
27 | else:
28 | num_apps_each[all_features[i]] = [0,1]
29 | # This sorts by number of malicious apps using it, but can easily be changed
30 | for feature in sorted(num_apps_each.items(), key=lambda item: item[1][0], reverse=True):
31 | print('{} was used by {} apps ({} malicious and {} benign)'.format(feature[0], str(feature[1][0] + feature[1][1]), str(feature[1][0]), str(feature[1][1])))
32 |
33 | if __name__=='__main__':
34 | if len(sys.argv) == 1:
35 | print('Usage: python3 {} '.format(sys.argv[0]))
36 | sys.exit(1)
37 | main()
38 |
--------------------------------------------------------------------------------
/get_dates.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """
4 | This script reads the resources.arsc files in the malicous_apk
5 | and benign_apk folders and copies the modified file dates into a
6 | JSON file for later analysis
7 |
8 | The output data format is as follows:
9 | {"features": ["1222000000_to_1222111111", ...],
10 | "apps": {"999eca2457729e371355aea5faa38e14.apk": {"vector": [0,0,0,1], "malicious": [0,1]}, ...}}
11 | """
12 |
13 | import os
14 | import json
15 | import glob
16 | import time
17 | import random
18 | from configparser import ConfigParser
19 |
20 | __author__='mkkeffeler'
21 |
22 | def main():
23 | config = ConfigParser()
24 | config.read('config.ini')
25 | NUM_DATE_BUCKETS = config.getint('AMA', 'NUM_DATE_BUCKETS')
26 |
27 | date_buckets = [] # list of strings naming each date range used in the dataset
28 | app_date_map = {} # mapping from android app names to lists of dates
29 | app_malicious_map = {} # mapping from android app names to 1 or 0 for malware or goodware
30 | apps_per_bucket = {} # number of apps in each date range
31 | relevant_buckets = [] # subset of buckets that will be used (based on NUM_DATE_BUCKETS)
32 | all_apps = {} # mapping combining app_date_map and app_malicious_map using bits
33 | apps_found_per_bucket = {} # number of apps added to all_apps for each bucket
34 | root_dir = os.getcwd()
35 |
36 | num_apps_before = 0
37 | num_apps_after = 0
38 | num_file_not_found = 0
39 | fnfe = open('file_not_found_error', 'w')
40 | for i, directory in enumerate(['benign_apk', 'malicious_apk']):
41 | os.chdir(directory)
42 | for filename in glob.glob('*.apk'):
43 | #print('Processing ' + filename)
44 | try:
45 | os.chdir(filename[:-4])
46 | if os.path.exists('classes.dex'):
47 | mtime = os.stat('classes.dex')
48 | else:
49 | mtime = os.stat('resources.arsc')
50 | if mtime.st_mtime < 1222000000:
51 | num_apps_before += 1
52 | if mtime.st_mtime > time.time():
53 | num_apps_after += 1
54 | except FileNotFoundError:
55 | num_file_not_found += 1
56 | fnfe.write(filename + '\n')
57 | os.chdir(os.path.join(root_dir, directory))
58 | continue
59 | app_date_map[filename] = int(mtime.st_mtime)
60 | app_name = filename
61 | # make a one-hot bit vector of length 2. 1st bit set if malicious, otherwise 2nd bit
62 | app_malicious_map[app_name] = [1,0] if i else [0,1]
63 | os.chdir(os.pardir)
64 | os.chdir(root_dir)
65 | fnfe.close()
66 |
67 | # Android was released Sept. 23, 2008
68 | startdate = 1222000000
69 | secondsinmonth = 60 * 60 * 24 * 28
70 | enddate = startdate + secondsinmonth
71 | while True:
72 | date_buckets.append(str(startdate)+"_to_"+str(enddate))
73 | # Apps can't have been made in the future
74 | if(enddate >= time.time()):
75 | break
76 | startdate = enddate
77 | enddate = startdate + secondsinmonth
78 |
79 | # Count the number of apps per date range so we can ensure there's an equal number in each
80 | for app_name in app_date_map:
81 | for bucket in date_buckets:
82 | mtime = app_date_map[app_name]
83 | startdate = int(bucket.split("_to_")[0])
84 | enddate = int(bucket.split("_to_")[1])
85 | if (startdate <= mtime) and (mtime < enddate):
86 | if bucket not in apps_per_bucket:
87 | apps_per_bucket[bucket] = app_malicious_map[app_name]
88 | else:
89 | if app_malicious_map[app_name][0] == 1:
90 | apps_per_bucket[bucket][0] += 1
91 | else:
92 | apps_per_bucket[bucket][1] += 1
93 | break
94 | with open('apps_per_bucket.json', 'w') as f:
95 | json.dump(apps_per_bucket, f)
96 | relevant_buckets = sorted(apps_per_bucket, key=lambda bucket: min(apps_per_bucket[bucket]), reverse=True)
97 | if len(relevant_buckets) > NUM_DATE_BUCKETS:
98 | relevant_buckets = relevant_buckets[:NUM_DATE_BUCKETS]
99 | apps_per_bucket_limit = min(apps_per_bucket[relevant_buckets[-1]]) # number of apps of each type (benign/malicious) of each bucket
100 |
101 | # Now add apps_per_bucket_limit apps from each bucket to all_apps
102 | for bucket in relevant_buckets:
103 | apps_found_per_bucket[bucket] = [0,0]
104 | for app_name in app_date_map:
105 | date_vector = []
106 | in_relevant_bucket = False
107 | this_bucket = ''
108 | for bucket in relevant_buckets:
109 | mtime = app_date_map[app_name]
110 | startdate = int(bucket.split("_to_")[0])
111 | enddate = int(bucket.split("_to_")[1])
112 | if (startdate <= mtime) and (mtime < enddate):
113 | date_vector.append(1)
114 | in_relevant_bucket = True
115 | this_bucket = bucket
116 | else:
117 | date_vector.append(0)
118 | malicious = (app_malicious_map[app_name] == [1,0])
119 | if in_relevant_bucket and apps_found_per_bucket[this_bucket][0 if malicious else 1] < apps_per_bucket_limit:
120 | apps_found_per_bucket[this_bucket][0 if malicious else 1] += 1
121 | all_apps[app_name] = {'vector': date_vector, 'malicious': app_malicious_map[app_name]}
122 | with open('app_date_vectors.json', 'w') as outfile:
123 | json.dump({'features': relevant_buckets, 'apps': all_apps}, outfile)
124 | print('Wrote data on ' + str(len(relevant_buckets)) + ' date buckets and ' + str(len(all_apps)) + ' apps to a file.')
125 | print('{} apps were before Android began and {} were after today'.format(num_apps_before, num_apps_after))
126 | print('{} classes.dex files were not found'.format(num_file_not_found))
127 |
128 | if __name__=='__main__':
129 | main()
130 |
--------------------------------------------------------------------------------
/get_samples.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | # This script downloads Android malware (and goodware) from andrototal.org
4 |
5 | import subprocess
6 | import os
7 | import glob
8 | from configparser import ConfigParser
9 |
10 | def main():
11 | config = ConfigParser()
12 | config.read('config.ini')
13 | API_KEY = config.get('AMA', 'API_KEY')
14 | START_DATE = config.get('AMA', 'START_DATE')
15 | END_DATE = config.get('AMA', 'END_DATE')
16 | subprocess.check_call('./tools/samples_cli.py getbydate -at-key {} {} {}'.format(API_KEY, START_DATE, END_DATE), shell=True)
17 | for apk in glob.glob('*.apk'):
18 | os.rename(apk, 'all_apks/' + apk)
19 |
20 | if __name__=='__main__':
21 | main()
22 |
--------------------------------------------------------------------------------
/match_features.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """
4 | This script reads the JSON file passed as the first command line argument to
5 | get the names of features and feature_weights.json (written by tensorflow_learn.py)
6 | to get the feature weights from a trained ML model. It then matches the feature
7 | weights to the human-readable names for them, and prints them out, sorted by the weights.
8 | So the first feature listed is the one most indicative of maliciousness, and the first
9 | one in the second list is the one most indicative of benign (the lists are just mirror
10 | images of each other).
11 | """
12 |
13 | import json
14 | import sys
15 |
16 | def main():
17 | with open(sys.argv[1]) as vectors:
18 | # Dataset of feature names that were used in the model
19 | feature_names = json.load(vectors)['features']
20 |
21 | with open('feature_weights.json') as weights:
22 | # Tensorflow model calculated weights for every feature
23 | feature_weights = json.load(weights)
24 |
25 | # Separate malicous and benign weights
26 | malicious_weights = [weight[0] for weight in feature_weights]
27 | benign_weights = [weight[1] for weight in feature_weights]
28 |
29 | # Sort weights in descending order
30 | malicious_indices=sorted(range(len(malicious_weights)), key=lambda k: malicious_weights[k], reverse=True)
31 | benign_indices=sorted(range(len(benign_weights)), key=lambda k: benign_weights[k], reverse=True)
32 |
33 | # Prints the rank of each feature, its weight, and the feature name
34 | print('MALICIOUS FEATURE RANKINGS:\n')
35 | for i,x in enumerate(malicious_indices):
36 | print ('{}. {} {}'.format(i, feature_names[x], malicious_weights[x]))
37 |
38 | print ('\n\n\n\n\nBENIGN FEATURE RANKINGS:\n')
39 | for i,x in enumerate(benign_indices):
40 | print ('{}. {} {}'.format(i, feature_names[x], benign_weights[x]))
41 |
42 | if __name__=='__main__':
43 | main()
44 |
--------------------------------------------------------------------------------
/parse_disassembled.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """
4 | This script reads the disassembled.code files in the malicous_apk
5 | and benign_apk folders and copies the Android and Java methods called
6 | into a JSON file for later analysis.
7 |
8 | The output data format is as follows:
9 | {"features": ["java/lang/String.length", ...],
10 | "apps": {"999eca2457729e371355aea5faa38e14.apk": {"vector": [0,0,0,1], "malicious": [0,1]}, ...}}
11 | """
12 |
13 | import os
14 | import json
15 | import glob
16 |
17 | __author__='mwleeds'
18 |
19 | def main():
20 | all_methods = [] # list of strings naming each method used in the dataset
21 | app_method_map = {} # mapping from android app names to lists of methods
22 | app_malicious_map = {} # mapping from android app names to 1 or 0 for malware or goodware
23 | root_dir = os.getcwd()
24 | for i, directory in enumerate(['benign_apk', 'malicious_apk']):
25 | os.chdir(directory)
26 | category_root_dir = os.getcwd()
27 | for filename in glob.glob('*.apk'):
28 | try:
29 | print('Processing ' + filename)
30 | os.chdir(filename[:-4])
31 | with open('disassembled.code') as disassembled_code:
32 | app_name = filename
33 | # make a one-hot bit vector of length 2. 1st bit set if malicious, otherwise 2nd bit
34 | app_malicious_map[app_name] = [1,0] if i else [0,1]
35 | # parse the file and record any interesting methods
36 | app_method_map[app_name] = []
37 | for line in disassembled_code.readlines():
38 | try:
39 | method = line.split('// Method ')[1].split(':')[0]
40 | #if not method.startswith('java') and not method.startswith('android'):
41 | if not method.startswith('java'):
42 | continue
43 | # Comment the below line to use methods rather than classes
44 | method = method.split('.')[0]
45 | # the method is probably obfuscated; ignore it
46 | if len(method.split('/')[-1]) < 4 or len(method.split('/')[-2]) == 1:
47 | continue
48 | if method not in all_methods:
49 | all_methods.append(method)
50 | if method not in app_method_map[app_name]:
51 | app_method_map[app_name].append(method)
52 | except IndexError:
53 | continue
54 | except FileNotFoundError as e:
55 | print(e)
56 | finally:
57 | os.chdir(category_root_dir)
58 | os.chdir(root_dir)
59 | all_apps = {} # mapping combining app_methods_map and app_malicious_map using bits
60 | for app_name in app_method_map:
61 | bit_vector = [1 if m in app_method_map[app_name] else 0 for m in all_methods]
62 | all_apps[app_name] = {'vector': bit_vector, 'malicious': app_malicious_map[app_name]}
63 | with open('app_method_vectors.json', 'w') as outfile:
64 | json.dump({'features': all_methods, 'apps': all_apps}, outfile)
65 | print('Wrote data on ' + str(len(all_methods)) + ' methods and ' + str(len(all_apps)) + ' apps to a file.')
66 |
67 | if __name__=='__main__':
68 | main()
69 |
--------------------------------------------------------------------------------
/parse_maline_output.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """
4 | This script reads the .freq files written by maline, converts them into bit
5 | vectors denoting which system calls were used and copies that information
6 | into a JSON file for later analysis.
7 |
8 | The output data format is as follows:
9 | {"features": ["android.permission.RECEIVE_BOOT_COMPLETED", ...],
10 | "apps": {"": {"vector": [0,0,0,1], "malicious": [0,1]}, ...}}
11 | """
12 |
13 | import glob
14 | import os
15 | import json
16 | from configparser import ConfigParser
17 |
18 | __author__='mwleeds'
19 |
20 | def main():
21 | config = ConfigParser()
22 | config.read('config.ini')
23 | MALINE_DIR = config.get('AMA', 'MALINE_DIR')
24 | MALINE_DIR = os.path.expanduser(MALINE_DIR)
25 |
26 | all_apps = {} # mapping combining app_syscall_map and app_malicious_map using bits
27 | all_syscalls = [] # list of strings naming each syscall for the architecture
28 | root_dir = os.getcwd()
29 | freq_files = glob.glob('all_freq/*.freq')
30 | os.chdir(MALINE_DIR)
31 | with open('data/i386-syscall.txt') as f:
32 | all_syscalls = [line.strip() for line in f.readlines()]
33 | os.chdir(root_dir)
34 | for filename in freq_files:
35 | print('Processing ' + filename)
36 | apk_name = filename.split('-')[1]
37 | malicious = os.path.isfile(os.getcwd() + '/malicious_apk/' + apk_name + '.apk')
38 | with open(filename) as f:
39 | frequencies = [freq for freq in f.readlines()[1].split(' ') if len(freq) > 0]
40 | assert(len(frequencies) == len(all_syscalls))
41 | frequency_bits = [1 if int(f) > 0 else 0 for f in frequencies]
42 | all_apps[apk_name + '.apk'] = {'vector': frequency_bits, 'malicious': [1,0] if malicious else [0,1]}
43 | with open('app_syscall_vectors.json', 'w') as outfile:
44 | json.dump({'features': all_syscalls, 'apps': all_apps}, outfile)
45 | print('Wrote data on ' + str(len(all_syscalls)) + ' syscalls and ' + str(len(all_apps)) + ' apps to a file.')
46 |
47 | if __name__=='__main__':
48 | main()
49 |
--------------------------------------------------------------------------------
/parse_ssdeep.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """
4 | This script reads the CSV output from ssdeep in the malicious_apk
5 | and benign_apk folders and writes similarity scores for each sample
6 | and classifications to a JSON file for later analysis
7 |
8 | The output data format is as follows:
9 | {"features": ["similarity_limit_0", "similarity_limit_0.2", ...],
10 | "apps": {"999eca2457729e371355aea5faa38e14.apk": {"vector": [0,0,0,1], "malicious": [0,1]}, ...}}
11 | """
12 |
13 | import os
14 | import json
15 | import glob
16 | import random
17 | import numpy
18 | import ssdeep
19 |
20 | __author__='mwleeds'
21 |
22 | def main():
23 | all_hashes = {'malicious': [], 'benign': []}
24 | app_malicious_map = {} # mapping from android app names to 1 or 0 for malware or goodware
25 | similarity_buckets = ['similarity_limit_0', 'similarity_limit_0.2', 'similarity_limit_0.4', 'similarity_limit_0.6', 'similarity_limit_0.8', 'similarity_limit_1.0']
26 | root_dir = os.getcwd()
27 | for i, directory in enumerate(['benign_apk', 'malicious_apk']):
28 | os.chdir(directory)
29 | with open(directory.split('_')[0] + '_apk_ssdeep.csv') as hashes:
30 | for j, line in enumerate(hashes):
31 | if j == 0: continue
32 | b64hash = line.split(',')[0]
33 | app_name = line.split(',')[-1].split('/')[-1][:-2]
34 | app_malicious_map[app_name] = [1,0] if i else [0,1]
35 | all_hashes['malicious' if i else 'benign'].append((app_name, b64hash))
36 | os.chdir(root_dir)
37 | all_apps = {} # mapping from each app to its similarity score and classification
38 | num_zero = {}
39 | num_each = {}
40 | for category in all_hashes:
41 | num_zero[category] = 0
42 | num_each[category] = 0
43 | for app_and_hash in all_hashes[category]:
44 | similarity_scores = []
45 | this_score = app_and_hash[1]
46 | for i in range(1000):
47 | other_score = random.choice(all_hashes[category])[1]
48 | similarity_scores.append(ssdeep.compare(this_score, other_score))
49 | score = numpy.mean(similarity_scores)
50 | num_each[category] += 1
51 | if score == 0: num_zero[category] += 1
52 | bit_vector = []
53 | last_limit = -0.01
54 | for limit in similarity_buckets:
55 | float_limit = float(limit.split('_')[-1])
56 | if score <= float_limit and score > last_limit:
57 | bit_vector.append(1)
58 | else:
59 | bit_vector.append(0)
60 | last_limit = float_limit
61 | if not any(bit_vector): # score > 1
62 | bit_vector[-1] = 1
63 | all_apps[app_and_hash[0]] = {'vector': bit_vector, 'malicious': app_malicious_map[app_and_hash[0]]}
64 | with open('app_hash_vectors.json', 'w') as outfile:
65 | json.dump({'features': similarity_buckets, 'apps': all_apps}, outfile)
66 | print('{} of {} malicious apps and {} of {} benign apps had zero similarity found'.format(num_zero['malicious'], num_each['malicious'], num_zero['benign'], num_zero['benign']))
67 | print('Wrote data on ' + str(len(all_apps)) + ' apps to a file.')
68 |
69 | if __name__=='__main__':
70 | main()
71 |
--------------------------------------------------------------------------------
/parse_xml.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """
4 | This script reads the AndroidManifest.xml files in the malicous_apk
5 | and benign_apk folders and copies the requested permissions into a
6 | JSON file for later analysis
7 |
8 | The output data format is as follows:
9 | {"features": ["ANDROID.PERMISSION.RECEIVE_BOOT_COMPLETED", ...],
10 | "apps": {"999eca2457729e371355aea5faa38e14.apk": {"vector": [0,0,0,1], "malicious": [0,1]}, ...}}
11 | """
12 |
13 | import os
14 | from defusedxml import ElementTree
15 | import json
16 | import glob
17 |
18 | __author__='mwleeds'
19 |
20 | def main():
21 | all_permissions = [] # list of strings naming each permission used in the dataset
22 | app_permission_map = {} # mapping from android app names to lists of permissions
23 | app_malicious_map = {} # mapping from android app names to 1 or 0 for malware or goodware
24 | root_dir = os.getcwd()
25 | for i, directory in enumerate(['benign_apk', 'malicious_apk']):
26 | os.chdir(directory)
27 | category_root_dir = os.getcwd()
28 | for filename in glob.glob('*.apk'):
29 | print('Processing ' + filename)
30 | try:
31 | os.chdir(filename[:-4])
32 | with open('AndroidManifest.xml') as xml_file:
33 | et = ElementTree.parse(xml_file)
34 | except (ElementTree.ParseError, UnicodeDecodeError, FileNotFoundError):
35 | print('Parsing error encountered for ' + filename)
36 | os.chdir(category_root_dir)
37 | continue
38 | app_name = filename
39 | # make a one-hot bit vector of length 2. 1st bit set if malicious, otherwise 2nd bit
40 | app_malicious_map[app_name] = [1,0] if i else [0,1]
41 | permissions = et.getroot().findall('./uses-permission')
42 | app_permission_map[app_name] = []
43 | for permission in permissions:
44 | try:
45 | permission_name = permission.attrib['{http://schemas.android.com/apk/res/android}name'].upper()
46 | if not permission_name.startswith('ANDROID.PERMISSION'): continue # ignore custom permissions
47 | if permission_name not in all_permissions: all_permissions.append(permission_name)
48 | app_permission_map[app_name].append(permission_name)
49 | except KeyError:
50 | pass
51 | os.chdir(os.pardir)
52 | os.chdir(root_dir)
53 | all_apps = {} # mapping combining app_permission_map and app_malicious_map using bits
54 | for app_name in app_permission_map:
55 | bit_vector = [1 if p in app_permission_map[app_name] else 0 for p in all_permissions]
56 | all_apps[app_name] = {'vector': bit_vector, 'malicious': app_malicious_map[app_name]}
57 | with open('app_permission_vectors.json', 'w') as outfile:
58 | json.dump({'features': all_permissions, 'apps': all_apps}, outfile)
59 | print('Wrote data on ' + str(len(all_permissions)) + ' permissions and ' + str(len(all_apps)) + ' apps to a file.')
60 |
61 | if __name__=='__main__':
62 | main()
63 |
--------------------------------------------------------------------------------
/plot_data.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | # This script plots the data produced by run_trials.sh
4 |
5 | import matplotlib.pyplot as plt
6 | from matplotlib.axes import Axes
7 | import numpy
8 |
9 | CSV_FILE = 'results.csv'
10 |
11 | def main():
12 | # read the data from the CSV files
13 | data = numpy.genfromtxt(CSV_FILE, delimiter=',', names=True)
14 |
15 | # plot training steps vs classification accuracy
16 | plt.plot(data['n'], data['false_positive'], 'r.', markersize=20)
17 | plt.plot(data['n'], data['false_negative'], 'g.', markersize=20)
18 | plt.plot(data['n'], data['accuracy'], 'b.', markersize=20)
19 | plt.title('Number of Training Steps vs Classification Accuracy \n and False Negative/Positive Rates')
20 | plt.xlabel('Number of Training Steps')
21 | plt.ylabel('Classification Accuracy')
22 | plt.grid(True)
23 | plt.savefig('training_steps_vs_accuracy.png')
24 |
25 | if __name__=='__main__':
26 | main()
27 |
--------------------------------------------------------------------------------
/possibly_helpful_papers.txt:
--------------------------------------------------------------------------------
1 | http://scholarworks.sjsu.edu/cgi/viewcontent.cgi?article=1488&context=etd_projects
2 | http://ieeexplore.ieee.org/xpls/icp.jsp?arnumber=5696292
3 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | matplotlib
2 | pydotplus
3 | sklearn
4 | numpy
5 | ssdeep
6 |
--------------------------------------------------------------------------------
/run_trials.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | set -e
4 |
5 | if [ ! -e "$1" ]; then
6 | echo "Usage: $0 "
7 | exit 1
8 | fi
9 |
10 | rm -f results.csv
11 | echo "n,false_positive,false_negative,accuracy" >> results.csv
12 | for n in 20 40 60 80 100 120 140 160 180 200; do
13 | m=10
14 | false_positive_sum=0
15 | false_negative_sum=0
16 | accuracy_sum=0
17 | for i in `seq 1 $m`; do
18 | output=`python3 tensorflow_learn.py $1 $n 2>/dev/null`
19 | output_arr=(${output//$'\n'/ })
20 | echo "n: $n false_positive: ${output_arr[0]} false_negative: ${output_arr[1]} accuracy: ${output_arr[2]}"
21 | false_positive_sum=$(echo "scale=2;$false_positive_sum + ${output_arr[0]}" | bc)
22 | false_negative_sum=$(echo "scale=2;$false_negative_sum + ${output_arr[1]}" | bc)
23 | accuracy_sum=$(echo "scale=2;$accuracy_sum + ${output_arr[2]}" | bc)
24 | NUMBER_MALICIOUS="${output_arr[3]}"
25 | NUMBER_BENIGN="${output_arr[4]}"
26 | done
27 | false_positive_avg=$(echo "scale=2;$false_positive_sum/$m" | bc)
28 | false_negative_avg=$(echo "scale=2;$false_negative_sum/$m" | bc)
29 | accuracy_avg=$(echo "scale=2;$accuracy_sum/$m" | bc)
30 | echo "$n,$false_positive_avg,$false_negative_avg,$accuracy_avg" >> results.csv
31 | done
32 |
33 | python3 plot_data.py
34 | python3 match_features.py $1 >> top_features.txt
35 |
36 | rm -f RUN_INFO
37 | grep "LEARNING_RATE" config.ini >> RUN_INFO
38 | grep "NUM_CHUNKS" config.ini >> RUN_INFO
39 | grep "SHUFFLE_CHUNKS" config.ini >> RUN_INFO
40 | grep "DECAY_RATE" config.ini >> RUN_INFO
41 | echo "NUMBER_MALICIOUS = $NUMBER_MALICIOUS" >> RUN_INFO
42 | echo "NUMBER_BENIGN = $NUMBER_BENIGN" >> RUN_INFO
43 |
44 | RUN_FOLDER="results_`date --iso-8601=seconds`"
45 | mkdir "$RUN_FOLDER"
46 | mv results.csv RUN_INFO feature_weights.json training_steps_vs_accuracy.png top_features.txt "$RUN_FOLDER"
47 | cp $1 "$RUN_FOLDER"
48 |
--------------------------------------------------------------------------------
/sklearn_forest.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import os
4 | import json
5 | import sys
6 | import sklearn
7 | from sklearn import cross_validation, grid_search, ensemble
8 | from sklearn.metrics import confusion_matrix, classification_report
9 | from sklearn.externals import joblib
10 |
11 | def train_forest_classifer(features, labels, model_output_path):
12 | """
13 | train_forest_classifer will train a RandomForestClassifier
14 |
15 | features: 2D array of each input feature for each sample
16 | labels: array of string labels classifying each sample
17 | model_output_path: path for storing the trained forest model
18 | """
19 | # save 20% of data for performance evaluation
20 | X_train, X_test, y_train, y_test = cross_validation.train_test_split(features, labels, test_size=0.2)
21 |
22 | param = [
23 | {
24 | "max_depth": [None, 10, 100, 1000, 10000],
25 | "n_estimators": [1, 10, 100]
26 | }
27 | ]
28 |
29 | forest = ensemble.RandomForestClassifier(random_state=0)
30 |
31 | # 10-fold cross validation, use 4 thread as each fold and each parameter set can be train in parallel
32 | clf = grid_search.GridSearchCV(forest, param,
33 | cv=10, n_jobs=20, verbose=3)
34 |
35 | clf.fit(X_train, y_train)
36 |
37 | if os.path.exists(model_output_path):
38 | joblib.dump(clf.best_estimator_, model_output_path)
39 | else:
40 | print("Cannot save trained forest model to {0}.".format(model_output_path))
41 |
42 | print("\nBest parameters set:")
43 | print(clf.best_params_)
44 |
45 | y_predict=clf.predict(X_test)
46 |
47 | labels=sorted(list(set(labels)))
48 | print("\nConfusion matrix:")
49 | print("Labels: {0}\n".format(",".join(labels)))
50 | print(confusion_matrix(y_test, y_predict, labels=labels))
51 |
52 | print("\nClassification report:")
53 | print(classification_report(y_test, y_predict))
54 |
55 | def main():
56 | # load the feature data from a file
57 | with open(sys.argv[1]) as infile:
58 | dataset = json.load(infile)
59 | app_names = list(dataset['apps'].keys())
60 | feature_vectors = [dataset['apps'][app]['vector'] for app in app_names]
61 | labels = ['1' if dataset['apps'][app]['malicious'] == [1,0] else '0' for app in app_names]
62 | train_forest_classifer(feature_vectors, labels, 'model.out')
63 |
64 | if __name__=='__main__':
65 | main()
66 |
--------------------------------------------------------------------------------
/sklearn_svm.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import os
4 | import json
5 | import sys
6 | import sklearn
7 | from sklearn import cross_validation, grid_search
8 | from sklearn.metrics import confusion_matrix, classification_report
9 | from sklearn.svm import SVC
10 | from sklearn.externals import joblib
11 |
12 | # Code credit to https://code.oursky.com/tensorflow-svm-image-classifications-engine/
13 |
14 | def train_svm_classifer(features, labels, model_output_path):
15 | """
16 | train_svm_classifer will train a SVM, saved the trained and SVM model and
17 | report the classification performance
18 |
19 | features: 2D array of each input feature for each sample
20 | labels: array of string labels classifying each sample
21 | model_output_path: path for storing the trained svm model
22 | """
23 | # save 20% of data for performance evaluation
24 | X_train, X_test, y_train, y_test = cross_validation.train_test_split(features, labels, test_size=0.2)
25 |
26 | param = [
27 | {
28 | "kernel": ["linear"],
29 | "C": [1, 10, 100, 1000]
30 | },
31 | {
32 | "kernel": ["rbf"],
33 | "C": [1, 10, 100, 1000],
34 | "gamma": [1e-2, 1e-3, 1e-4, 1e-5]
35 | }
36 | ]
37 |
38 | # request probability estimation
39 | svm = SVC(probability=True)
40 |
41 | # 10-fold cross validation, use 4 thread as each fold and each parameter set can be train in parallel
42 | clf = grid_search.GridSearchCV(svm, param,
43 | cv=10, n_jobs=20, verbose=3)
44 |
45 | clf.fit(X_train, y_train)
46 |
47 | if os.path.exists(model_output_path):
48 | joblib.dump(clf.best_estimator_, model_output_path)
49 | else:
50 | print("Cannot save trained svm model to {0}.".format(model_output_path))
51 |
52 | print("\nBest parameters set:")
53 | print(clf.best_params_)
54 |
55 | y_predict=clf.predict(X_test)
56 |
57 | labels=sorted(list(set(labels)))
58 | print("\nConfusion matrix:")
59 | print("Labels: {0}\n".format(",".join(labels)))
60 | print(confusion_matrix(y_test, y_predict, labels=labels))
61 |
62 | print("\nClassification report:")
63 | print(classification_report(y_test, y_predict))
64 |
65 | def main():
66 | # load the feature data from a file
67 | with open(sys.argv[1]) as infile:
68 | dataset = json.load(infile)
69 | app_names = list(dataset['apps'].keys())
70 | feature_vectors = [dataset['apps'][app]['vector'] for app in app_names]
71 | labels = ['1' if dataset['apps'][app]['malicious'] == [1,0] else '0' for app in app_names]
72 | train_svm_classifer(feature_vectors, labels, 'model.out')
73 |
74 | if __name__=='__main__':
75 | main()
76 |
--------------------------------------------------------------------------------
/sklearn_tree.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | import os
4 | import json
5 | import sys
6 | import sklearn
7 | import pydotplus
8 | from sklearn import cross_validation, grid_search, tree
9 | from sklearn.metrics import confusion_matrix, classification_report
10 | from sklearn.externals import joblib
11 |
12 | def train_tree_classifer(features, labels, model_output_path):
13 | """
14 | train_tree_classifer will train a DecisionTree and write it out to a pdf file
15 |
16 | features: 2D array of each input feature for each sample
17 | labels: array of string labels classifying each sample
18 | model_output_path: path for storing the trained tree model
19 | """
20 | # save 20% of data for performance evaluation
21 | X_train, X_test, y_train, y_test = cross_validation.train_test_split(features, labels, test_size=0.2)
22 |
23 | param = [
24 | {
25 | "max_depth": [None, 10, 100, 1000, 10000]
26 | }
27 | ]
28 |
29 | dtree = tree.DecisionTreeClassifier(random_state=0)
30 |
31 | # 10-fold cross validation, use 4 thread as each fold and each parameter set can be train in parallel
32 | clf = grid_search.GridSearchCV(dtree, param,
33 | cv=10, n_jobs=20, verbose=3)
34 |
35 | clf.fit(X_train, y_train)
36 |
37 | if os.path.exists(model_output_path):
38 | joblib.dump(clf.best_estimator_, model_output_path)
39 | else:
40 | print("Cannot save trained tree model to {0}.".format(model_output_path))
41 |
42 | dot_data = tree.export_graphviz(clf.best_estimator_, out_file=None)
43 | graph = pydotplus.graph_from_dot_data(dot_data)
44 | graph.write_pdf('best_tree.pdf')
45 |
46 | print("\nBest parameters set:")
47 | print(clf.best_params_)
48 |
49 | y_predict=clf.predict(X_test)
50 |
51 | labels=sorted(list(set(labels)))
52 | print("\nConfusion matrix:")
53 | print("Labels: {0}\n".format(",".join(labels)))
54 | print(confusion_matrix(y_test, y_predict, labels=labels))
55 |
56 | print("\nClassification report:")
57 | print(classification_report(y_test, y_predict))
58 |
59 | def main():
60 | # load the feature data from a file
61 | with open(sys.argv[1]) as infile:
62 | dataset = json.load(infile)
63 | app_names = list(dataset['apps'].keys())
64 | feature_vectors = [dataset['apps'][app]['vector'] for app in app_names]
65 | labels = ['1' if dataset['apps'][app]['malicious'] == [1,0] else '0' for app in app_names]
66 | train_tree_classifer(feature_vectors, labels, 'model.out')
67 |
68 | if __name__=='__main__':
69 | main()
70 |
--------------------------------------------------------------------------------
/sort_malicious.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | # This script looks at the .apk files in the 'all_apks' folder,
4 | # submits their hashes to andrototal.org to see if they're malicious,
5 | # and sorts them into folders based on that ('malicious_apk' and 'benign_apk')
6 | # (make sure those folders exist before running this)
7 |
8 | import subprocess
9 | import os
10 | import json
11 | import glob
12 | from configparser import ConfigParser
13 |
14 | def main():
15 | config = ConfigParser()
16 | config.read('config.ini')
17 | API_KEY = config.get('AMA', 'API_KEY')
18 | for apk in glob.glob('all_apks/*.apk'):
19 | if not os.path.isfile(apk[:-4] + '_andrototal.json'):
20 | print('Checking ' + apk)
21 | try:
22 | analysis = subprocess.check_output('./tools/andrototal_cli.py analysis -at-key {} {}'.format(API_KEY, apk.split('/')[1][:-4]), shell=True).decode('utf-8')
23 | except subprocess.CalledProcessError as e:
24 | print(str(e))
25 | continue
26 | with open(apk[:-4] + '_andrototal.json', 'w') as out_file:
27 | out_file.write(analysis)
28 | try:
29 | with open(apk[:-4] + '_andrototal.json') as json_file:
30 | analysis = json.load(json_file)
31 | if type(analysis) == str: raise ValueError
32 | except ValueError:
33 | with open('invalid_andrototal_responses', 'a') as out_file:
34 | out_file.write(apk.split('/')[1] + '\n')
35 | continue
36 | if all([test['result'] == 'NO_THREAT_FOUND' for test in analysis['tests']]):
37 | os.rename(apk, 'benign_apk/' + apk.split('/')[1])
38 | else:
39 | os.rename(apk, 'malicious_apk/' + apk.split('/')[1])
40 |
41 | if __name__=='__main__':
42 | main()
43 |
--------------------------------------------------------------------------------
/tensorflow_learn.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | """
4 | This script reads app_permission_vectors.json (written by parse_xml.py) and
5 | feeds the data into a tensorflow "neural network" to try to learn from it.
6 | """
7 |
8 | import tensorflow as tf
9 | import numpy as np
10 | import json
11 | import math
12 | import random
13 | import sys
14 | from configparser import ConfigParser
15 |
16 | __author__='mwleeds'
17 |
18 | def main():
19 | config = ConfigParser()
20 | config.read('config.ini')
21 | LEARNING_RATE = config.getfloat('AMA', 'LEARNING_RATE')
22 | NUM_CHUNKS = config.getint('AMA', 'NUM_CHUNKS')
23 | SHUFFLE_CHUNKS = config.getboolean('AMA', 'SHUFFLE_CHUNKS')
24 | DECAY_RATE = config.getfloat('AMA', 'DECAY_RATE')
25 |
26 | # load the data from a file
27 | with open(sys.argv[1]) as infile:
28 | dataset = json.load(infile)
29 |
30 | # placeholder for any number of bit vectors
31 | x = tf.placeholder(tf.float32, [None, len(dataset['features'])])
32 |
33 | # weights for each synapse
34 | W = tf.Variable(tf.zeros([len(dataset['features']), 2]))
35 |
36 | b = tf.Variable(tf.zeros([2]))
37 |
38 | # results
39 | y = tf.nn.softmax(tf.matmul(x, W) + b)
40 |
41 | # placeholder for correct answers
42 | y_ = tf.placeholder(tf.float32, [None, 2])
43 |
44 | cross_entropy = -tf.reduce_sum(y_*tf.log(y))
45 | init = tf.initialize_all_variables()
46 |
47 | sess = tf.Session()
48 |
49 | sess.run(init)
50 |
51 | #TODO make a clean interface for this
52 | #TODO make sure the training sample contains reasonable proportions of benign/malicious
53 | malicious_app_names = [app for app in dataset['apps'] if dataset['apps'][app]['malicious'] == [1,0]]
54 | benign_app_names = [app for app in dataset['apps'] if dataset['apps'][app]['malicious'] == [0,1]]
55 | # break up the data into chunks for training and testing
56 | malicious_app_name_chunks = list(chunks(malicious_app_names, math.floor(len(dataset['apps']) / NUM_CHUNKS)))
57 | benign_app_name_chunks = list(chunks(benign_app_names, math.floor(len(dataset['apps']) / NUM_CHUNKS)))
58 | if SHUFFLE_CHUNKS:
59 | random.shuffle(malicious_app_name_chunks)
60 | random.shuffle(benign_app_name_chunks)
61 |
62 | # the first chunk of each will be used for testing (and the rest for training)
63 | for i in range(int(sys.argv[2])):
64 | # decayed Learning Rate increases accuracy by 3-5%
65 | decayed_learning_rate = tf.train.exponential_decay(LEARNING_RATE, i, 1, DECAY_RATE, staircase=False)
66 | train_step = tf.train.GradientDescentOptimizer(decayed_learning_rate).minimize(cross_entropy)
67 |
68 | j = random.randrange(1, len(malicious_app_name_chunks))
69 | k = random.randrange(1, len(benign_app_name_chunks))
70 | app_names_chunk = malicious_app_name_chunks[j] + benign_app_name_chunks[k]
71 | batch_xs = [dataset['apps'][app]['vector'] for app in app_names_chunk]
72 | batch_ys = [dataset['apps'][app]['malicious'] for app in app_names_chunk]
73 | sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
74 |
75 | feature_weights=sess.run([W])[0]
76 | # store feature weights that were calculated. Used by match_features.py
77 | with open ('feature_weights.json','w') as f:
78 | json.dump(feature_weights.tolist(),f)
79 |
80 | app_names_chunk = malicious_app_name_chunks[0] + benign_app_name_chunks[0]
81 | test_xs = [dataset['apps'][app]['vector'] for app in app_names_chunk]
82 | test_ys = [dataset['apps'][app]['malicious'] for app in app_names_chunk]
83 |
84 | prediction_diff = tf.subtract(tf.argmax(y,1), tf.argmax(y_,1))
85 | # calculate how often benign apps were thought to be malicious
86 | false_positive = tf.equal(prediction_diff, tf.constant(-1,shape=[len(test_ys)],dtype=tf.int64))
87 | # calculate how often malicious apps were thought to be benign
88 | false_negative = tf.equal(prediction_diff, tf.constant(1,shape=[len(test_ys)],dtype=tf.int64))
89 | # recalculate prediction accuracy
90 | correct_prediction = tf.equal(prediction_diff, tf.constant(0,shape=[len(test_ys)],dtype=tf.int64))
91 |
92 | false_positive_rate = tf.reduce_mean(tf.cast(false_positive, tf.float32))
93 | false_negative_rate = tf.reduce_mean(tf.cast(false_negative, tf.float32))
94 | accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
95 |
96 | print(sess.run(false_positive_rate, feed_dict={x: test_xs, y_: test_ys}))
97 | print(sess.run(false_negative_rate, feed_dict={x: test_xs, y_: test_ys}))
98 | print(sess.run(accuracy, feed_dict={x: test_xs, y_: test_ys}))
99 | print(str(len(malicious_app_names)))
100 | print(str(len(benign_app_names)))
101 |
102 | def chunks(l, n):
103 | """Yield successive n-sized chunks from l."""
104 | for i in range(0, len(l), n):
105 | yield l[i:i+n]
106 |
107 | if __name__=='__main__':
108 | main()
109 |
--------------------------------------------------------------------------------