misp-modules 2.4.196__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. misp_modules/__init__.py +379 -0
  2. misp_modules/helpers/__init__.py +1 -0
  3. misp_modules/helpers/cache.py +84 -0
  4. misp_modules/lib/__init__.py +4 -0
  5. misp_modules/lib/_vmray/__init__.py +0 -0
  6. misp_modules/lib/_vmray/parser.py +1417 -0
  7. misp_modules/lib/_vmray/rest_api.py +148 -0
  8. misp_modules/lib/cof2misp/LICENSE-2.0.txt +202 -0
  9. misp_modules/lib/cof2misp/__init__.py +0 -0
  10. misp_modules/lib/cof2misp/cof.py +165 -0
  11. misp_modules/lib/joe_mapping.py +114 -0
  12. misp_modules/lib/joe_parser.py +573 -0
  13. misp_modules/lib/lastline_api.py +841 -0
  14. misp_modules/lib/qintel_helper.py +263 -0
  15. misp_modules/lib/stix2misp.py +2080 -0
  16. misp_modules/lib/stix2misp_mapping.py +460 -0
  17. misp_modules/lib/synonymsToTagNames.json +1 -0
  18. misp_modules/lib/vt_graph_parser/__init__.py +8 -0
  19. misp_modules/lib/vt_graph_parser/errors.py +20 -0
  20. misp_modules/lib/vt_graph_parser/helpers/__init__.py +7 -0
  21. misp_modules/lib/vt_graph_parser/helpers/parsers.py +88 -0
  22. misp_modules/lib/vt_graph_parser/helpers/rules.py +304 -0
  23. misp_modules/lib/vt_graph_parser/helpers/wrappers.py +58 -0
  24. misp_modules/lib/vt_graph_parser/importers/__init__.py +7 -0
  25. misp_modules/lib/vt_graph_parser/importers/base.py +98 -0
  26. misp_modules/lib/vt_graph_parser/importers/pymisp_response.py +73 -0
  27. misp_modules/modules/__init__.py +4 -0
  28. misp_modules/modules/action_mod/__init__.py +1 -0
  29. misp_modules/modules/action_mod/_utils/__init__.py +1 -0
  30. misp_modules/modules/action_mod/_utils/utils.py +70 -0
  31. misp_modules/modules/action_mod/mattermost.py +113 -0
  32. misp_modules/modules/action_mod/slack.py +96 -0
  33. misp_modules/modules/action_mod/testaction.py +68 -0
  34. misp_modules/modules/expansion/__init__.py +36 -0
  35. misp_modules/modules/expansion/_dnsdb_query/COPYRIGHT +27 -0
  36. misp_modules/modules/expansion/_dnsdb_query/LICENSE +202 -0
  37. misp_modules/modules/expansion/_dnsdb_query/README.md +162 -0
  38. misp_modules/modules/expansion/_dnsdb_query/__init__.py +0 -0
  39. misp_modules/modules/expansion/_dnsdb_query/dnsdb_query.py +327 -0
  40. misp_modules/modules/expansion/_ransomcoindb/__init__.py +0 -0
  41. misp_modules/modules/expansion/_ransomcoindb/ransomcoindb.py +96 -0
  42. misp_modules/modules/expansion/_vulnerability_parser/__init__.py +0 -0
  43. misp_modules/modules/expansion/_vulnerability_parser/vulnerability_parser.py +118 -0
  44. misp_modules/modules/expansion/abuseipdb.py +146 -0
  45. misp_modules/modules/expansion/apiosintds.py +365 -0
  46. misp_modules/modules/expansion/apivoid.py +133 -0
  47. misp_modules/modules/expansion/assemblyline_query.py +179 -0
  48. misp_modules/modules/expansion/assemblyline_submit.py +100 -0
  49. misp_modules/modules/expansion/backscatter_io.py +84 -0
  50. misp_modules/modules/expansion/btc_scam_check.py +54 -0
  51. misp_modules/modules/expansion/btc_steroids.py +238 -0
  52. misp_modules/modules/expansion/censys_enrich.py +287 -0
  53. misp_modules/modules/expansion/circl_passivedns.py +85 -0
  54. misp_modules/modules/expansion/circl_passivessl.py +113 -0
  55. misp_modules/modules/expansion/clamav.py +129 -0
  56. misp_modules/modules/expansion/cluster25_expand.py +239 -0
  57. misp_modules/modules/expansion/countrycode.py +69 -0
  58. misp_modules/modules/expansion/cpe.py +140 -0
  59. misp_modules/modules/expansion/crowdsec.py +235 -0
  60. misp_modules/modules/expansion/crowdstrike_falcon.py +148 -0
  61. misp_modules/modules/expansion/cuckoo_submit.py +161 -0
  62. misp_modules/modules/expansion/cve.py +57 -0
  63. misp_modules/modules/expansion/cve_advanced.py +185 -0
  64. misp_modules/modules/expansion/cytomic_orion.py +196 -0
  65. misp_modules/modules/expansion/dbl_spamhaus.py +78 -0
  66. misp_modules/modules/expansion/dns.py +71 -0
  67. misp_modules/modules/expansion/docx_enrich.py +71 -0
  68. misp_modules/modules/expansion/domaintools.py +290 -0
  69. misp_modules/modules/expansion/eql.py +91 -0
  70. misp_modules/modules/expansion/eupi.py +86 -0
  71. misp_modules/modules/expansion/extract_url_components.py +83 -0
  72. misp_modules/modules/expansion/farsight_passivedns.py +243 -0
  73. misp_modules/modules/expansion/geoip_asn.py +75 -0
  74. misp_modules/modules/expansion/geoip_city.py +75 -0
  75. misp_modules/modules/expansion/geoip_country.py +73 -0
  76. misp_modules/modules/expansion/google_safe_browsing.py +86 -0
  77. misp_modules/modules/expansion/google_search.py +57 -0
  78. misp_modules/modules/expansion/google_threat_intelligence.py +453 -0
  79. misp_modules/modules/expansion/greynoise.py +346 -0
  80. misp_modules/modules/expansion/hashdd.py +53 -0
  81. misp_modules/modules/expansion/hashlookup.py +118 -0
  82. misp_modules/modules/expansion/hibp.py +62 -0
  83. misp_modules/modules/expansion/html_to_markdown.py +63 -0
  84. misp_modules/modules/expansion/hyasinsight.py +881 -0
  85. misp_modules/modules/expansion/intel471.py +73 -0
  86. misp_modules/modules/expansion/intelmq_eventdb.py.experimental +67 -0
  87. misp_modules/modules/expansion/ip2locationio.py +90 -0
  88. misp_modules/modules/expansion/ipasn.py +70 -0
  89. misp_modules/modules/expansion/ipinfo.py +112 -0
  90. misp_modules/modules/expansion/ipqs_fraud_and_risk_scoring.py +633 -0
  91. misp_modules/modules/expansion/iprep.py +98 -0
  92. misp_modules/modules/expansion/jinja_template_rendering.py +54 -0
  93. misp_modules/modules/expansion/joesandbox_query.py +91 -0
  94. misp_modules/modules/expansion/joesandbox_submit.py +147 -0
  95. misp_modules/modules/expansion/lastline_query.py +148 -0
  96. misp_modules/modules/expansion/lastline_submit.py +180 -0
  97. misp_modules/modules/expansion/macaddress_io.py +130 -0
  98. misp_modules/modules/expansion/macvendors.py +55 -0
  99. misp_modules/modules/expansion/malshare_upload.py +107 -0
  100. misp_modules/modules/expansion/malwarebazaar.py +67 -0
  101. misp_modules/modules/expansion/mcafee_insights_enrich.py +249 -0
  102. misp_modules/modules/expansion/mmdb_lookup.py +138 -0
  103. misp_modules/modules/expansion/module.py.skeleton +44 -0
  104. misp_modules/modules/expansion/mwdb.py +152 -0
  105. misp_modules/modules/expansion/ocr_enrich.py +74 -0
  106. misp_modules/modules/expansion/ods_enrich.py +71 -0
  107. misp_modules/modules/expansion/odt_enrich.py +61 -0
  108. misp_modules/modules/expansion/onyphe.py +243 -0
  109. misp_modules/modules/expansion/onyphe_full.py +387 -0
  110. misp_modules/modules/expansion/otx.py +167 -0
  111. misp_modules/modules/expansion/passive_ssh.py +150 -0
  112. misp_modules/modules/expansion/passivetotal.py +358 -0
  113. misp_modules/modules/expansion/pdf_enrich.py +58 -0
  114. misp_modules/modules/expansion/pptx_enrich.py +65 -0
  115. misp_modules/modules/expansion/qintel_qsentry.py +229 -0
  116. misp_modules/modules/expansion/qrcode.py +99 -0
  117. misp_modules/modules/expansion/ransomcoindb.py +82 -0
  118. misp_modules/modules/expansion/rbl.py +126 -0
  119. misp_modules/modules/expansion/recordedfuture.py +544 -0
  120. misp_modules/modules/expansion/reversedns.py +77 -0
  121. misp_modules/modules/expansion/securitytrails.py +571 -0
  122. misp_modules/modules/expansion/shodan.py +244 -0
  123. misp_modules/modules/expansion/sigma_queries.py +61 -0
  124. misp_modules/modules/expansion/sigma_syntax_validator.py +49 -0
  125. misp_modules/modules/expansion/sigmf_expand.py +303 -0
  126. misp_modules/modules/expansion/socialscan.py +108 -0
  127. misp_modules/modules/expansion/sophoslabs_intelix.py +146 -0
  128. misp_modules/modules/expansion/sourcecache.py +57 -0
  129. misp_modules/modules/expansion/stairwell.py +156 -0
  130. misp_modules/modules/expansion/stix2_pattern_syntax_validator.py +56 -0
  131. misp_modules/modules/expansion/threatcrowd.py +170 -0
  132. misp_modules/modules/expansion/threatfox.py +75 -0
  133. misp_modules/modules/expansion/threatminer.py +152 -0
  134. misp_modules/modules/expansion/triage_submit.py +119 -0
  135. misp_modules/modules/expansion/trustar_enrich.py +235 -0
  136. misp_modules/modules/expansion/urlhaus.py +164 -0
  137. misp_modules/modules/expansion/urlscan.py +269 -0
  138. misp_modules/modules/expansion/variotdbs.py +133 -0
  139. misp_modules/modules/expansion/virustotal.py +311 -0
  140. misp_modules/modules/expansion/virustotal_public.py +272 -0
  141. misp_modules/modules/expansion/virustotal_upload.py +91 -0
  142. misp_modules/modules/expansion/vmray_submit.py +161 -0
  143. misp_modules/modules/expansion/vmware_nsx.py +628 -0
  144. misp_modules/modules/expansion/vulndb.py +292 -0
  145. misp_modules/modules/expansion/vulnerability_lookup.py +324 -0
  146. misp_modules/modules/expansion/vulners.py +81 -0
  147. misp_modules/modules/expansion/vysion.py +221 -0
  148. misp_modules/modules/expansion/whois.py +72 -0
  149. misp_modules/modules/expansion/whoisfreaks.py +232 -0
  150. misp_modules/modules/expansion/wiki.py +58 -0
  151. misp_modules/modules/expansion/xforceexchange.py +189 -0
  152. misp_modules/modules/expansion/xlsx_enrich.py +63 -0
  153. misp_modules/modules/expansion/yara_query.py +70 -0
  154. misp_modules/modules/expansion/yara_syntax_validator.py +49 -0
  155. misp_modules/modules/expansion/yeti.py +196 -0
  156. misp_modules/modules/export_mod/__init__.py +3 -0
  157. misp_modules/modules/export_mod/cef_export.py +93 -0
  158. misp_modules/modules/export_mod/cisco_firesight_manager_ACL_rule_export.py +150 -0
  159. misp_modules/modules/export_mod/defender_endpoint_export.py +141 -0
  160. misp_modules/modules/export_mod/goamlexport.py +255 -0
  161. misp_modules/modules/export_mod/liteexport.py +97 -0
  162. misp_modules/modules/export_mod/mass_eql_export.py +106 -0
  163. misp_modules/modules/export_mod/nexthinkexport.py +131 -0
  164. misp_modules/modules/export_mod/osqueryexport.py +125 -0
  165. misp_modules/modules/export_mod/pdfexport.py +107 -0
  166. misp_modules/modules/export_mod/testexport.py +73 -0
  167. misp_modules/modules/export_mod/threatStream_misp_export.py +114 -0
  168. misp_modules/modules/export_mod/threat_connect_export.py +125 -0
  169. misp_modules/modules/export_mod/virustotal_collections.py +141 -0
  170. misp_modules/modules/export_mod/vt_graph.py +120 -0
  171. misp_modules/modules/export_mod/yara_export.py +290 -0
  172. misp_modules/modules/import_mod/__init__.py +22 -0
  173. misp_modules/modules/import_mod/cof2misp.py +264 -0
  174. misp_modules/modules/import_mod/csvimport.py +319 -0
  175. misp_modules/modules/import_mod/cuckooimport.py +749 -0
  176. misp_modules/modules/import_mod/email_import.py +294 -0
  177. misp_modules/modules/import_mod/goamlimport.py +188 -0
  178. misp_modules/modules/import_mod/import_blueprint.py +93 -0
  179. misp_modules/modules/import_mod/joe_import.py +74 -0
  180. misp_modules/modules/import_mod/lastline_import.py +160 -0
  181. misp_modules/modules/import_mod/mispjson.py +73 -0
  182. misp_modules/modules/import_mod/ocr.py +122 -0
  183. misp_modules/modules/import_mod/openiocimport.py +99 -0
  184. misp_modules/modules/import_mod/taxii21.py +383 -0
  185. misp_modules/modules/import_mod/testimport.py +73 -0
  186. misp_modules/modules/import_mod/threatanalyzer_import.py +552 -0
  187. misp_modules/modules/import_mod/url_import.py +97 -0
  188. misp_modules/modules/import_mod/vmray_import.py +96 -0
  189. misp_modules/modules/import_mod/vmray_summary_json_import.py +87 -0
  190. misp_modules-2.4.196.dist-info/LICENSE +661 -0
  191. misp_modules-2.4.196.dist-info/METADATA +281 -0
  192. misp_modules-2.4.196.dist-info/RECORD +194 -0
  193. misp_modules-2.4.196.dist-info/WHEEL +4 -0
  194. misp_modules-2.4.196.dist-info/entry_points.txt +3 -0
@@ -0,0 +1,264 @@
1
+ """ PassiveDNS Common Output Format (COF) MISP importer.
2
+
3
+ Takes as input a valid COF file or the output of the dnsdbflex utility
4
+ and creates MISP objects for the input.
5
+
6
+ Copyright 2021: Farsight Security (https://www.farsightsecurity.com/)
7
+
8
+ Author: Aaron Kaplan <aaron@lo-res.org>
9
+
10
+ Released under the Apache 2.0 license.
11
+ See: https://www.apache.org/licenses/LICENSE-2.0.txt
12
+
13
+ """
14
+
15
+ import sys
16
+ import json
17
+ import base64
18
+
19
+
20
+ import ndjson
21
+
22
+ # from pymisp import MISPObject, MISPEvent, PyMISP
23
+ from pymisp import MISPObject
24
+
25
+ from cof2misp.cof import validate_cof, validate_dnsdbflex
26
+
27
+
28
+ create_specific_attributes = False # this is for https://github.com/MISP/misp-objects/pull/314
29
+
30
+
31
+ misperrors = {'error': 'Error'}
32
+ userConfig = {}
33
+
34
+ inputSource = ['file']
35
+
36
+ mispattributes = {'inputSource': ['file'], 'output': ['MISP objects'],
37
+ 'format': 'misp_standard'}
38
+
39
+
40
+ moduleinfo = {
41
+ 'version': '0.3',
42
+ 'author': 'Aaron Kaplan',
43
+ 'description': 'Passive DNS Common Output Format (COF) MISP importer',
44
+ 'module-type': ['import'],
45
+ 'name': 'PDNS COF Importer',
46
+ 'requirements': ['PyMISP'],
47
+ 'features': 'Takes as input a valid COF file or the output of the dnsdbflex utility and creates MISP objects for the input.',
48
+ 'references': ['https://tools.ietf.org/id/draft-dulaunoy-dnsop-passive-dns-cof-08.html'],
49
+ 'input': 'Passive DNS output in Common Output Format (COF)',
50
+ 'output': 'MISP objects',
51
+ 'logo': '',
52
+ }
53
+
54
+ moduleconfig = []
55
+
56
+
57
+ # misp = PyMISP()
58
+
59
+
60
+ def parse_and_insert_cof(data: str) -> dict:
61
+ """Parse and validate the COF data.
62
+
63
+ Parameters
64
+ ----------
65
+ data as a string
66
+
67
+ Returns
68
+ -------
69
+ A dict with either the error message or the data which may be sent off the the caller of handler()
70
+
71
+ Raises
72
+ --------
73
+ none. All Exceptions will be handled here. On error, a misperror is returned.
74
+ """
75
+
76
+ objects = []
77
+ try:
78
+ entries = ndjson.loads(data)
79
+ for entry in entries: # iterate over all ndjson lines
80
+
81
+ # validate here (simple validation or full JSON Schema validation)
82
+ if not validate_cof(entry):
83
+ return {"error": "Could not validate the COF input '%s'" % entry}
84
+
85
+ # Next, extract some fields
86
+ rrtype = entry['rrtype'].upper()
87
+ rrname = entry['rrname'].rstrip('.')
88
+ rdata = [x.rstrip('.') for x in entry['rdata']]
89
+
90
+ # create a new MISP object, based on the passive-dns object for each nd-JSON line
91
+ o = MISPObject(name='passive-dns', standalone=False, comment='created by cof2misp')
92
+
93
+ # o.add_tag('tlp:amber') # FIXME: we'll want to add a tlp: tag to the object
94
+ if 'bailiwick' in entry:
95
+ o.add_attribute('bailiwick', value=entry['bailiwick'].rstrip('.'), distribution=0)
96
+
97
+ #
98
+ # handle the combinations of rrtype (domain, ip) on both left and right side
99
+ #
100
+
101
+ if create_specific_attributes:
102
+ if rrtype in ['A', 'AAAA', 'A6']: # address type
103
+ # address type
104
+ o.add_attribute('rrname_domain', value=rrname, distribution=0)
105
+ for r in rdata:
106
+ o.add_attribute('rdata_ip', value=r, distribution=0)
107
+ elif rrtype in ['CNAME', 'DNAME', 'NS']: # both sides are domains
108
+ o.add_attribute('rrname_domain', value=rrname, distribution=0)
109
+ for r in rdata:
110
+ o.add_attribute('rdata_domain', value=r, distribution=0)
111
+ elif rrtype in ['SOA']: # left side is a domain, right side is text
112
+ o.add_attribute('rrname_domain', value=rrname, distribution=0)
113
+
114
+ #
115
+ # now do the regular filling up of rrname, rrtype, time_first, etc.
116
+ #
117
+ o.add_attribute('rrname', value=rrname, distribution=0)
118
+ o.add_attribute('rrtype', value=rrtype, distribution=0)
119
+ for r in rdata:
120
+ o.add_attribute('rdata', value=r, distribution=0)
121
+ o.add_attribute('raw_rdata', value=json.dumps(rdata), distribution=0) # FIXME: do we need to hex encode it?
122
+ o.add_attribute('time_first', value=entry['time_first'], distribution=0)
123
+ o.add_attribute('time_last', value=entry['time_last'], distribution=0)
124
+ o.first_seen = entry['time_first'] # is this redundant?
125
+ o.last_seen = entry['time_last']
126
+
127
+ #
128
+ # Now add the other optional values. # FIXME: how about a map() other function. DNRY
129
+ #
130
+ for k in ['count', 'sensor_id', 'origin', 'text', 'time_first_ms', 'time_last_ms', 'zone_time_first', 'zone_time_last']:
131
+ if k in entry and entry[k]:
132
+ o.add_attribute(k, value=entry[k], distribution=0)
133
+
134
+ #
135
+ # add COF entry to MISP object
136
+ #
137
+ objects.append(o.to_json())
138
+
139
+ r = {'results': {'Object': [json.loads(o) for o in objects]}}
140
+ except Exception as ex:
141
+ misperrors["error"] = "An error occured during parsing of input: '%s'" % (str(ex),)
142
+ return misperrors
143
+ return r
144
+
145
+
146
+ def parse_and_insert_dnsdbflex(data: str):
147
+ """Parse and validate the more simplier dndsdbflex output data.
148
+
149
+ Parameters
150
+ ----------
151
+ data as a string
152
+
153
+ Returns
154
+ -------
155
+ A dict with either the error message or the data which may be sent off the the caller of handler()
156
+
157
+ Raises
158
+ --------
159
+ none
160
+ """
161
+ objects = []
162
+ try:
163
+ entries = ndjson.loads(data)
164
+ for entry in entries: # iterate over all ndjson lines
165
+ # validate here (simple validation or full JSON Schema validation)
166
+ if not validate_dnsdbflex(entry):
167
+ return {"error": "Could not validate the dnsdbflex input '%s'" % entry}
168
+
169
+ # Next, extract some fields
170
+ rrtype = entry['rrtype'].upper()
171
+ rrname = entry['rrname'].rstrip('.')
172
+
173
+ # create a new MISP object, based on the passive-dns object for each nd-JSON line
174
+ try:
175
+ o = MISPObject(name='passive-dns', standalone=False, distribution=0, comment='DNSDBFLEX import by cof2misp')
176
+ o.add_attribute('rrtype', value=rrtype, distribution=0, comment='DNSDBFLEX import by cof2misp')
177
+ o.add_attribute('rrname', value=rrname, distribution=0, comment='DNSDBFLEX import by cof2misp')
178
+ except Exception as ex:
179
+ print("could not create object. Reason: %s" % str(ex))
180
+
181
+ #
182
+ # add dnsdbflex entry to MISP object
183
+ #
184
+ objects.append(o.to_json())
185
+
186
+ r = {'results': {'Object': [json.loads(o) for o in objects]}}
187
+ except Exception as ex:
188
+ misperrors["error"] = "An error occured during parsing of input: '%s'" % (str(ex),)
189
+ return misperrors
190
+ return r
191
+
192
+
193
+ def is_dnsdbflex(data: str) -> bool:
194
+ """Check if the supplied data conforms to the dnsdbflex output (which only contains rrname and rrtype)
195
+
196
+ Parameters
197
+ ----------
198
+ ndjson data as a string
199
+
200
+ Returns
201
+ -------
202
+ True or False
203
+
204
+ Raises
205
+ --------
206
+ none
207
+ """
208
+
209
+ try:
210
+ j = ndjson.loads(data)
211
+ for line in j:
212
+ if not set(line.keys()) == {'rrname', 'rrtype'}:
213
+ return False # shortcut. We assume it's not if a single line does not conform
214
+ return True
215
+ except Exception as ex:
216
+ print("oops, this should not have happened. Maybe not an ndjson file? Reason: %s" % (str(ex),), file=sys.stderr)
217
+ return False
218
+
219
+
220
+ def is_cof(data: str) -> bool:
221
+ return True
222
+
223
+
224
+ def handler(q=False):
225
+ if q is False:
226
+ return False
227
+
228
+ request = json.loads(q)
229
+ # Parse the json, determine which type of JSON it is (dnsdbflex or COF?)
230
+ # Validate it
231
+ # transform into MISP object
232
+ # push to MISP
233
+ # event_id = request['event_id']
234
+ # event = misp.get_event(event_id)
235
+ # print("event_id = %s" % event_id, file=sys.stderr)
236
+ try:
237
+ data = base64.b64decode(request["data"]).decode('utf-8')
238
+ if not data:
239
+ return json.dumps({'success': 0}) # empty file is ok
240
+ if is_dnsdbflex(data):
241
+ return parse_and_insert_dnsdbflex(data)
242
+ elif is_cof(data):
243
+ # check if it's valid COF format
244
+ return parse_and_insert_cof(data)
245
+ else:
246
+ return {'error': 'Could not find any valid COF input nor dnsdbflex input. Please have a loot at: https://datatracker.ietf.org/doc/draft-dulaunoy-dnsop-passive-dns-cof/'}
247
+ except Exception as ex:
248
+ print("oops, got exception %s" % str(ex), file=sys.stderr)
249
+ return {'error': "Got exception %s" % str(ex)}
250
+
251
+
252
+ def introspection():
253
+ return mispattributes
254
+
255
+
256
+ def version():
257
+ moduleinfo['config'] = moduleconfig
258
+ return moduleinfo
259
+
260
+
261
+ if __name__ == '__main__':
262
+ x = open('test.json', 'r')
263
+ r = handler(q=x.read())
264
+ print(json.dumps(r))
@@ -0,0 +1,319 @@
1
+ from pymisp import MISPEvent, MISPObject
2
+ import csv
3
+ import io
4
+ import base64
5
+
6
+ misperrors = {'error': 'Error'}
7
+ moduleinfo = {
8
+ 'version': '0.2',
9
+ 'author': 'Christian Studer',
10
+ 'module-type': ['import'],
11
+ 'name': 'CSV Import',
12
+ 'description': 'Module to import MISP attributes from a csv file.',
13
+ 'requirements': ['PyMISP'],
14
+ 'features': "In order to parse data from a csv file, a header is required to let the module know which column is matching with known attribute fields / MISP types.\n\nThis header either comes from the csv file itself or is part of the configuration of the module and should be filled out in MISP plugin settings, each field separated by COMMAS. Fields that do not match with any type known in MISP or are not MISP attribute fields should be ignored in import, using a space or simply nothing between two separators (example: 'ip-src, , comment, ').\n\nIf the csv file already contains a header that does not start by a '#', you should tick the checkbox 'has_header' to avoid importing it and have potential issues. You can also redefine the header even if it is already contained in the file, by following the rules for headers explained earlier. One reason why you would redefine a header is for instance when you want to skip some fields, or some fields are not valid types.",
15
+ 'references': ['https://tools.ietf.org/html/rfc4180', 'https://tools.ietf.org/html/rfc7111'],
16
+ 'input': 'CSV format file.',
17
+ 'output': 'MISP Event attributes',
18
+ 'logo': '',
19
+ }
20
+ moduleconfig = []
21
+ userConfig = {
22
+ 'header': {
23
+ 'type': 'String',
24
+ 'message': 'Define the header of the csv file, with types (included in MISP attribute types or attribute fields) separated by commas.\nFor fields that do not match these types or that you want to skip, please use space or simply nothing between commas.\nFor instance: ip-src,domain, ,timestamp'},
25
+ 'has_header': {
26
+ 'type': 'Boolean',
27
+ 'message': 'Tick this box ONLY if there is a header line, NOT COMMENTED, and all the fields of this header are respecting the recommendations above.'},
28
+ 'special_delimiter': {
29
+ 'type': 'String',
30
+ 'message': 'IF THE DELIMITERS ARE NOT COMMAS, please specify which ones are used (for instance: ";", "|", "/", "\t" for tabs, etc).'
31
+ }
32
+ }
33
+ mispattributes = {'userConfig': userConfig, 'inputSource': ['file'], 'format': 'misp_standard'}
34
+
35
+ misp_standard_csv_header = ['uuid', 'event_id', 'category', 'type', 'value', 'comment', 'to_ids', 'date',
36
+ 'object_relation', 'attribute_tag', 'object_uuid', 'object_name', 'object_meta_category']
37
+ misp_context_additional_fields = ['event_info', 'event_member_org', 'event_source_org', 'event_distribution',
38
+ 'event_threat_level_id', 'event_analysis', 'event_date', 'event_tag']
39
+ misp_extended_csv_header = misp_standard_csv_header + misp_context_additional_fields
40
+
41
+
42
+ class CsvParser:
43
+ def __init__(self, header, has_header, delimiter, data, from_misp, MISPtypes, categories):
44
+ self.misp_event = MISPEvent()
45
+ self.header = header
46
+ self.has_header = has_header
47
+ self.delimiter = delimiter
48
+ self.data = data
49
+ self.from_misp = from_misp
50
+ self.MISPtypes = MISPtypes
51
+ self.categories = categories
52
+ self.fields_number = len(self.header)
53
+ self.__score_mapping = {0: self.__create_standard_attribute,
54
+ 1: self.__create_attribute_with_ids,
55
+ 2: self.__create_attribute_with_tags,
56
+ 3: self.__create_attribute_with_ids_and_tags,
57
+ 4: self.__create_attribute_check_category,
58
+ 5: self.__create_attribute_check_category_and_ids,
59
+ 6: self.__create_attribute_check_category_and_tags,
60
+ 7: self.__create_attribute_check_category_with_ids_and_tags}
61
+
62
+ def parse_csv(self):
63
+ if self.from_misp:
64
+ if self.header == misp_standard_csv_header:
65
+ self.__parse_misp_csv()
66
+ else:
67
+ attribute_fields = misp_standard_csv_header[:1] + misp_standard_csv_header[2:10]
68
+ object_fields = ['object_id'] + misp_standard_csv_header[10:]
69
+ attribute_indexes = []
70
+ object_indexes = []
71
+ for i in range(len(self.header)):
72
+ if self.header[i] in attribute_fields:
73
+ attribute_indexes.append(i)
74
+ elif self.header[i] in object_fields:
75
+ object_indexes.append(i)
76
+ if object_indexes:
77
+ if not any(field in self.header for field in ('object_uuid', 'object_id')) or 'object_name' not in self.header:
78
+ for line in self.data:
79
+ for index in object_indexes:
80
+ if line[index].strip():
81
+ return {'error': 'It is not possible to import MISP objects from your csv file if you do not specify any object identifier and object name to separate each object from each other.'}
82
+ if 'object_relation' not in self.header:
83
+ return {'error': 'In order to import MISP objects, an object relation for each attribute contained in an object is required.'}
84
+ self.__build_misp_event(attribute_indexes, object_indexes)
85
+ else:
86
+ attribute_fields = misp_standard_csv_header[:1] + misp_standard_csv_header[2:9]
87
+ attribute_indexes = []
88
+ types_indexes = []
89
+ for i in range(len(self.header)):
90
+ if self.header[i] in attribute_fields:
91
+ attribute_indexes.append(i)
92
+ elif self.header[i] in self.MISPtypes:
93
+ types_indexes.append(i)
94
+ self.__parse_external_csv(attribute_indexes, types_indexes)
95
+ self.__finalize_results()
96
+ return {'success': 1}
97
+
98
+ ################################################################################
99
+ # Parsing csv data with MISP fields, #
100
+ # but a custom header #
101
+ ################################################################################
102
+
103
+ def __build_misp_event(self, attribute_indexes, object_indexes):
104
+ score = self.__get_score()
105
+ if object_indexes:
106
+ objects = {}
107
+ id_name = 'object_id' if 'object_id' in self.header else 'object_uuid'
108
+ object_id_index = self.header.index(id_name)
109
+ name_index = self.header.index('object_name')
110
+ for line in self.data:
111
+ attribute = self.__score_mapping[score](line, attribute_indexes)
112
+ object_id = line[object_id_index]
113
+ if object_id:
114
+ if object_id not in objects:
115
+ misp_object = MISPObject(line[name_index])
116
+ if id_name == 'object_uuid':
117
+ misp_object.uuid = object_id
118
+ objects[object_id] = misp_object
119
+ objects[object_id].add_attribute(**attribute)
120
+ else:
121
+ self.event.add_attribute(**attribute)
122
+ for misp_object in objects.values():
123
+ self.misp_event.add_object(**misp_object)
124
+ else:
125
+ for line in self.data:
126
+ attribute = self.__score_mapping[score](line, attribute_indexes)
127
+ self.misp_event.add_attribute(**attribute)
128
+
129
+ ################################################################################
130
+ # Parsing csv data containing fields that are not #
131
+ # MISP attributes or objects standard fields #
132
+ # (but should be MISP attribute types!!) #
133
+ ################################################################################
134
+
135
+ def __parse_external_csv(self, attribute_indexes, types_indexes):
136
+ score = self.__get_score()
137
+ if attribute_indexes:
138
+ for line in self.data:
139
+ try:
140
+ base_attribute = self.__score_mapping[score](line, attribute_indexes)
141
+ except IndexError:
142
+ continue
143
+ for index in types_indexes:
144
+ attribute = {'type': self.header[index], 'value': line[index]}
145
+ attribute.update(base_attribute)
146
+ self.misp_event.add_attribute(**attribute)
147
+ else:
148
+ for line in self.data:
149
+ for index in types_indexes:
150
+ self.misp_event.add_attribute(**{'type': self.header[index], 'value': line[index]})
151
+
152
+ ################################################################################
153
+ # Parsing standard MISP csv format #
154
+ ################################################################################
155
+
156
+ def __parse_misp_csv(self):
157
+ objects = {}
158
+ attribute_fields = self.header[:1] + self.header[2:8]
159
+ for line in self.data:
160
+ a_uuid, _, category, _type, value, comment, ids, timestamp, relation, tag, o_uuid, name, _ = line[:self.fields_number]
161
+ attribute = {t: v.strip('"') for t, v in zip(attribute_fields, (a_uuid, category, _type, value, comment, ids, timestamp))}
162
+ attribute['to_ids'] = True if attribute['to_ids'] == '1' else False
163
+ if tag:
164
+ attribute['Tag'] = [{'name': t.strip()} for t in tag.split(',')]
165
+ if relation:
166
+ if o_uuid not in objects:
167
+ objects[o_uuid] = MISPObject(name)
168
+ objects[o_uuid].add_attribute(relation, **attribute)
169
+ else:
170
+ self.misp_event.add_attribute(**attribute)
171
+ for uuid, misp_object in objects.items():
172
+ misp_object.uuid = uuid
173
+ self.misp_event.add_object(**misp_object)
174
+
175
+ ################################################################################
176
+ # Utility functions #
177
+ ################################################################################
178
+
179
+ def __create_attribute_check_category(self, line, indexes):
180
+ attribute = self.__create_standard_attribute(line, indexes)
181
+ self.__check_category(attribute)
182
+ return attribute
183
+
184
+ def __create_attribute_check_category_and_ids(self, line, indexes):
185
+ attribute = self.__create_attribute_with_ids(line, indexes)
186
+ self.__check_category(attribute)
187
+ return attribute
188
+
189
+ def __create_attribute_check_category_and_tags(self, line, indexes):
190
+ attribute = self.__create_attribute_with_tags(line, indexes)
191
+ self.__check_category(attribute)
192
+ return attribute
193
+
194
+ def __create_attribute_check_category_with_ids_and_tags(self, line, indexes):
195
+ attribute = self.__create_attribute_with_ids_and_tags(line, indexes)
196
+ self.__check_category(attribute)
197
+ return attribute
198
+
199
+ def __create_attribute_with_ids(self, line, indexes):
200
+ attribute = self.__create_standard_attribute(line, indexes)
201
+ self.__deal_with_ids(attribute)
202
+ return attribute
203
+
204
+ def __create_attribute_with_ids_and_tags(self, line, indexes):
205
+ attribute = self.__create_standard_attribute(line, indexes)
206
+ self.__deal_with_ids(attribute)
207
+ self.__deal_with_tags(attribute)
208
+ return attribute
209
+
210
+ def __create_attribute_with_tags(self, line, indexes):
211
+ attribute = self.__create_standard_attribute(line, indexes)
212
+ self.__deal_with_tags(attribute)
213
+ return attribute
214
+
215
+ def __create_standard_attribute(self, line, indexes):
216
+ return {self.header[index]: line[index] for index in indexes if line[index]}
217
+
218
+ def __check_category(self, attribute):
219
+ category = attribute['category']
220
+ if category in self.categories:
221
+ return
222
+ if category.capitalize() in self.categories:
223
+ attribute['category'] = category.capitalize()
224
+ return
225
+ del attribute['category']
226
+
227
+ @staticmethod
228
+ def __deal_with_ids(attribute):
229
+ attribute['to_ids'] = True if attribute['to_ids'] == '1' else False
230
+
231
+ @staticmethod
232
+ def __deal_with_tags(attribute):
233
+ if 'Tag' in attribute.keys():
234
+ attribute['Tag'] = [{'name': tag.strip()} for tag in attribute['Tag'].split(',')]
235
+
236
+ def __get_score(self):
237
+ score = 1 if 'to_ids' in self.header else 0
238
+ if 'attribute_tag' in self.header:
239
+ score += 2
240
+ if 'category' in self.header:
241
+ score += 4
242
+ return score
243
+
244
+ def __finalize_results(self):
245
+ event = self.misp_event.to_dict()
246
+ self.results = {key: event[key] for key in ('Attribute', 'Object') if (key in event and event[key])}
247
+
248
+
249
+ def __any_mandatory_misp_field(header):
250
+ return any(field in header for field in ('type', 'value'))
251
+
252
+
253
+ def __special_parsing(data, delimiter):
254
+ return list(tuple(part.strip() for part in line[0].split(delimiter)) for line in csv.reader(io.TextIOWrapper(io.BytesIO(data.encode()), encoding='utf-8')) if line and not line[0].startswith('#'))
255
+
256
+
257
+ def __standard_parsing(data):
258
+ return list(tuple(part.strip() for part in line) for line in csv.reader(io.TextIOWrapper(io.BytesIO(data.encode()), encoding='utf-8')) if line and not line[0].startswith('#'))
259
+
260
+
261
+ def dict_handler(request: dict):
262
+ if request.get('data'):
263
+ try:
264
+ data = base64.b64decode(request['data']).decode('utf-8')
265
+ except UnicodeDecodeError:
266
+ misperrors['error'] = "Input is not valid UTF-8"
267
+ return misperrors
268
+ else:
269
+ misperrors['error'] = "Unsupported attributes type"
270
+ return misperrors
271
+ has_header = request['config'].get('has_header')
272
+ has_header = True if has_header == '1' else False
273
+ header = request['config']['header'].split(',') if request['config'].get('header').strip() else []
274
+ delimiter = request['config']['special_delimiter'] if request['config'].get('special_delimiter').strip() else ','
275
+ data = __standard_parsing(data) if delimiter == ',' else __special_parsing(data, delimiter)
276
+ if not header:
277
+ if has_header:
278
+ header = data.pop(0)
279
+ else:
280
+ misperrors['error'] = "Configuration error. Provide a header or use the one within the csv file and tick the checkbox 'Has_header'."
281
+ return misperrors
282
+ else:
283
+ header = [h.strip() for h in header]
284
+ if has_header:
285
+ del data[0]
286
+ if header == misp_standard_csv_header or header == misp_extended_csv_header:
287
+ header = misp_standard_csv_header
288
+
289
+ description = MISPEvent().describe_types
290
+ misp_types = description['types']
291
+ for h in header:
292
+ if not any((h in misp_types, h in misp_extended_csv_header, h in ('', ' ', '_', 'object_id'))):
293
+ misperrors['error'] = 'Wrong header field: {}. Please use a header value that can be recognized by MISP (or alternatively skip it using a whitespace).'.format(h)
294
+ return misperrors
295
+ from_misp = all((h in misp_extended_csv_header or h in ('', ' ', '_', 'object_id') for h in header))
296
+ if from_misp:
297
+ if not __any_mandatory_misp_field(header):
298
+ misperrors['error'] = 'Please make sure the data you try to import can be identified with a type/value combinaison.'
299
+ return misperrors
300
+ else:
301
+ if __any_mandatory_misp_field(header):
302
+ wrong_types = tuple(wrong_type for wrong_type in ('type', 'value') if wrong_type in header)
303
+ misperrors['error'] = 'Error with the following header: {}. It contains the following field(s): {}, which is(are) already provided by the usage of at least on MISP attribute type in the header.'.format(header, 'and'.join(wrong_types))
304
+ return misperrors
305
+ csv_parser = CsvParser(header, has_header, delimiter, data, from_misp, misp_types, description['categories'])
306
+ # build the attributes
307
+ result = csv_parser.parse_csv()
308
+ if 'error' in result:
309
+ return result
310
+ return {'results': csv_parser.results}
311
+
312
+
313
+ def introspection():
314
+ return mispattributes
315
+
316
+
317
+ def version():
318
+ moduleinfo['config'] = moduleconfig
319
+ return moduleinfo