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,544 @@
1
+ import json
2
+ import logging
3
+ import requests
4
+ from requests.exceptions import (
5
+ HTTPError,
6
+ ProxyError,
7
+ InvalidURL,
8
+ ConnectTimeout,
9
+ ConnectionError,
10
+ )
11
+ from typing import Optional, List, Tuple, Dict
12
+ from . import check_input_attribute, checking_error, standard_error_message
13
+ import platform
14
+ import os
15
+ from urllib.parse import quote, urlparse
16
+ from pymisp import MISPAttribute, MISPEvent, MISPTag, MISPObject
17
+
18
+ moduleinfo = {
19
+ 'version': '2.0.0',
20
+ 'author': 'Recorded Future',
21
+ 'description': 'Module to enrich attributes with threat intelligence from Recorded Future.',
22
+ 'module-type': ['expansion', 'hover'],
23
+ 'name': 'Recorded Future Enrich',
24
+ 'logo': 'recordedfuture.png',
25
+ 'requirements': ['A Recorded Future API token.'],
26
+ 'features': "Enrich an attribute to add a custom enrichment object to the event. The object contains a copy of the enriched attribute with added tags presenting risk score and triggered risk rules from Recorded Future. Malware and Threat Actors related to the enriched indicator in Recorded Future is matched against MISP's galaxy clusters and applied as galaxy tags. The custom enrichment object also includes a list of related indicators from Recorded Future (IP's, domains, hashes, URL's and vulnerabilities) added as additional attributes.",
27
+ 'references': ['https://www.recordedfuture.com/'],
28
+ 'input': 'A MISP attribute of one of the following types: ip, ip-src, ip-dst, domain, hostname, md5, sha1, sha256, uri, url, vulnerability, weakness.',
29
+ 'output': 'A MISP object containing a copy of the enriched attribute with added tags from Recorded Future and a list of new attributes related to the enriched attribute.',
30
+ }
31
+
32
+ moduleconfig = ["token", "proxy_host", "proxy_port", "proxy_username", "proxy_password"]
33
+
34
+ misperrors = {"error": "Error"}
35
+
36
+ GALAXY_FILE_PATH = "https://raw.githubusercontent.com/MISP/misp-galaxy/main/clusters/"
37
+
38
+ ATTRIBUTESTYPES = [
39
+ "ip",
40
+ "ip-src",
41
+ "ip-dst",
42
+ "ip-src|port",
43
+ "ip-dst|port",
44
+ "domain",
45
+ "hostname",
46
+ "md5",
47
+ "sha1",
48
+ "sha256",
49
+ "uri",
50
+ "url",
51
+ "vulnerability",
52
+ "weakness",
53
+ ]
54
+
55
+ OUTPUTATTRIBUTESTYPES = ATTRIBUTESTYPES + [
56
+ "email-src",
57
+ "malware-sample",
58
+ "text",
59
+ "target-org",
60
+ "threat-actor",
61
+ "target-user",
62
+ ]
63
+
64
+ mispattributes = {
65
+ "input": ATTRIBUTESTYPES,
66
+ "output": OUTPUTATTRIBUTESTYPES,
67
+ "format": "misp_standard",
68
+ }
69
+
70
+ LOGGER = logging.getLogger("recorded_future")
71
+ LOGGER.setLevel(logging.INFO)
72
+
73
+
74
+ class RequestHandler:
75
+ """A class for handling any outbound requests from this module."""
76
+
77
+ def __init__(self):
78
+ self.session = requests.Session()
79
+ self.app_id = (
80
+ f'{os.path.basename(__file__)}/{moduleinfo["version"]} ({platform.platform()}) '
81
+ f'misp_enrichment/{moduleinfo["version"]} python-requests/{requests.__version__}'
82
+ )
83
+ self.proxies = None
84
+ self.rf_token = None
85
+
86
+ def get(self, url: str, headers: dict = None) -> requests.Response:
87
+ """General get method with proxy error handling."""
88
+ try:
89
+ timeout = 7 if self.proxies else None
90
+ response = self.session.get(
91
+ url, headers=headers, proxies=self.proxies, timeout=timeout
92
+ )
93
+ response.raise_for_status()
94
+ return response
95
+ except (ConnectTimeout, ProxyError, InvalidURL) as error:
96
+ msg = "Error connecting with proxy, please check the Recorded Future app proxy settings."
97
+ LOGGER.error(f"{msg} Error: {error}")
98
+ misperrors["error"] = msg
99
+ raise
100
+
101
+ def rf_lookup(self, category: str, ioc: str) -> requests.Response:
102
+ """Do a lookup call using Recorded Future's ConnectAPI."""
103
+ parsed_ioc = quote(ioc, safe="")
104
+ url = f"https://api.recordedfuture.com/gw/misp/lookup/{category}/{parsed_ioc}"
105
+ headers = {"X-RFToken": self.rf_token, "User-Agent": self.app_id}
106
+ try:
107
+ response = self.get(url, headers)
108
+ except HTTPError as error:
109
+ msg = f"Error when requesting data from Recorded Future. {error.response}: {error.response.reason}"
110
+ LOGGER.error(msg)
111
+ misperrors["error"] = msg
112
+ raise
113
+ return response
114
+
115
+
116
+ GLOBAL_REQUEST_HANDLER = RequestHandler()
117
+
118
+
119
+ class GalaxyFinder:
120
+ """A class for finding MISP galaxy matches to Recorded Future data."""
121
+
122
+ def __init__(self):
123
+ self.session = requests.Session()
124
+ # There are duplicates values for different keys because Links entities and Related entities
125
+ # have have different naming for the same types
126
+ self.sources = {
127
+ "RelatedThreatActor": [f"{GALAXY_FILE_PATH}threat-actor.json"],
128
+ "Threat Actor": [f"{GALAXY_FILE_PATH}threat-actor.json"],
129
+ "RelatedMalware": [
130
+ f"{GALAXY_FILE_PATH}banker.json",
131
+ f"{GALAXY_FILE_PATH}botnet.json",
132
+ f"{GALAXY_FILE_PATH}exploit-kit.json",
133
+ f"{GALAXY_FILE_PATH}rat.json",
134
+ f"{GALAXY_FILE_PATH}ransomware.json",
135
+ f"{GALAXY_FILE_PATH}malpedia.json",
136
+ ],
137
+ "Malware": [
138
+ f"{GALAXY_FILE_PATH}banker.json",
139
+ f"{GALAXY_FILE_PATH}botnet.json",
140
+ f"{GALAXY_FILE_PATH}exploit-kit.json",
141
+ f"{GALAXY_FILE_PATH}rat.json",
142
+ f"{GALAXY_FILE_PATH}ransomware.json",
143
+ f"{GALAXY_FILE_PATH}malpedia.json",
144
+ ],
145
+ "MitreAttackIdentifier": [
146
+ f"{GALAXY_FILE_PATH}mitre-attack-pattern.json",
147
+ f"{GALAXY_FILE_PATH}mitre-course-of-action.json",
148
+ f"{GALAXY_FILE_PATH}mitre-enterprise-attack-attack-pattern.json",
149
+ f"{GALAXY_FILE_PATH}mitre-enterprise-attack-course-of-action.json",
150
+ f"{GALAXY_FILE_PATH}mitre-enterprise-attack-intrusion-set.json",
151
+ f"{GALAXY_FILE_PATH}mitre-enterprise-attack-malware.json",
152
+ f"{GALAXY_FILE_PATH}mitre-enterprise-attack-tool.json",
153
+ f"{GALAXY_FILE_PATH}mitre-intrusion-set.json",
154
+ f"{GALAXY_FILE_PATH}mitre-malware.json",
155
+ f"{GALAXY_FILE_PATH}mitre-mobile-attack-attack-pattern.json",
156
+ f"{GALAXY_FILE_PATH}mitre-mobile-attack-course-of-action.json",
157
+ f"{GALAXY_FILE_PATH}mitre-mobile-attack-intrusion-set.json",
158
+ f"{GALAXY_FILE_PATH}mitre-mobile-attack-malware.json",
159
+ f"{GALAXY_FILE_PATH}mitre-mobile-attack-tool.json",
160
+ f"{GALAXY_FILE_PATH}mitre-pre-attack-attack-pattern.json",
161
+ f"{GALAXY_FILE_PATH}mitre-pre-attack-intrusion-set.json",
162
+ f"{GALAXY_FILE_PATH}mitre-tool.json",
163
+ ],
164
+ }
165
+ self.galaxy_clusters = {}
166
+
167
+ def pull_galaxy_cluster(self, related_type: str) -> None:
168
+ """Fetches galaxy clusters for the related_type from the remote json files specified as self.sources."""
169
+ # Only fetch clusters if not fetched previously
170
+ if not self.galaxy_clusters.get(related_type):
171
+ for source in self.sources.get(related_type):
172
+ try:
173
+ response = GLOBAL_REQUEST_HANDLER.get(source)
174
+ name = source.split("/")[-1].split(".")[0]
175
+ self.galaxy_clusters.setdefault(related_type, {}).update(
176
+ {name: response.json()}
177
+ )
178
+ except ConnectionError as error:
179
+ LOGGER.warning(
180
+ f"pull_galaxy_cluster failed for source: {source}, with error: {error}."
181
+ )
182
+
183
+ def find_galaxy_match(self, indicator: str, related_type: str) -> str:
184
+ """Searches the clusters of the related_type for a match with the indicator.
185
+ :returns the first matching galaxy string or an empty string if no galaxy match is found.
186
+ """
187
+ self.pull_galaxy_cluster(related_type)
188
+ for cluster_name, cluster in self.galaxy_clusters.get(related_type, {}).items():
189
+ for value in cluster["values"]:
190
+ if indicator in value.get("meta", {}).get(
191
+ "synonyms", ""
192
+ ) or indicator in value.get("value", ""):
193
+ value = value["value"]
194
+ return f'misp-galaxy:{cluster_name}="{value}"'
195
+ return ""
196
+
197
+
198
+ class RFColors:
199
+ """Class for setting signature RF-colors."""
200
+
201
+ def __init__(self):
202
+ self.rf_white = "#CCCCCC"
203
+ self.rf_grey = " #CDCDCD"
204
+ self.rf_yellow = "#FFCF00"
205
+ self.rf_red = "#D10028"
206
+
207
+ def riskscore_color(self, risk_score: int) -> str:
208
+ """Returns appropriate hex-colors according to risk score."""
209
+ risk_score = int(risk_score)
210
+ if risk_score < 25:
211
+ return self.rf_white
212
+ elif risk_score < 65:
213
+ return self.rf_yellow
214
+ else:
215
+ return self.rf_red
216
+
217
+ def riskrule_color(self, risk_rule_criticality: int) -> str:
218
+ """Returns appropriate hex-colors according to risk rule criticality."""
219
+ risk_rule_criticality = int(risk_rule_criticality)
220
+ if risk_rule_criticality == 1:
221
+ return self.rf_white
222
+ elif risk_rule_criticality == 2:
223
+ return self.rf_yellow
224
+ else: # risk_rule_criticality == 3 or 4
225
+ return self.rf_red
226
+
227
+ def criticality_color(self, criticality) -> str:
228
+ mapper = {
229
+ "None": self.rf_grey,
230
+ "Low": self.rf_grey,
231
+ "Unusual": self.rf_grey,
232
+ "Informational": self.rf_grey,
233
+ "Medium": self.rf_yellow,
234
+ "Suspicious": self.rf_yellow,
235
+ "High": self.rf_red,
236
+ "Critical": self.rf_red,
237
+ "Very Critical": self.rf_red,
238
+ "Malicious": self.rf_red,
239
+ "Very Malicious": self.rf_red,
240
+ }
241
+ return mapper.get(criticality, self.rf_white)
242
+
243
+
244
+ class RFEnricher:
245
+ """Class for enriching an attribute with data from Recorded Future.
246
+ The enrichment data is returned as a custom MISP object.
247
+ """
248
+
249
+ def __init__(self, attribute_props: dict):
250
+ self.event = MISPEvent()
251
+ self.enrichment_object = MISPObject("Recorded Future Enrichment")
252
+ self.enrichment_object.template_uuid = "cbe0ffda-75e5-4c49-833f-093f057652ba"
253
+ self.enrichment_object.template_id = "1"
254
+ self.enrichment_object.description = "Recorded Future Enrichment"
255
+ setattr(self.enrichment_object, 'meta-category', 'network')
256
+ description = (
257
+ "An object containing the enriched attribute and "
258
+ "related entities from Recorded Future."
259
+ )
260
+ self.enrichment_object.from_dict(
261
+ **{"meta-category": "misc", "description": description, "distribution": 0}
262
+ )
263
+
264
+ # Create a copy of enriched attribute to add tags to
265
+ temp_attr = MISPAttribute()
266
+ temp_attr.from_dict(**attribute_props)
267
+ self.enriched_attribute = MISPAttribute()
268
+ self.enriched_attribute.from_dict(
269
+ **{"value": temp_attr.value, "type": temp_attr.type, "distribution": 0}
270
+ )
271
+
272
+ self.related_attributes: List[Tuple[str, MISPAttribute]] = []
273
+ self.color_picker = RFColors()
274
+ self.galaxy_finder = GalaxyFinder()
275
+
276
+ # Mapping from MISP-type to RF-type
277
+ self.type_to_rf_category = {
278
+ "ip": "ip",
279
+ "ip-src": "ip",
280
+ "ip-dst": "ip",
281
+ "ip-src|port": "ip",
282
+ "ip-dst|port": "ip",
283
+ "domain": "domain",
284
+ "hostname": "domain",
285
+ "md5": "hash",
286
+ "sha1": "hash",
287
+ "sha256": "hash",
288
+ "uri": "url",
289
+ "url": "url",
290
+ "vulnerability": "vulnerability",
291
+ "weakness": "vulnerability",
292
+ }
293
+
294
+ # Related entities have 'Related' as part of the word and Links entities from RF
295
+ # portrayed as related attributes in MISP
296
+ self.related_attribute_types = [
297
+ "RelatedIpAddress",
298
+ "RelatedInternetDomainName",
299
+ "RelatedHash",
300
+ "RelatedEmailAddress",
301
+ "RelatedCyberVulnerability",
302
+ "IpAddress",
303
+ "InternetDomainName",
304
+ "Hash",
305
+ "EmailAddress",
306
+ "CyberVulnerability",
307
+ ]
308
+ # Related entities have 'Related' as part of the word and and Links entities from RF portrayed as tags in MISP
309
+ self.galaxy_tag_types = [
310
+ "RelatedMalware",
311
+ "RelatedThreatActor",
312
+ "Threat Actor",
313
+ "MitreAttackIdentifier",
314
+ "Malware",
315
+ ]
316
+
317
+ def enrich(self) -> None:
318
+ """Run the enrichment."""
319
+ category = self.type_to_rf_category.get(self.enriched_attribute.type, "")
320
+ enriched_attribute_value = self.enriched_attribute.value
321
+ # If enriched attribute has a port we need to remove that port
322
+ # since RF do not support enriching ip addresses with port
323
+ if self.enriched_attribute.type in ["ip-src|port", "ip-dst|port"]:
324
+ enriched_attribute_value = enriched_attribute_value.split("|")[0]
325
+ json_response = GLOBAL_REQUEST_HANDLER.rf_lookup(
326
+ category, enriched_attribute_value
327
+ )
328
+ response = json.loads(json_response.content)
329
+
330
+ try:
331
+ # Add risk score and risk rules as tags to the enriched attribute
332
+ risk_score = response["data"]["risk"]["score"]
333
+ hex_color = self.color_picker.riskscore_color(risk_score)
334
+ tag_name = f'recorded-future:risk-score="{risk_score}"'
335
+ self.add_tag(tag_name, hex_color)
336
+ risk_criticality = response["data"]["risk"]["criticalityLabel"]
337
+ hex_color = self.color_picker.criticality_color(risk_criticality)
338
+ tag_name = f'recorded-future:criticality="{risk_criticality}"'
339
+ self.add_tag(tag_name, hex_color)
340
+
341
+ for evidence in response["data"]["risk"]["evidenceDetails"]:
342
+ risk_rule = evidence["rule"]
343
+ criticality = evidence["criticality"]
344
+ hex_color = self.color_picker.riskrule_color(criticality)
345
+ tag_name = f'recorded-future:risk-rule="{risk_rule}"'
346
+ self.add_tag(tag_name, hex_color)
347
+
348
+ links_data = response["data"].get("links", {}).get("hits")
349
+ # Check if we have error in links response. If yes, then user do not have right module enabled in token
350
+ links_access_error = response["data"].get("links", {}).get("error")
351
+ galaxy_tags = []
352
+ if not links_access_error:
353
+ for hit in links_data:
354
+ for section in hit["sections"]:
355
+ for sec_list in section["lists"]:
356
+ entity_type = sec_list["type"]["name"]
357
+ for entity in sec_list["entities"]:
358
+ if entity_type in self.galaxy_tag_types:
359
+ galaxy = self.galaxy_finder.find_galaxy_match(
360
+ entity["name"], entity_type
361
+ )
362
+ if galaxy and galaxy not in galaxy_tags:
363
+ galaxy_tags.append(galaxy)
364
+ else:
365
+ self.add_attribute(entity["name"], entity_type)
366
+
367
+ else:
368
+ # Retrieve related entities
369
+ for related_entity in response["data"]["relatedEntities"]:
370
+ related_type = related_entity["type"]
371
+ if related_type in self.related_attribute_types:
372
+ # Related entities returned as additional attributes
373
+ for related in related_entity["entities"]:
374
+ # filter those entities that have count bigger than 4, to reduce noise
375
+ # because there can be a huge list of related entities
376
+ if int(related["count"]) > 4:
377
+ indicator = related["entity"]["name"]
378
+ self.add_attribute(indicator, related_type)
379
+ elif related_type in self.galaxy_tag_types:
380
+ # Related entities added as galaxy-tags to the enriched attribute
381
+ galaxy_tags = []
382
+ for related in related_entity["entities"]:
383
+ # filter those entities that have count bigger than 4, to reduce noise
384
+ # because there can be a huge list of related entities
385
+ if int(related["count"]) > 4:
386
+ indicator = related["entity"]["name"]
387
+ galaxy = self.galaxy_finder.find_galaxy_match(
388
+ indicator, related_type
389
+ )
390
+ # Handle deduplication of galaxy tags
391
+ if galaxy and galaxy not in galaxy_tags:
392
+ galaxy_tags.append(galaxy)
393
+ for galaxy in galaxy_tags:
394
+ self.add_tag(galaxy)
395
+
396
+ except KeyError:
397
+ misperrors["error"] = "Unexpected format in Recorded Future api response."
398
+ raise
399
+
400
+ def add_attribute(self, indicator: str, indicator_type: str) -> None:
401
+ """Helper method for adding an indicator to the attribute list."""
402
+ out_type = self.get_output_type(indicator_type, indicator)
403
+ attribute = MISPAttribute()
404
+ attribute.from_dict(**{"value": indicator, "type": out_type, "distribution": 0})
405
+ self.related_attributes.append((indicator_type, attribute))
406
+
407
+ def add_tag(self, tag_name: str, hex_color: str = None) -> None:
408
+ """Helper method for adding a tag to the enriched attribute."""
409
+ tag = MISPTag()
410
+ tag_properties = {"name": tag_name}
411
+ if hex_color:
412
+ tag_properties["colour"] = hex_color
413
+ tag.from_dict(**tag_properties)
414
+ self.enriched_attribute.add_tag(tag)
415
+
416
+ def get_output_type(self, related_type: str, indicator: str) -> str:
417
+ """Helper method for translating a Recorded Future related type to a MISP output type."""
418
+ output_type = "text"
419
+ if related_type in ["RelatedIpAddress", "IpAddress"]:
420
+ output_type = "ip-dst"
421
+ elif related_type in ["RelatedInternetDomainName", "InternetDomainName"]:
422
+ output_type = "domain"
423
+ elif related_type in ["RelatedHash", "Hash"]:
424
+ hash_len = len(indicator)
425
+ if hash_len == 64:
426
+ output_type = "sha256"
427
+ elif hash_len == 40:
428
+ output_type = "sha1"
429
+ elif hash_len == 32:
430
+ output_type = "md5"
431
+ elif related_type in ["RelatedEmailAddress", "EmailAddress"]:
432
+ output_type = "email-src"
433
+ elif related_type in ["RelatedCyberVulnerability", "CyberVulnerability"]:
434
+ signature = indicator.split("-")[0]
435
+ if signature == "CVE":
436
+ output_type = "vulnerability"
437
+ elif signature == "CWE":
438
+ output_type = "weakness"
439
+ elif related_type == "MalwareSignature":
440
+ output_type = "malware-sample"
441
+ elif related_type == "Organization":
442
+ output_type = "target-org"
443
+ elif related_type == "Username":
444
+ output_type = "target-user"
445
+ return output_type
446
+
447
+ def get_results(self) -> dict:
448
+ """Build and return the enrichment results."""
449
+ self.enrichment_object.add_attribute(
450
+ "Enriched attribute", **self.enriched_attribute
451
+ )
452
+ for related_type, attribute in self.related_attributes:
453
+ self.enrichment_object.add_attribute(related_type, **attribute)
454
+ self.event.add_object(**self.enrichment_object)
455
+ event = json.loads(self.event.to_json())
456
+ result = {key: event[key] for key in ["Object"] if key in event}
457
+ return {"results": result}
458
+
459
+
460
+ def get_proxy_settings(config: dict) -> Optional[Dict[str, str]]:
461
+ """Returns proxy settings in the requests format.
462
+ If no proxy settings are set, return None."""
463
+ proxies = None
464
+ host = config.get("proxy_host")
465
+ port = config.get("proxy_port")
466
+ username = config.get("proxy_username")
467
+ password = config.get("proxy_password")
468
+
469
+ if host:
470
+ if not port:
471
+ misperrors["error"] = (
472
+ "The recordedfuture_proxy_host config is set, "
473
+ "please also set the recordedfuture_proxy_port."
474
+ )
475
+ raise KeyError
476
+ parsed = urlparse(host)
477
+ if "http" in parsed.scheme:
478
+ scheme = "http"
479
+ else:
480
+ scheme = parsed.scheme
481
+ netloc = parsed.netloc
482
+ host = f"{netloc}:{port}"
483
+
484
+ if username:
485
+ if not password:
486
+ misperrors["error"] = (
487
+ "The recordedfuture_proxy_username config is set, "
488
+ "please also set the recordedfuture_proxy_password."
489
+ )
490
+ raise KeyError
491
+ auth = f"{username}:{password}"
492
+ host = auth + "@" + host
493
+
494
+ proxies = {"http": f"{scheme}://{host}", "https": f"{scheme}://{host}"}
495
+
496
+ LOGGER.info(f"Proxy settings: {proxies}")
497
+ return proxies
498
+
499
+
500
+ def handler(q=False):
501
+ """Handle enrichment."""
502
+ if q is False:
503
+ return False
504
+ request = json.loads(q)
505
+
506
+ config = request.get("config")
507
+ if config and config.get("token"):
508
+ GLOBAL_REQUEST_HANDLER.rf_token = config.get("token")
509
+ else:
510
+ misperrors["error"] = "Missing Recorded Future token."
511
+ return misperrors
512
+ if not request.get("attribute") or not check_input_attribute(
513
+ request["attribute"], requirements=("type", "value")
514
+ ):
515
+ return {"error": f"{standard_error_message}, {checking_error}."}
516
+ if request["attribute"]["type"] not in mispattributes["input"]:
517
+ return {"error": "Unsupported attribute type."}
518
+
519
+ try:
520
+ GLOBAL_REQUEST_HANDLER.proxies = get_proxy_settings(config)
521
+ except KeyError:
522
+ return misperrors
523
+
524
+ input_attribute = request.get("attribute")
525
+ rf_enricher = RFEnricher(input_attribute)
526
+
527
+ try:
528
+ rf_enricher.enrich()
529
+ except (HTTPError, ConnectTimeout, ProxyError, InvalidURL, KeyError):
530
+ return misperrors
531
+
532
+ return rf_enricher.get_results()
533
+
534
+
535
+ def introspection():
536
+ """Returns a dict of the supported attributes."""
537
+ return mispattributes
538
+
539
+
540
+ def version():
541
+ """Returns a dict with the version and the associated meta-data
542
+ including potential configurations required of the module."""
543
+ moduleinfo["config"] = moduleconfig
544
+ return moduleinfo
@@ -0,0 +1,77 @@
1
+ import json
2
+ from dns import reversename, resolver, exception
3
+
4
+ misperrors = {'error': 'Error'}
5
+ mispattributes = {'input': ['ip-src', 'ip-dst', 'domain|ip'], 'output': ['hostname']}
6
+
7
+ # possible module-types: 'expansion', 'hover' or both
8
+ moduleinfo = {
9
+ 'version': '0.1',
10
+ 'author': 'Andreas Muehlemann',
11
+ 'description': 'Simple Reverse DNS expansion service to resolve reverse DNS from MISP attributes.',
12
+ 'module-type': ['expansion', 'hover'],
13
+ 'name': 'Reverse DNS',
14
+ 'logo': '',
15
+ 'requirements': ['DNS python library'],
16
+ 'features': 'The module takes an IP address as input and tries to find the hostname this IP address is resolved into.\n\nThe address of the DNS resolver to use is also configurable, but if no configuration is set, we use the Google public DNS address (8.8.8.8).\n\nPlease note that composite MISP attributes containing IP addresses are supported as well.',
17
+ 'references': [],
18
+ 'input': 'An IP address attribute.',
19
+ 'output': 'Hostname attribute the input is resolved into.',
20
+ }
21
+
22
+ # config fields that your code expects from the site admin
23
+ moduleconfig = ['nameserver']
24
+
25
+
26
+ def handler(q=False):
27
+ if q is False:
28
+ return False
29
+ request = json.loads(q)
30
+ if request.get('ip-dst'):
31
+ toquery = request['ip-dst']
32
+ elif request.get('ip-src'):
33
+ toquery = request['ip-src']
34
+ elif request.get('domain|ip'):
35
+ toquery = request['domain|ip'].split('|')[1]
36
+ else:
37
+ return False
38
+
39
+ # reverse lookup for ip
40
+ revname = reversename.from_address(toquery)
41
+
42
+ r = resolver.Resolver()
43
+ r.timeout = 2
44
+ r.lifetime = 2
45
+
46
+ if request.get('config'):
47
+ if request['config'].get('nameserver'):
48
+ nameservers = []
49
+ nameservers.append(request['config'].get('nameserver'))
50
+ r.nameservers = nameservers
51
+ else:
52
+ r.nameservers = ['8.8.8.8']
53
+
54
+ try:
55
+ answer = r.resolve(revname, 'PTR')
56
+ except resolver.NXDOMAIN:
57
+ misperrors['error'] = "NXDOMAIN"
58
+ return misperrors
59
+ except exception.Timeout:
60
+ misperrors['error'] = "Timeout"
61
+ return misperrors
62
+ except Exception:
63
+ misperrors['error'] = "DNS resolving error"
64
+ return misperrors
65
+
66
+ r = {'results': [{'types': mispattributes['output'],
67
+ 'values':[str(answer[0])]}]}
68
+ return r
69
+
70
+
71
+ def introspection():
72
+ return mispattributes
73
+
74
+
75
+ def version():
76
+ moduleinfo['config'] = moduleconfig
77
+ return moduleinfo