├── LICENSE ├── README.md ├── screenshots ├── 100_imports_99.png ├── 30_strings_73_exif.png ├── one.png └── two.png ├── similarity.py └── template.py /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

Twitter

2 | 3 | # viper-plugins 4 | These are my plugins for [the Viper Framework](https://github.com/viper-framework/viper), still in development! 5 | 6 | ### Plugins 7 | * Similarity Analysis 8 | * Tracking Template 9 | * Timestamp Heat Map 10 | 11 | 12 | ## Similarity Analysis w/ [Neo4j](https://neo4j.com/) 13 | Performs Similarity analysis to cluster and visualize collections of malware. Currently supports comparing by strings, windows pe imports and exif data. 14 | ``` 15 | usage: similarity [-h] [-t THRESHOLD] [-o OUTFILE] [-p] [-s] [-i] [-m MIN] 16 | [-e] [-c] 17 | 18 | Analyze all samples for code similarity 19 | 20 | optional arguments: 21 | -h, --help show this help message and exit 22 | -t THRESHOLD, --threshold THRESHOLD 23 | Jaccard index threshold (default is 0.7) 24 | -o OUTFILE, --output OUTFILE 25 | Output file name for the graph image. 26 | -p, --pdb Add path debug information label on nodes 27 | -s, --strings Compare samples using strings 28 | -i, --imports Compare samples using imports 29 | -m MIN, --min MIN Set minimum string length for search 30 | -e, --exif Compare samples using ExifData 31 | -c, --cli Command line only, no graphs 32 | ``` 33 | ### Requirements 34 | * The Viper Framework 35 | * pefile 36 | * exiftool 37 | * Neo4j 38 | * [py2neo](https://py2neo.org/v4/) 39 | * neomodel 40 | 41 | #### Add to viper.conf 42 | Update to match your environment 43 | 44 | ``` 45 | [similarity] 46 | url = http://localhost:7474/db/data 47 | user = neo4j 48 | pwd = 49 | ``` 50 | 51 | ### Examples 52 | Ryuk Strings Similarity Ryuk Imports Similarity 53 | 54 | ### Development 55 | * Add web ui support 56 | * Add linux and mac based malware support 57 | 58 | ## Tracking Template 59 | This is a template that can be used to create custom modules for tracking malware. 60 | ``` 61 | viper > template -h 62 | usage: template [-h] [-a] [-s SEARCH_STRING] 63 | 64 | Template module for tracking malware 65 | 66 | optional arguments: 67 | -h, --help show this help message and exit 68 | -a, --all Run the module on all samples 69 | -s SEARCH_STRING, --search SEARCH_STRING 70 | Search for a specifc string 71 | 72 | viper > template -a -s InternetOpen 73 | +------------------+------------------------------------------------------------------------------+ 74 | | Key | Value | 75 | +------------------+------------------------------------------------------------------------------+ 76 | | Name | 46fb27f4cff2d33baae3b1c199797d1f0929bc03166cebd092081e4fe2f9ea6e | 77 | +------------------+------------------------------------------------------------------------------+ 78 | | MD5 | bc041eb3eeb75312288557c23e919caa | 79 | +------------------+------------------------------------------------------------------------------+ 80 | | Timestamp | 2018:10:13 | 81 | +------------------+------------------------------------------------------------------------------+ 82 | | CodeSize | 87040 | 83 | +------------------+------------------------------------------------------------------------------+ 84 | | PDB Path | C:\Users\Admin\Documents\Visual Studio 2015\Projects\ConsoleApplication54new | 85 | | | crypted\x64\Release\ConsoleApplication54.pdb | 86 | +------------------+------------------------------------------------------------------------------+ 87 | | Search Results: | ['\x0c\x0bInternetOpenUrlA'] | 88 | +------------------+------------------------------------------------------------------------------+ 89 | 90 | +------------------+------------------------------------------------------------------------------+ 91 | | Key | Value | 92 | +------------------+------------------------------------------------------------------------------+ 93 | | Name | 1b465c0e12523747f892b48fa92a30f82e5027199a2aff06587c5269bd99f69a | 94 | +------------------+------------------------------------------------------------------------------+ 95 | | MD5 | cce28fefb5e16f4a9d0cc01fd5ad817c | 96 | +------------------+------------------------------------------------------------------------------+ 97 | | Timestamp | 2018:10:09 | 98 | +------------------+------------------------------------------------------------------------------+ 99 | | CodeSize | 86528 | 100 | +------------------+------------------------------------------------------------------------------+ 101 | | PDB Path | C:\Users\Admin\Documents\Visual Studio 2015\Projects\ConsoleApplication54new | 102 | | | crypted\x64\Release\ConsoleApplication54.pdb | 103 | +------------------+------------------------------------------------------------------------------+ 104 | | Search Results: | ['\x0c\x0bInternetOpenUrlA'] | 105 | +------------------+------------------------------------------------------------------------------+ 106 | 107 | ``` 108 | 109 | ## Timestamp Heat Map 110 | _Coming soon..._ 111 | -------------------------------------------------------------------------------- /screenshots/100_imports_99.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/colincowie/viper-plugins/3bfc483ad1376d63f85c94a6c7cc2a1c6137fdd8/screenshots/100_imports_99.png -------------------------------------------------------------------------------- /screenshots/30_strings_73_exif.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/colincowie/viper-plugins/3bfc483ad1376d63f85c94a6c7cc2a1c6137fdd8/screenshots/30_strings_73_exif.png -------------------------------------------------------------------------------- /screenshots/one.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/colincowie/viper-plugins/3bfc483ad1376d63f85c94a6c7cc2a1c6137fdd8/screenshots/one.png -------------------------------------------------------------------------------- /screenshots/two.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/colincowie/viper-plugins/3bfc483ad1376d63f85c94a6c7cc2a1c6137fdd8/screenshots/two.png -------------------------------------------------------------------------------- /similarity.py: -------------------------------------------------------------------------------- 1 | # Colin Cowie - @th3_protoCOL 2 | # Similarity analysis plugin for viper 3 | import os 4 | import re 5 | import string 6 | import pefile 7 | import exiftool 8 | import itertools 9 | 10 | from viper.common.abstracts import Module 11 | from viper.core.session import __sessions__ 12 | from viper.core.config import __config__ 13 | from viper.core.database import Database 14 | from viper.core.storage import get_sample_path 15 | from viper.common.objects import File 16 | 17 | from py2neo import Graph, Node, Relationship 18 | from neomodel import StructuredNode, StringProperty, DateProperty 19 | 20 | cfg = __config__ 21 | 22 | # Define Neo4j Node 23 | class SampleNode(StructuredNode): 24 | name = StringProperty(unique_index=True) 25 | timestamp = DateProperty() 26 | pdb = StringProperty() 27 | 28 | class Similarity(Module): 29 | cmd = 'similarity' 30 | description = 'Analyze all samples for code similarity' 31 | authors = ['th3_protoCOL'] 32 | 33 | def __init__(self): 34 | super(Similarity, self).__init__() 35 | self.parser.add_argument('-t', '--threshold', dest='threshold', type=float, default=0.75, help='Jaccard index threshold (default is 0.7)') 36 | self.parser.add_argument('-p', '--pdb', action='store_true', help='Add path debug information label on nodes') 37 | self.parser.add_argument('-s', '--strings', action='store_true', help='Compare samples using strings') 38 | self.parser.add_argument('-i', '--imports', action='store_true', help='Compare samples using imports') 39 | self.parser.add_argument('-m', '--min', dest='min', type=int, default=4, help='Set minimum string length for search') 40 | self.parser.add_argument('-e', '--exif', action='store_true', help='Compare samples using ExifData') 41 | 42 | 43 | def jaccard(self, set1, set2): 44 | set1_set = set(set1) 45 | set2_set = set(set2) 46 | intersection = set1_set.intersection(set2_set) 47 | intersection_length = float(len(intersection)) 48 | union = set1_set.union(set2_set) 49 | union_length = float(len(union)) 50 | return intersection_length / union_length 51 | 52 | def get_strings(self, f): 53 | # String implementation see http://stackoverflow.com/a/17197027/6880819 - Extended with Unicode support. todo: explore other string detections 54 | results = [] 55 | result = "" 56 | counter = 1 57 | wide_word = False 58 | min = self.args.min 59 | for c in f.data.decode('utf-8', 'ignore'): 60 | # Already have something, check if the second byte is a null 61 | if counter == 2 and c == "\x00": 62 | wide_word = True 63 | counter += 1 64 | continue 65 | # Every 2 chars we allow a 00 66 | if wide_word and c == "\x00" and not counter % 2: 67 | counter += 1 68 | continue 69 | # Valid char, go to next - newlines are to be considered as the end of the string 70 | if c in string.printable and c not in ['\n', '\r']: 71 | result += c 72 | counter += 1 73 | continue 74 | if len(result) >= min: 75 | results.append(result) 76 | # Reset the variables 77 | result = '' 78 | counter = 1 79 | wide_word = False 80 | if len(result) >= min: # Catch result at EOF 81 | results.append(result) 82 | return results 83 | 84 | def get_apis(self, path): 85 | try: 86 | pe = pefile.PE(path) 87 | except pefile.PEFormatError: 88 | return None 89 | 90 | results = [] 91 | 92 | if not hasattr(pe, 'DIRECTORY_ENTRY_IMPORT'): 93 | return results 94 | 95 | for entry in pe.DIRECTORY_ENTRY_IMPORT: 96 | for imp in entry.imports: 97 | results.append(imp.name.decode('utf-8')) 98 | return results 99 | 100 | def get_exif(self, f): 101 | with exiftool.ExifTool() as et: 102 | metadata = et.get_metadata(f) 103 | return metadata 104 | 105 | def parse_pdb(self, path): 106 | try: 107 | pe = pefile.PE(path) 108 | except pefile.PEFormatError: 109 | return None 110 | 111 | result = None 112 | try: 113 | result = str(pe.get_string_from_data(0x18, pe.get_data(pe.DIRECTORY_ENTRY_DEBUG[0].struct.AddressOfRawData, pe.DIRECTORY_ENTRY_DEBUG[0].struct.SizeOfData))) 114 | except Exception: 115 | pass 116 | 117 | return result 118 | 119 | # todo: improve and implement this 120 | def parse_dll(self, strings): 121 | DLL_REGEX = re.compile(r'^[a-zA-Z0-9]{8,}.dll$', re.IGNORECASE) 122 | result = None 123 | for entry in strings: 124 | if DLL_REGEX.search(entry): 125 | if "32" not in entry: 126 | result = entry 127 | return result 128 | 129 | def run(self): 130 | super(Similarity, self).run() 131 | 132 | if self.args is None: 133 | return 134 | elif self.args.imports and self.args.threshold == 0.75: #todo: find a better way to check if thresholds haven't been set 135 | self.log('warning', 'Adjusting default threashold to 0.97 to scale for imports') 136 | threshold = 0.97 137 | elif self.args.threshold: 138 | threshold = self.args.threshold 139 | self.log('info', 'Setting Jaccard index threshold to '+ str(threshold)) 140 | 141 | # Get all samples from viper database 142 | db = Database() 143 | samples = db.find(key='all') 144 | malware_features = dict() 145 | 146 | # Neo4j Setup 147 | ## Get Url from Config 148 | neo4j_url = cfg.similarity.url 149 | ## Get Username from Config 150 | neo4j_user = cfg.similarity.user 151 | ## Get Password from Config 152 | neo4j_pwd = cfg.similarity.pwd 153 | ## Connect to neo4j data and define a graph 154 | graph = Graph(neo4j_url, user=neo4j_user, password=neo4j_pwd) 155 | try: 156 | graph.delete_all() 157 | except: 158 | self.log("Error", "Issue deleting graph. Are the credentials correct in the config file?") 159 | return 160 | 161 | sample_nodes = [] 162 | 163 | for sample in samples: 164 | malware_path = get_sample_path(sample.sha256) 165 | features = [] 166 | 167 | timestamp = "" 168 | # Check arguments to determine what should be compared 169 | if self.args.exif: 170 | if not self.args.strings and not self.args.imports: # Can I find a better way to do this? 171 | features += self.get_exif(malware_path) 172 | metadata = [] 173 | with exiftool.ExifTool() as et: 174 | metadata = et.get_metadata(malware_path) 175 | if 'EXE:TimeStamp' in metadata: 176 | timestamp = metadata['EXE:TimeStamp'][:10] 177 | if self.args.strings: 178 | features += self.get_strings(File(malware_path)) 179 | if self.args.imports: 180 | imports = self.get_apis(malware_path) 181 | if imports is not None: 182 | features += imports 183 | else: 184 | self.log('warning', 'No imports found for {0}...'.format(sample.md5)) 185 | 186 | # Adds path debug information to nodes 187 | pdb_label = "" 188 | if self.args.pdb: 189 | pdb = self.parse_pdb(malware_path) 190 | if pdb is not None: 191 | self.log('success', 'Found pdb path {0}'.format(pdb)) 192 | try: 193 | ## Was not sure if you had a special purpose behind parsing the pdb string 194 | #project_start = pdb.index('\\Projects') 195 | #project_end = pdb.index('\\x64\\') 196 | #pdb_label = pdb[int(project_start)+9:int(project_end)] 197 | pdb_label = pdb 198 | except: 199 | self.log('error','Unexpected pdb path') 200 | 201 | # Set default comparison 202 | if (not self.args.strings and not self.args.imports and not self.args.exif): 203 | features += self.get_strings(File(malware_path)) 204 | 205 | if len(features) == 0: 206 | self.log('error', 'Extracted {0} features from {1}...'.format(len(features), sample.md5)) 207 | continue 208 | 209 | self.log('success', 'Extracted {0} features from {1}...'.format(len(features), sample.md5)) 210 | 211 | malware_features[malware_path] = features 212 | 213 | tx = graph.begin() 214 | 215 | #Create new nodes 216 | sample_node = Node("SampleNode", name=str(sample.sha256), timestamp=timestamp, pdb=pdb_label) 217 | labels = [sample.sha256, timestamp] 218 | sample_node.cast(labels) 219 | tx.create(sample_node) 220 | tx.commit() 221 | sample_nodes.append(sample_node) 222 | 223 | # Determine the jaccard index beteween malware and graph realtionships 224 | self.log('info', 'Starting graphing process') 225 | for malware1, malware2 in itertools.combinations(sample_nodes, 2): 226 | # Compute the jaccard index for the current malware pair 227 | jaccard_index = self.jaccard(malware_features[get_sample_path(malware1["name"])], malware_features[get_sample_path(malware2["name"])]) 228 | # If the jaccard distance is above the threshold draw a connection between nodes 229 | if jaccard_index > threshold: 230 | if jaccard_index > 0.95: 231 | r = Relationship(malware1,"very_high", malware2) 232 | elif jaccard_index > 0.88: 233 | r = Relationship(malware1,"high", malware2) 234 | elif jaccard_index > 0.83: 235 | r = Relationship(malware1,"moderate", malware2) 236 | elif jaccard_index > 0.78: 237 | r = Relationship(malware1,"low", malware2) 238 | elif jaccard_index > 0.60: 239 | r = Relationship(malware1,"very_low", malware2) 240 | 241 | tx = graph.begin() 242 | tx.create(r) 243 | tx.commit() 244 | 245 | self.log('success', 'Finished graphing nodes and realtionships') 246 | -------------------------------------------------------------------------------- /template.py: -------------------------------------------------------------------------------- 1 | # Colin Cowie - @th3_protoCOL 2 | # Template module for malware analysis 3 | import os 4 | import re 5 | import string 6 | import pefile 7 | import exiftool 8 | 9 | from viper.common.abstracts import Module 10 | from viper.core.session import __sessions__ 11 | from viper.core.config import __config__ 12 | from viper.core.database import Database 13 | from viper.core.storage import get_sample_path 14 | from viper.common.objects import File 15 | 16 | class Template(Module): 17 | cmd = 'hunt' 18 | description = 'Template module for tracking malware' 19 | authors = ['th3_protoCOL'] 20 | emails = [] # todo: move to its own plugin 21 | 22 | def __init__(self): 23 | super(Template, self).__init__() 24 | self.parser.add_argument('-a', '--all', action='store_true', help='Run the module on all samples') 25 | self.parser.add_argument('-e', '--emails', action='store_true', help='Extract all email addresses') 26 | self.parser.add_argument('-s', '--search', dest='search_string', help='Search for a specifc string') 27 | 28 | def get_strings(self, f): 29 | # String implementation see http://stackoverflow.com/a/17197027/6880819 - Extended with Unicode support. todo: explore other string detections 30 | results = [] 31 | result = "" 32 | counter = 1 33 | wide_word = False 34 | min = 3 35 | for c in f.data.decode('utf-8', 'ignore'): 36 | # Already have something, check if the second byte is a null 37 | if counter == 2 and c == "\x00": 38 | wide_word = True 39 | counter += 1 40 | continue 41 | # Every 2 chars we allow a 00 42 | if wide_word and c == "\x00" and not counter % 2: 43 | counter += 1 44 | continue 45 | # Valid char, go to next - newlines are to be considered as the end of the string 46 | if c in string.printable and c not in ['\n', '\r']: 47 | result += c 48 | counter += 1 49 | continue 50 | if len(result) >= min: 51 | results.append(result) 52 | # Reset the variables 53 | result = '' 54 | counter = 1 55 | wide_word = False 56 | if len(result) >= min: # Catch result at EOF 57 | results.append(result) 58 | return results 59 | 60 | def parse_search(self, strings, search): 61 | results = [] 62 | for entry in strings: 63 | to_add = False 64 | if re.search(search, entry): 65 | results.append(entry) 66 | 67 | return results 68 | 69 | def parse_ips(self, strings): 70 | IP_REGEX = re.compile(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$') 71 | results = [] 72 | for entry in strings: 73 | if IP_REGEX.search(entry): 74 | results.append(entry) 75 | return results; 76 | 77 | def parse_pdb(self, strings): 78 | PDB_REGEX = re.compile(r'\.pdb$', re.IGNORECASE) 79 | result = None 80 | for entry in strings: 81 | if PDB_REGEX.search(entry): 82 | result = entry; 83 | return result; 84 | 85 | def parse_emails(self, strings): 86 | EMAIL_REGEX = re.compile(r'(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)', re.IGNORECASE) 87 | emails = [] 88 | for entry in strings: 89 | if EMAIL_REGEX.search(entry): 90 | emails.append(entry); 91 | return emails; 92 | 93 | # Main analysis function 94 | def scan(self, file): 95 | sample = File(file) 96 | strings = self.get_strings(sample) 97 | 98 | # Sets up rows - modify these 99 | rows = [ 100 | ['Name', sample.name], 101 | ['MD5', sample.md5] 102 | ] 103 | 104 | # Get exif data 105 | metadata = [] 106 | timestamp = "" 107 | with exiftool.ExifTool() as et: 108 | metadata = et.get_metadata(file) 109 | if 'EXE:TimeStamp' in metadata: 110 | rows.append(['TimeStamp',metadata['EXE:TimeStamp'][:10]]) 111 | if 'EXE:CodeSize' in metadata: 112 | rows.append(['CodeSize',metadata['EXE:CodeSize']]) 113 | header = ['Key', 'Value'] 114 | 115 | rows.append(['PDB Path', self.parse_pdb(strings)]) 116 | rows.append(['IPv4s', self.parse_ips(strings)]) 117 | rows.append(['Emails', self.parse_emails(strings)]) 118 | 119 | #Find Emails 120 | if self.args.emails: 121 | for email in self.parse_emails(strings): 122 | self.emails.append(email) 123 | 124 | # Search for specfic string 125 | if self.args.search_string: 126 | search_result = self.parse_search(strings, self.args.search_string) 127 | if search_result: 128 | rows.append(['Search Results: ', search_result]) 129 | self.log('table', dict(header=header, rows=rows)) 130 | print('') 131 | else: 132 | self.log('table', dict(header=header, rows=rows)) 133 | 134 | def run(self): 135 | super(Template, self).run() 136 | 137 | if self.args is None: 138 | return 139 | 140 | # Check arguments and scan accordingly 141 | if self.args.all: 142 | db = Database() 143 | samples = db.find(key='all') 144 | for sample in samples: 145 | self.scan(get_sample_path(sample.sha256)) 146 | if self.args.emails: 147 | self.log('success', "Found emails: ") 148 | self.log('success', str(set(self.emails))) 149 | 150 | elif __sessions__.is_set(): 151 | self.scan(__sessions__.current.file.path) 152 | else: 153 | self.usage() 154 | --------------------------------------------------------------------------------