├── .gitignore
├── LICENSE
├── README.md
├── analyze_by_file.py
├── analyze_by_hash.py
├── artwork
└── Figure_1.png
├── cluster_directory.py
├── generate-endpoint-scan-pdf-report
├── endpoint_analysis_pdf_report.css
├── generate_ep_scan.py
├── intezer-logo.png
└── report_template.html
├── generate-file-scan-pdf-report
├── generate_file_scan_pdf_report.py
├── intezer-logo.png
├── pdf-report-tempalte.html
└── pdf-report.css
├── get_latest_analysis.py
├── iocs-extraction-to-csv
└── iocs_extraction_to_csv.py
└── requirements.txt
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | *.egg-info/
24 | .installed.cfg
25 | *.egg
26 | MANIFEST
27 |
28 | # PyInstaller
29 | # Usually these files are written by a python script from a template
30 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
31 | *.manifest
32 | *.spec
33 |
34 | # Installer logs
35 | pip-log.txt
36 | pip-delete-this-directory.txt
37 |
38 | # Unit test / coverage reports
39 | htmlcov/
40 | .tox/
41 | .coverage
42 | .coverage.*
43 | .cache
44 | nosetests.xml
45 | coverage.xml
46 | *.cover
47 | .hypothesis/
48 | .pytest_cache/
49 |
50 | # Translations
51 | *.mo
52 | *.pot
53 |
54 | # Django stuff:
55 | *.log
56 | local_settings.py
57 | db.sqlite3
58 |
59 | # Flask stuff:
60 | instance/
61 | .webassets-cache
62 |
63 | # Scrapy stuff:
64 | .scrapy
65 |
66 | # Sphinx documentation
67 | docs/_build/
68 |
69 | # PyBuilder
70 | target/
71 |
72 | # Jupyter Notebook
73 | .ipynb_checkpoints
74 |
75 | # pyenv
76 | .python-version
77 |
78 | # celery beat schedule file
79 | celerybeat-schedule
80 |
81 | # SageMath parsed files
82 | *.sage.py
83 |
84 | # Environments
85 | .env
86 | .venv
87 | env/
88 | venv/
89 | ENV/
90 | env.bak/
91 | venv.bak/
92 |
93 | # Spyder project settings
94 | .spyderproject
95 | .spyproject
96 |
97 | # Rope project settings
98 | .ropeproject
99 |
100 | # mkdocs documentation
101 | /site
102 |
103 | # mypy
104 | .mypy_cache/
105 | .idea
106 |
107 | .DS_Store
--------------------------------------------------------------------------------
/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 | # Intezer Analyze Scripts
2 | Basic scripts of Intezer Analyze API 2.0
3 |
4 | Currently the following scripts are available:
5 |
6 | - [Analyze by file](analyze_by_file.py)
7 | - [Analyze by hash](analyze_by_hash.py): Supports SHA256, SHA1 and MD5
8 | - [Get Latest Analysis](get_latest_analysis.py): Gets the latest analysis for the give hash available for your account
9 | - [Cluster Directory](cluster_directory.py): Create a graph based on code reuse between all the files in a specific directory. The script export a Gephi file as shown in this [recorded webinar](https://www.youtube.com/watch?v=ZD6O0QT8AG4)
10 |
11 |
12 | More information on how to obtain API access to could be found in our [blog post](https://www.intezer.com/blog-api-intezer-analyze-community/)
13 |
--------------------------------------------------------------------------------
/analyze_by_file.py:
--------------------------------------------------------------------------------
1 | import pprint
2 | import sys
3 | import time
4 |
5 | import requests
6 |
7 | base_url = 'https://analyze.intezer.com/api/v2-0'
8 | api_key = 'YOUR API KEY'
9 |
10 |
11 | def main(file_path):
12 | response = requests.post(base_url + '/get-access-token', json={'api_key': api_key})
13 | response.raise_for_status()
14 | session = requests.session()
15 | session.headers['Authorization'] = session.headers['Authorization'] = 'Bearer %s' % response.json()['result']
16 |
17 | with open(file_path, 'rb') as file_to_upload:
18 | files = {'file': ('file_name', file_to_upload)}
19 | response = session.post(base_url + '/analyze', files=files)
20 | assert response.status_code == 201
21 |
22 | while response.status_code != 200:
23 | time.sleep(1)
24 | result_url = response.json()['result_url']
25 | response = session.get(base_url + result_url)
26 | response.raise_for_status()
27 |
28 | report = response.json()
29 | pprint.pprint(report)
30 |
31 |
32 | if __name__ == '__main__':
33 | main(sys.argv[1])
34 |
--------------------------------------------------------------------------------
/analyze_by_hash.py:
--------------------------------------------------------------------------------
1 | import pprint
2 | import sys
3 | import time
4 |
5 | import requests
6 |
7 | base_url = 'https://analyze.intezer.com/api/v2-0'
8 | api_key = 'YOUR API KEY'
9 |
10 |
11 | def main(hash_value):
12 | response = requests.post(base_url + '/get-access-token', json={'api_key': api_key})
13 | response.raise_for_status()
14 | session = requests.session()
15 | session.headers['Authorization'] = session.headers['Authorization'] = 'Bearer %s' % response.json()['result']
16 |
17 | data = {'hash': hash_value}
18 | response = session.post(base_url + '/analyze-by-hash', json=data)
19 | if response.status_code == 404:
20 | print('File not found')
21 | return
22 |
23 | assert response.status_code == 201
24 |
25 | while response.status_code != 200:
26 | time.sleep(1)
27 | result_url = response.json()['result_url']
28 | response = session.get(base_url + result_url)
29 | response.raise_for_status()
30 |
31 | report = response.json()
32 | pprint.pprint(report)
33 |
34 |
35 | if __name__ == '__main__':
36 | main(sys.argv[1])
37 |
--------------------------------------------------------------------------------
/artwork/Figure_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/intezer/analyze-scripts/505540d0a2bbea8a333ee2f6b45fc3cf81b414b6/artwork/Figure_1.png
--------------------------------------------------------------------------------
/cluster_directory.py:
--------------------------------------------------------------------------------
1 | import os
2 | import sys
3 |
4 | import networkx as nx
5 | import requests
6 | import networkx.readwrite.gexf as gexf
7 |
8 | BASE_URL = 'https://analyze.intezer.com/api/v2-0'
9 | API_KEY = 'YOUR API KEY'
10 |
11 |
12 | def get_session():
13 | response = requests.post(BASE_URL + '/get-access-token', json={'api_key': API_KEY})
14 | response.raise_for_status()
15 | session = requests.session()
16 | session.headers['Authorization'] = session.headers['Authorization'] = 'Bearer %s' % response.json()['result']
17 | return session
18 |
19 |
20 | def send_to_analysis(file_path, session):
21 | result_url = ''
22 | with open(file_path, 'rb') as file_to_upload:
23 | files = {'file': (os.path.basename(file_path), file_to_upload)}
24 | response = session.post(BASE_URL + '/analyze', files=files)
25 | if response.status_code == 201 or response.status_code == 200:
26 | result_url = response.json()['result_url']
27 | else:
28 | print('Analyzing of file named {0} failed with code: {1} message: {2} '.format(file_path,
29 | response.status_code,
30 | response.text))
31 | return result_url
32 |
33 |
34 | def analyze_directory(dir_path, session):
35 | result_urls = []
36 | results = []
37 | for path in os.listdir(dir_path):
38 | file_path = os.path.join(dir_path, path)
39 | if os.path.isfile(file_path):
40 | result_url = send_to_analysis(file_path, session)
41 | if result_url:
42 | result_urls.append((result_url, os.path.basename(path)))
43 |
44 | while result_urls:
45 | result_url, file_name = result_urls.pop()
46 | response = session.get(BASE_URL + result_url)
47 | response.raise_for_status()
48 | if response.status_code != 200:
49 | result_urls.append((result_url, file_name))
50 | else:
51 | report = response.json()['result']
52 | if report['verdict'] != 'not_supported':
53 | results.append((report['sha256'], report['analysis_id'], file_name))
54 |
55 | return results
56 |
57 |
58 | def send_to_related_samples(analysis_id, session):
59 | result_url = ''
60 | response = session.post(BASE_URL + '/analyses/{}/sub-analyses/root/get-account-related-samples'.format(analysis_id))
61 | if response.status_code != 201:
62 | print('Get related sampled for analysis ID: {0} failed with status code {1}'.format(analysis_id, response.status_code))
63 | else:
64 | result_url = response.json()['result_url']
65 | return result_url
66 |
67 |
68 | def get_related_samples(results, session):
69 | result_urls = []
70 | previous_samples = {}
71 | for sha256, analysis_id, file_name in results:
72 | result_url = send_to_related_samples(analysis_id, session)
73 | if result_url:
74 | result_urls.append((sha256, result_url))
75 |
76 | while result_urls:
77 | sha256, result_url = result_urls.pop()
78 | response = session.get(BASE_URL + result_url)
79 | response.raise_for_status()
80 | if response.status_code != 200:
81 | result_urls.append((sha256, result_url))
82 | else:
83 | previous_samples[sha256] = response.json()['result']['related_samples']
84 |
85 | return previous_samples
86 |
87 |
88 | def draw_graph(previous_samples):
89 | g = nx.Graph()
90 | g.add_nodes_from(previous_samples)
91 |
92 | for sha256, (related_samples) in previous_samples.items():
93 | for analysis in related_samples:
94 | if analysis['analysis']['sha256'] in previous_samples:
95 | g.add_edge(sha256, analysis['analysis']['sha256'], gene_count=analysis['reused_genes']['gene_count'])
96 |
97 | gexf.write_gexf(g, 'output.gexf')
98 | print('graph was saved as output.gexf')
99 |
100 |
101 | def main(dir_path):
102 | session = get_session()
103 | results = analyze_directory(dir_path, session)
104 | previous_samples = get_related_samples(results, session)
105 | draw_graph(previous_samples)
106 |
107 |
108 | if __name__ == '__main__':
109 | main(sys.argv[1])
110 |
--------------------------------------------------------------------------------
/generate-endpoint-scan-pdf-report/endpoint_analysis_pdf_report.css:
--------------------------------------------------------------------------------
1 | html {
2 | font-family: "Open Sans",sans-serif;
3 | font-size: 20px;
4 | line-height: 1.5;
5 | }
6 |
7 | h1 {
8 | font-size: 2.5rem;
9 | page: cover;
10 | string-set: heading-name content();
11 | margin-bottom: 0;
12 | }
13 |
14 | h2 {
15 | string-set: heading content();
16 | }
17 |
18 | h3, h4 {
19 | margin-top: 2rem;
20 | }
21 |
22 | h2 + h3, h3 + h4 {
23 | margin-top: inherit;
24 | }
25 |
26 | ul {
27 | page-break-inside: avoid;
28 | }
29 |
30 | a {
31 | background-color: transparent;
32 | color: #0969da;
33 | text-decoration: none;
34 | }
35 |
36 | a:active, a:hover {
37 | text-decoration: underline;
38 | }
39 |
40 | table {
41 | table-layout: fixed;
42 | width: 1400px;
43 | border-spacing: 0;
44 | border-collapse: collapse;
45 | overflow: auto;
46 | }
47 |
48 | table th, table td {
49 | padding: 0.5rem 1rem 0;
50 | word-wrap: break-word;
51 | text-align: left;
52 | padding: 6px 13px;
53 | border: 1px solid #d0d7de;
54 | }
55 |
56 | table tr {
57 | background-color: #ffffff;
58 | border-top: 1px solid #d0d7de;
59 | }
60 |
61 | table tr:nth-child(2n) {
62 | background-color: #f6f8fa;
63 | }
64 |
65 | .logo {
66 | display: block;
67 | margin-left: auto;
68 | margin-right: auto;
69 | width: 200px;
70 | }
71 |
72 | .small-cell {
73 | width: 125px;
74 | }
75 |
76 | .long-cell {
77 | width: 600px;
78 | }
79 |
80 | .field-name {
81 | width: 220px;
82 | }
--------------------------------------------------------------------------------
/generate-endpoint-scan-pdf-report/generate_ep_scan.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import base64
3 | import time
4 | import traceback
5 | from datetime import datetime
6 |
7 | import jinja2
8 | import pdfkit
9 | from intezer_sdk import api
10 | from intezer_sdk.endpoint_analysis import EndpointAnalysis
11 | from intezer_sdk import consts
12 |
13 |
14 | def scan_duration(scan_start: str, scan_end: str) -> str:
15 | date_format = consts.DEFAULT_DATE_FORMAT
16 | # Calculating the time the endpoint scan took
17 | start_date = datetime.strptime(scan_start, date_format)
18 | end_date = datetime.strptime(scan_end, date_format)
19 | # Setting the time format
20 | duration_in_seconds = int((end_date - start_date).total_seconds())
21 | hours = duration_in_seconds // 3600
22 | minutes = (duration_in_seconds % 3600) // 60
23 | seconds = duration_in_seconds % 60
24 |
25 | formatted_time = ''
26 | if hours > 0:
27 | formatted_time += f"{hours} hour{'s' if hours > 1 else ''},"
28 | if minutes > 0:
29 | formatted_time += f" {minutes} minute{'s' if minutes > 1 else ''} and "
30 |
31 | formatted_time += f"{seconds} second{'s' if seconds > 1 else ''}"
32 | return formatted_time
33 |
34 |
35 | def generate_report(
36 | endpoint_analysis: EndpointAnalysis,
37 | css_input: str,
38 | template_text: str,
39 | logo_base64: str,
40 | save_html_to_file: bool = False):
41 | all_sub_analyses = endpoint_analysis.get_sub_analyses()
42 | sub_analyses = [sub_analysis for sub_analysis in all_sub_analyses if sub_analysis.verdict == 'malicious']
43 |
44 | if not sub_analyses:
45 | sub_analyses = [sub_analysis for sub_analysis in all_sub_analyses if
46 | sub_analysis.verdict in ('suspicious', 'unknown')]
47 | sub_analyses.sort(key=lambda value: (value.verdict != 'suspicious', value.verdict))
48 | sub_analyses = sub_analyses[:100]
49 |
50 | family_info = []
51 | for analysis in sub_analyses:
52 | if analysis.verdict != 'malicious':
53 | continue
54 |
55 | if analysis.code_reuse:
56 | # Getting the malicious family name
57 | malware_families = []
58 | families = sorted(analysis.code_reuse.get('families', []),
59 | key=lambda family_: family_.get('reused_gene_count'), reverse=True)
60 |
61 | for family in families:
62 | if family.get('family_type') == 'malware':
63 | malware_families.append(family)
64 |
65 | if malware_families:
66 | family_info.append({
67 | 'family_name': malware_families[0].get('family_name'),
68 | 'family_id': malware_families[0].get('family_id')
69 | })
70 |
71 | # Basic info
72 | endpoint_analysis_metadata = endpoint_analysis.result()
73 | endpoint_analysis_metadata['status'] = endpoint_analysis.status.value
74 |
75 | endpoint_analysis_metadata['scan_duration'] = scan_duration(endpoint_analysis_metadata['scan_start_time'],
76 | endpoint_analysis_metadata['scan_end_time'])
77 |
78 | if endpoint_analysis_metadata['families']:
79 | endpoint_analysis_metadata['families'] = ', '.join(endpoint_analysis_metadata['families'])
80 |
81 | sub_analyses_original_names = {}
82 | for analysis in sub_analyses:
83 | sub_analysis_metadata = analysis.metadata
84 | if sub_analysis_metadata.get('original_filename'):
85 | sub_analyses_original_names[analysis.analysis_id] = sub_analysis_metadata['original_filename']
86 |
87 | report_template_data = {'sub_analyses': sub_analyses,
88 | 'sub_analyses_original_names': sub_analyses_original_names,
89 | 'family_info': family_info,
90 | 'endpoint_analysis_metadata': endpoint_analysis_metadata,
91 | 'sub_analyses_count': len(all_sub_analyses),
92 | 'logo_base64': logo_base64,
93 | 'css_input': css_input,
94 | 'now': time.strftime(consts.DEFAULT_DATE_FORMAT, time.gmtime()),
95 | 'analyze_base_url': 'https://analyze.intezer.com'}
96 |
97 | environment = jinja2.Environment(autoescape=True)
98 | template = environment.from_string(template_text)
99 |
100 | html = template.render(**report_template_data)
101 |
102 | analysis_id = endpoint_analysis.analysis_id
103 | if save_html_to_file:
104 | # Saving HTML file
105 | with open(f'{analysis_id}.html', 'w+') as f:
106 | f.write(html)
107 | print(f'Saved HTML report to {analysis_id}.html')
108 |
109 | # Generating PDF file
110 | pdfkit.from_string(html, f'{analysis_id}.pdf')
111 | print(f'Saved PDF report to {analysis_id}.pdf')
112 |
113 |
114 | def generate_reports(intezer_api_key, endpoint_analyses_ids):
115 | api.set_global_api(intezer_api_key)
116 |
117 | css_file_name = 'endpoint_analysis_pdf_report.css'
118 |
119 | with open(css_file_name, mode='r') as css_file:
120 | css_input = css_file.read()
121 |
122 | with open('report_template.html', 'r') as f:
123 | template_text = f.read()
124 |
125 | with open('intezer-logo.png', 'rb') as image_file:
126 | logo_base64 = base64.b64encode(image_file.read()).decode('utf-8')
127 | for endpoint_analysis_id in endpoint_analyses_ids:
128 | try:
129 | endpoint_analysis = EndpointAnalysis.from_analysis_id(endpoint_analysis_id)
130 | if not endpoint_analysis:
131 | print(f"Analysis for endpoint analysis ID: {endpoint_analysis_id} isn't available")
132 |
133 | generate_report(endpoint_analysis, css_input, template_text, logo_base64)
134 | except Exception:
135 | traceback.print_exc()
136 |
137 |
138 | if __name__ == '__main__':
139 | parser = argparse.ArgumentParser(description='Generate a PDF and HTML reports for a given Intezer endpoint scans')
140 | parser.add_argument('-k', '--api-key', help='Intezer API Key', required=True)
141 | parser.add_argument('-a', '--analysis-id', help='Endpoint Analysis IDs', required=True, nargs='+')
142 |
143 | args = parser.parse_args()
144 | generate_reports(args.api_key, args.analysis_id)
145 |
--------------------------------------------------------------------------------
/generate-endpoint-scan-pdf-report/intezer-logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/intezer/analyze-scripts/505540d0a2bbea8a333ee2f6b45fc3cf81b414b6/generate-endpoint-scan-pdf-report/intezer-logo.png
--------------------------------------------------------------------------------
/generate-endpoint-scan-pdf-report/report_template.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 | Intezer Endpoint Scan Report
13 | {% if endpoint_analysis_metadata.verdict == 'malicious' and endpoint_analysis_metadata.families %}
14 | {{endpoint_analysis_metadata.computer_name}} | Infected | {{endpoint_analysis_metadata.families}}
15 | {% elif endpoint_analysis_metadata.verdict == 'malicious' %}
16 | {{endpoint_analysis_metadata.computer_name}} | Infected
17 | {% else %}
18 | {{endpoint_analysis_metadata.computer_name}} | {{endpoint_analysis_metadata.verdict.replace('_', ' ') | title}}
19 | {% endif %}
20 |
21 | Endpoint Analysis Summary
22 |
23 |
24 |
25 | Analysis URL |
26 | {{endpoint_analysis_metadata.analysis_url}} |
27 |
28 |
29 | Hostname |
30 | {{endpoint_analysis_metadata.computer_name}} |
31 |
32 |
33 | Verdict |
34 | {{endpoint_analysis_metadata.verdict.replace('_', ' ') | title}} |
35 |
36 | {% if endpoint_analysis_metadata.families %}
37 |
38 | Family |
39 | {{endpoint_analysis_metadata.families}} |
40 |
41 | {% endif %}
42 |
43 | Scan status |
44 | {{endpoint_analysis_metadata.status.capitalize()}} |
45 |
46 |
47 | OS version |
48 | {% if endpoint_analysis_metadata.computer_os_version is defined %}
49 | {{endpoint_analysis_metadata.computer_os_version.replace('_', ' ').capitalize()}} |
50 | {% else %}
51 | N/A |
52 | {% endif %}
53 |
54 |
55 | Scanner version |
56 | {% if endpoint_analysis_metadata.scanner_version is defined %}
57 | {{endpoint_analysis_metadata.scanner_version}}
58 | {% else %}
59 | | N/A |
60 | {% endif %}
61 |
62 |
63 | Analyzed at |
64 | {{endpoint_analysis_metadata.analysis_time}} |
65 |
66 |
67 | Analysis time |
68 | {{endpoint_analysis_metadata.scan_duration}} |
69 |
70 |
71 | Report generated at |
72 | {{now}} |
73 |
74 |
75 |
76 | Top Loaded Modules
77 |
78 |
79 |
80 | File name |
81 | Verdict |
82 | {% if endpoint_analysis_metadata.verdict == 'malicious' and endpoint_analysis_metadata.families %}
83 | Family |
84 | {% endif %}
85 | Path |
86 | Process name |
87 | Command line |
88 |
89 |
90 |
91 | {% for analysis in sub_analyses %}
92 |
93 | {% if sub_analyses_original_names[analysis['analysis_id']] is defined %}
94 | {{sub_analyses_original_names[analysis.analysis_id]}} |
95 | {% else %}
96 | {{analysis.sha256}} |
97 | {% endif %}
98 | {{analysis.verdict.capitalize()}} |
99 | {% if loop.index0 < family_info|length and endpoint_analysis_metadata.families %}
100 | {{family_info[loop.index0]['family_name']}} |
101 | {% endif %}
102 | N/A |
103 | N/A |
104 | N/A |
105 |
106 | {% endfor %}
107 |
108 |
109 |
110 |
111 | Total {{sub_analyses_count}} modules,
112 |
View all >
113 |
114 |
115 |
116 |
--------------------------------------------------------------------------------
/generate-file-scan-pdf-report/generate_file_scan_pdf_report.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import base64
3 | import time
4 | import traceback
5 | from typing import List
6 |
7 | import jinja2
8 | import pdfkit
9 | from intezer_sdk import api
10 | from intezer_sdk.analysis import FileAnalysis, SubAnalysis
11 |
12 |
13 | def generate_report(
14 | sha256: str,
15 | analysis: FileAnalysis,
16 | css_input: str,
17 | template_text: str,
18 | logo_base64: str,
19 | save_html_to_file: bool = False):
20 |
21 | # Basic info
22 | analysis_result = analysis.result()
23 | root_analysis: SubAnalysis = analysis.get_root_analysis()
24 | family_info = api.get_global_api().get_family_info(
25 | analysis_result['family_id']) if 'family_id' in analysis_result else {}
26 |
27 | # Handling sub analyses
28 | sub_analyses: List[SubAnalysis] = analysis.get_sub_analyses()
29 |
30 | # Mapping between source and sub analyses for generating the report
31 | sub_analysis_by_source = {}
32 |
33 | for sub_analysis in sub_analyses:
34 | sub_analysis_info = sub_analysis.metadata
35 | sub_analysis_info['analysis_id'] = sub_analysis.analysis_id
36 |
37 | if sub_analysis.source == 'static_extraction':
38 | sub_analysis_by_source.setdefault(sub_analysis.source, []).append(sub_analysis_info)
39 | sub_analysis_info['path'] = sub_analysis.extraction_info['dropped_path']
40 | elif sub_analysis.source == 'dynamic_execution':
41 | sub_analysis_by_source.setdefault(sub_analysis.extraction_info['collected_from'], []).append(
42 | sub_analysis_info)
43 |
44 | if sub_analysis.extraction_info['collected_from'] == 'memory' and sub_analysis.extraction_info.get(
45 | 'processes'):
46 | sub_analysis_info['path'] = sub_analysis.extraction_info['processes'][0]['module_path']
47 | sub_analysis_info['process_id'] = sub_analysis.extraction_info['processes'][0]['process_id']
48 | sub_analysis_info['parent_process_id'] = sub_analysis.extraction_info['processes'][0][
49 | 'parent_process_id']
50 |
51 | elif sub_analysis.extraction_info['collected_from'] == 'file_system':
52 | sub_analysis_info['path'] = sub_analysis.extraction_info['dropped_path']
53 | else:
54 | raise Exception(f'Unexpected sub analysis source {sub_analysis.source}')
55 |
56 | # Handling TTPs
57 | ttps = []
58 | if analysis.dynamic_ttps:
59 | severity_map = {1: 'Low', 2: 'Medium', 3: 'High'}
60 | for ttp in sorted(analysis.dynamic_ttps, key=lambda ttp_: ttp_['severity'], reverse=True):
61 | ttp_info = {
62 | 'mitre': '-',
63 | 'technique': ttp['description'],
64 | 'severity': severity_map[ttp['severity']],
65 | 'details': '-'
66 | }
67 |
68 | ttps_text = [f'{list(item.keys())[0]}: {list(item.values())[0]}' for item in ttp['data']]
69 |
70 | if ttps_text:
71 | ttp_info['details'] = ', '.join(ttps_text)
72 |
73 | if 'ttp' in ttp:
74 | ttp_info['mitre'] = ttp['ttp']['ttp']
75 |
76 | ttps.append(ttp_info)
77 |
78 | # Arranging the data to send to template
79 | report_template_data = {
80 | 'now': time.strftime("%a, %d %b %Y %H:%M:%S %Z", time.gmtime()),
81 | 'analyze_base_url': 'https://analyze.intezer.com',
82 | 'logo_base64': logo_base64,
83 | 'indicators_text': ', '.join(ind.get('name') for ind in root_analysis.metadata.get('indicators', []))
84 | }
85 |
86 | report_template_data.update(analysis_result)
87 | report_template_data.update(root_analysis.metadata)
88 | report_template_data.update(family_info)
89 | report_template_data['sub_analyses'] = sub_analysis_by_source
90 | report_template_data['ttps'] = ttps
91 | report_template_data['file_iocs'] = analysis.iocs['files']
92 | report_template_data['network_iocs'] = analysis.iocs['network']
93 | report_template_data['css_input'] = css_input
94 |
95 | # Generating the HTML report
96 | environment = jinja2.Environment(autoescape=True)
97 | template = environment.from_string(template_text)
98 | html = template.render(**report_template_data)
99 |
100 | if save_html_to_file:
101 | # Saving HTML file
102 | with open(f'{sha256}.html', 'w+') as f:
103 | f.write(html)
104 | print(f'Saved HTML report to {sha256}.html')
105 |
106 | # Generating PDF file
107 | pdfkit.from_string(html, f'{sha256}.pdf')
108 | print(f'Saved PDF report to {sha256}.pdf')
109 |
110 |
111 | def generate_reports(intezer_apikey, files_sha256):
112 | api.set_global_api(intezer_apikey)
113 |
114 | css_file_name = 'pdf-report.css'
115 |
116 | with open(css_file_name, mode="r", encoding="utf-8") as css_file:
117 | css_input = css_file.read()
118 |
119 | with open('pdf-report-tempalte.html', 'r') as f:
120 | template_text = f.read()
121 |
122 | with open('intezer-logo.png', 'rb') as image_file:
123 | logo_base64 = base64.b64encode(image_file.read()).decode("utf-8")
124 |
125 | for sha256 in files_sha256:
126 | try:
127 | analysis = FileAnalysis.from_latest_hash_analysis(file_hash=sha256)
128 |
129 | if not analysis:
130 | print(f"Analysis for file hash {sha256} isn't available")
131 |
132 | generate_report(sha256, analysis, css_input, template_text, logo_base64)
133 | except Exception:
134 | traceback.print_exc()
135 |
136 |
137 | if __name__ == '__main__':
138 | parser = argparse.ArgumentParser(description="Generate a PDF and HTML reports for a given Intezer file scan")
139 | parser.add_argument("-k", "--apikey", help="Intezer API Key", required=True)
140 | parser.add_argument("-f", "--sha256", help="File hash", required=True)
141 |
142 | args = parser.parse_args()
143 | generate_reports(args.apikey, [args.sha256])
144 |
--------------------------------------------------------------------------------
/generate-file-scan-pdf-report/intezer-logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/intezer/analyze-scripts/505540d0a2bbea8a333ee2f6b45fc3cf81b414b6/generate-file-scan-pdf-report/intezer-logo.png
--------------------------------------------------------------------------------
/generate-file-scan-pdf-report/pdf-report-tempalte.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | {% if family_name %}
6 | {{verdict.replace('_', ' ').capitalize()}}, {{family_name}}, {{sha256}}
7 | {% else %}
8 | {{verdict.replace('_', ' ').capitalize()}}, {{sha256}}
9 | {% endif %}
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 | Intezer File Scan Report
18 |
19 | {% if family_name %}
20 | {{verdict.replace('_', ' ').capitalize()}}, {{family_name}}, {{sha256}}
21 | {% else %}
22 | {{verdict.replace('_', ' ').capitalize()}}, {{sha256}}
23 | {% endif %}
24 |
25 | Analysis Summary
26 |
27 |
28 |
29 | Analysis URL |
30 | {{analysis_url}} |
31 |
32 |
33 |
34 |
35 |
36 |
37 | SHA256 |
38 | {{sha256}} |
39 |
40 |
41 | MD5 |
42 | {{md5}} |
43 |
44 |
45 | SHA1 |
46 | {{sha1}} |
47 |
48 |
49 | Verdict |
50 | {{verdict.replace('_', ' ').capitalize()}} |
51 |
52 |
53 | Sub verdict |
54 | {{sub_verdict.replace('_', ' ').capitalize()}} |
55 |
56 | {% if family_id and verdict in ['malicious', 'suspicious'] %}
57 |
58 | Family |
59 | {{family_name}} |
60 |
61 |
62 | Threat description |
63 | {{description or 'N/A'}} |
64 |
65 | {% else %}
66 |
67 | Family |
68 | {{family_name or 'N/A'}} |
69 |
70 | {% endif %}
71 |
72 | File type |
73 | {{file_type.upper()}} |
74 |
75 |
76 | Indicators |
77 | {{indicators_text or 'N/A'}} |
78 |
79 |
80 | Analyzed at |
81 | {{analysis_time}} |
82 |
83 |
84 | Report generated at |
85 | {{now}} |
86 |
87 |
88 |
89 |
90 | Genetic Analysis
91 | Genetic Summary
92 | Original file
93 |
94 |
95 |
96 | SHA256 |
97 | Verdict |
98 | Family |
99 |
100 |
101 |
102 |
103 | {{sha256}} |
104 | {{verdict.replace('_', ' ').capitalize()}} |
105 | {{family_name or 'N/A'}} |
106 |
107 |
108 |
109 | {% if 'memory' in sub_analyses and sub_analyses['memory'] %}
110 | Memory modules
111 |
112 |
113 |
114 | SHA256 |
115 | Module path |
116 | PID |
117 | PPID |
118 |
119 |
120 |
121 | {% for sub_analysis in sub_analyses['memory'] %}
122 |
123 | {{sub_analysis.sha256}} |
124 | {{sub_analysis.path}} |
125 | {{sub_analysis.process_id}} |
126 | {{sub_analysis.parent_process_id}} |
127 |
128 | {% endfor %}
129 |
130 |
131 | {% endif %}
132 |
133 | {% if sub_analyses.get('file_system') %}
134 | Dropped files
135 |
136 |
137 |
138 | SHA256 |
139 | Path |
140 |
141 |
142 |
143 | {% for sub_analysis in sub_analyses['file_system'] %}
144 |
145 | {{sub_analysis.sha256}} |
146 | {{sub_analysis.path}} |
147 |
148 | {% endfor %}
149 |
150 |
151 | {% endif %}
152 |
153 | {% if sub_analyses.get('static_extraction') %}
154 | Static extraction
155 |
156 |
157 |
158 | SHA256 |
159 | Path |
160 |
161 |
162 |
163 | {% for sub_analysis in sub_analyses['static_extraction'] %}
164 |
165 | {{sub_analysis.sha256}} |
166 | {{sub_analysis.path}} |
167 |
168 | {% endfor %}
169 |
170 |
171 | {% endif %}
172 |
173 | {% if ttps %}
174 | TTPs
175 |
176 |
177 |
178 | MITRE ATT&CK |
179 | Technique |
180 | Severity |
181 | Details |
182 |
183 |
184 |
185 | {% for ttp in ttps %}
186 |
187 | {{ttp.mitre}} |
188 | {{ttp.technique}} |
189 | {{ttp.severity}} |
190 | {{ttp.details}} |
191 |
192 | {% endfor %}
193 |
194 |
195 | {% endif %}
196 |
197 | {% if verdict not in ['trusted', 'no_threats'] and (network_iocs or file_iocs) %}
198 | IOCs
199 |
200 | {% if network_iocs %}
201 | Network IOCs
202 |
203 |
204 |
205 | Type |
206 | IOC |
207 | Source type |
208 |
209 |
210 |
211 | {% for ioc in network_iocs %}
212 |
213 | {{ioc.type}} |
214 | {{ioc.ioc.replace('http', 'hxxp')}} |
215 | {{', '.join(ioc.source)}} |
216 |
217 | {% endfor %}
218 |
219 |
220 | {% endif %}
221 |
222 | {% if file_iocs %}
223 | File IOCs
224 |
225 |
226 |
227 | SHA256 |
228 | Path |
229 | Type |
230 | Classification |
231 |
232 |
233 |
234 | {% for ioc in file_iocs %}
235 |
236 | {{ioc.sha256}} |
237 | {{ioc.path}} |
238 | {{ioc.type.replace('_', ' ').capitalize()}} |
239 | {{ioc.verdict.replace('_', ' ').capitalize()}} {% if ioc.family %}, {{ioc.family}}{% endif %} |
240 |
241 | {% endfor %}
242 |
243 |
244 | {% endif %}
245 | {% endif %}
246 |
247 |
248 |
--------------------------------------------------------------------------------
/generate-file-scan-pdf-report/pdf-report.css:
--------------------------------------------------------------------------------
1 | html {
2 | font-family: "Open Sans",sans-serif;
3 | font-size: 20px;
4 | line-height: 1.5;
5 | }
6 |
7 | h1 {
8 | font-size: 2.5rem;
9 | page: cover;
10 | string-set: heading-name content();
11 | margin-bottom: 0;
12 | }
13 |
14 | h2 {
15 | string-set: heading content();
16 | }
17 |
18 | h3, h4 {
19 | margin-top: 2rem;
20 | }
21 |
22 | h2 + h3, h3 + h4 {
23 | margin-top: inherit;
24 | }
25 |
26 | ul {
27 | page-break-inside: avoid;
28 | }
29 |
30 | a {
31 | background-color: transparent;
32 | color: #0969da;
33 | text-decoration: none;
34 | }
35 |
36 | a:active, a:hover {
37 | text-decoration: underline;
38 | }
39 |
40 | table {
41 | table-layout: fixed;
42 | width: 1400px;
43 | border-spacing: 0;
44 | border-collapse: collapse;
45 | overflow: auto;
46 | }
47 |
48 | table th, table td {
49 | padding: 0.5rem 1rem 0;
50 | word-wrap: break-word;
51 | text-align: left;
52 | padding: 6px 13px;
53 | border: 1px solid #d0d7de;
54 | }
55 |
56 | table tr {
57 | background-color: #ffffff;
58 | border-top: 1px solid #d0d7de;
59 | }
60 |
61 | table tr:nth-child(2n) {
62 | background-color: #f6f8fa;
63 | }
64 |
65 | .logo {
66 | display: block;
67 | margin-left: auto;
68 | margin-right: auto;
69 | width: 200px;
70 | }
71 |
72 | .small-cell {
73 | width: 120px;
74 | }
75 |
76 | .long-cell {
77 | width: 600px;
78 | }
79 |
80 | .field-name {
81 | width: 220px;
82 | }
--------------------------------------------------------------------------------
/get_latest_analysis.py:
--------------------------------------------------------------------------------
1 | import pprint
2 | import sys
3 |
4 | import requests
5 |
6 | base_url = 'https://analyze.intezer.com/api/v2-0'
7 | api_key = 'YOUR API KEY'
8 |
9 |
10 | def main(hash_value):
11 | response = requests.post(base_url + '/get-access-token', json={'api_key': api_key})
12 | response.raise_for_status()
13 | session = requests.session()
14 | session.headers['Authorization'] = session.headers['Authorization'] = 'Bearer %s' % response.json()['result']
15 |
16 | response = session.get(base_url + '/files/{}'.format(hash_value))
17 | if response.status_code == 404:
18 | print('File not found')
19 | return
20 |
21 | response.raise_for_status()
22 |
23 | report = response.json()
24 | pprint.pprint(report)
25 |
26 |
27 | if __name__ == '__main__':
28 | main(sys.argv[1])
29 |
--------------------------------------------------------------------------------
/iocs-extraction-to-csv/iocs_extraction_to_csv.py:
--------------------------------------------------------------------------------
1 | from intezer_sdk import api
2 | from intezer_sdk.analysis import FileAnalysis
3 | import argparse
4 | import requests
5 | from intezer_sdk.analyses_history import query_file_analyses_history
6 | from datetime import datetime
7 | import csv
8 |
9 |
10 | def write_to_csv(data, filename):
11 | with open(filename, 'w', encoding='utf-8', errors='surrogateescape') as csvfile:
12 | fieldnames = ['Type', 'IOC', 'Verdict', 'Family', 'Analysis URL']
13 | writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
14 | writer.writeheader()
15 |
16 | rows = []
17 | for item in data:
18 | row = {
19 | 'Type': item['type'],
20 | 'IOC': item['ioc'] if item.get('source') is not None and 'file' not in item.get('source') else item[
21 | 'path'],
22 | 'Verdict': item['verdict'] if item.get('verdict') is not None else 'N/A',
23 | 'Family': item['family'] if item.get('family') is not None else 'N/A',
24 | 'Analysis URL': item['analysis_url']
25 | }
26 | rows.append(row)
27 |
28 | writer.writerows(rows)
29 | print(f'Saved CSV: {filename} to directory')
30 |
31 |
32 | def ioc_extraction(start_date: datetime, end_date: datetime):
33 | history_results = query_file_analyses_history(start_date=start_date, end_date=end_date, aggregated_view=True)
34 | files_ios_list = []
35 | for analysis in history_results:
36 | analysis = FileAnalysis.from_analysis_id(analysis['analysis_id'])
37 |
38 | url = analysis.result()['analysis_url']
39 | if analysis.iocs:
40 | if analysis.iocs['network']:
41 | files_ios_list.extend([
42 | {**ioc, 'analysis_url': url}
43 | for ioc in analysis.iocs['network']
44 | ])
45 |
46 | if analysis.iocs['files']:
47 | files_ios_list.extend([
48 | {**ioc, 'analysis_url': url}
49 | for ioc in analysis.iocs['files']
50 | ])
51 | if len(history_results) == 0:
52 | print('No data to show in the chosen timeframe')
53 | exit()
54 | files_ios_list = sorted(files_ios_list, key=lambda item: (item['type'], item['analysis_url']))
55 | filename = 'extracted_iocs.csv'
56 |
57 | write_to_csv(files_ios_list, filename)
58 |
59 |
60 | def date_conversion(intezer_api_key, start_date_str: str, end_date_str: str = None):
61 | api.set_global_api(intezer_api_key)
62 | try:
63 | # Convert the date string to a datetime object
64 | if end_date_str is None:
65 | end_date = datetime.now()
66 | else:
67 | end_date = datetime.fromisoformat(end_date_str)
68 | start_date = datetime.fromisoformat(start_date_str)
69 |
70 | ioc_extraction(start_date, end_date)
71 | except ValueError as error:
72 | print(f'ValueError: {error}')
73 | except requests.exceptions.HTTPError as error:
74 | print(f'HTTPError: {error}')
75 |
76 |
77 | if __name__ == '__main__':
78 | parser = argparse.ArgumentParser(description='Extracting IOCs of all Intezer analysis from a given '
79 | 'time frame or start date')
80 | parser.add_argument('-k', '--api-key', help='Intezer API Key', required=True)
81 | parser.add_argument('-s', '--start-date', help='History start date, YYYY-MM-DD', required=True)
82 | parser.add_argument('-e', '--end-date', help='History end date, YYYY-MM-DD, default: Today', required=False)
83 |
84 | args = parser.parse_args()
85 | date_conversion(args.api_key, args.start_date, args.end_date)
86 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | requests
2 | networkx
3 | matplotlib
--------------------------------------------------------------------------------