Skip to content

Commit e9a6c3e

Browse files
committed
fix: various lint fixes
1 parent f79f934 commit e9a6c3e

7 files changed

Lines changed: 40 additions & 16 deletions

File tree

mitreattack/attackToExcel/attackToExcel.py

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import argparse
44
import os
5-
from typing import Dict, List
5+
from typing import Dict, List, Optional
66

77
import pandas as pd
88
import requests
@@ -16,7 +16,7 @@
1616
SUB_CHARACTERS = ["\\", "/"]
1717

1818

19-
def get_stix_data(domain: str, version: str = None, remote: str = None, stix_file: str = None) -> MemoryStore:
19+
def get_stix_data(domain: str, version: Optional[str] = None, remote: Optional[str] = None, stix_file: Optional[str] = None) -> MemoryStore:
2020
"""Download the ATT&CK STIX data for the given domain and version from MITRE/CTI (or just domain if a remote workbench is specified).
2121
2222
Parameters
@@ -110,7 +110,7 @@ def build_dataframes(src: MemoryStore, domain: str) -> Dict:
110110
return df
111111

112112

113-
def write_excel(dataframes: Dict, domain: str, version: str = None, output_dir: str = ".") -> List:
113+
def write_excel(dataframes: Dict, domain: str, version: Optional[str] = None, output_dir: str = ".") -> List:
114114
"""Given a set of dataframes from build_dataframes, write the ATT&CK dataset to output directory.
115115
116116
Parameters
@@ -262,11 +262,11 @@ def write_excel(dataframes: Dict, domain: str, version: str = None, output_dir:
262262

263263
def export(
264264
domain: str = "enterprise-attack",
265-
version: str = None,
265+
version: Optional[str] = None,
266266
output_dir: str = ".",
267-
remote: str = None,
268-
stix_file: str = None,
269-
mem_store: MemoryStore = None,
267+
remote: Optional[str] = None,
268+
stix_file: Optional[str] = None,
269+
mem_store: Optional[MemoryStore] = None,
270270
):
271271
"""Download ATT&CK data from MITRE/CTI and convert it to Excel spreadsheets.
272272
@@ -298,6 +298,8 @@ def export(
298298
------
299299
TypeError
300300
Raised when missing exactly one of `remote`, `stix_file`, or `mem_store`.
301+
ValueError
302+
Raised when `mem_store` fails to load.
301303
"""
302304
if (
303305
(remote and stix_file and mem_store)
@@ -312,6 +314,9 @@ def export(
312314
if get_stix_from_github or remote or stix_file:
313315
mem_store = get_stix_data(domain=domain, version=version, remote=remote, stix_file=stix_file)
314316

317+
if mem_store is None:
318+
raise ValueError("`mem_store` is empty - this should not be possible!")
319+
315320
logger.info(f"************ Exporting {domain} to Excel ************")
316321

317322
# build dataframes

mitreattack/attackToExcel/stixToDf.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from mitreattack.constants import MITRE_ATTACK_ID_SOURCE_NAMES, PLATFORMS_LOOKUP
1515
from mitreattack.stix20 import MitreAttackData
1616

17+
1718
def remove_revoked_deprecated(stix_objects):
1819
"""Remove any revoked or deprecated objects from queries made to the data source."""
1920
# Note we use .get() because the property may not be present in the JSON data. The default is False
@@ -132,6 +133,8 @@ def techniquesToDf(src, domain):
132133
if subtechnique:
133134
subtechnique_of = all_sub_techniques.query([Filter("source_ref", "=", technique["id"])])[0]
134135
parent = src.get(subtechnique_of["target_ref"])
136+
else:
137+
parent = None
135138

136139
# base STIX properties
137140
row = parseBaseStix(technique)
@@ -164,7 +167,7 @@ def techniquesToDf(src, domain):
164167
# domain specific fields -- enterprise
165168
if domain == "enterprise-attack":
166169
row["is sub-technique"] = subtechnique
167-
if subtechnique:
170+
if subtechnique and parent is not None:
168171
row["name"] = f"{parent['name']}: {technique['name']}"
169172
row["sub-technique of"] = parent["external_references"][0]["external_id"]
170173

mitreattack/collections/collection_to_index.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -75,12 +75,12 @@ def generate_index(name, description, root_url, files=None, folders=None, sets=N
7575
)
7676
cleaned_bundles.append(potentially_valid_bundle)
7777
else:
78-
print(f"cannot use bundle {potentially_valid_bundle.id} due to lack of collection object")
78+
print(f"cannot use bundle {potentially_valid_bundle['id']} due to lack of collection object")
7979
else:
80-
print(f"cannot use bundle {potentially_valid_bundle.id} due to lack of collection object")
80+
print(f"cannot use bundle {potentially_valid_bundle['id']} due to lack of collection object")
8181

82-
index_created = None
83-
index_modified = None
82+
index_created = isoparse("9999-12-31T23:59:59.999Z")
83+
index_modified = isoparse("9999-12-31T23:59:59.999Z")
8484
collections = {} # STIX ID -> collection object
8585

8686
if files:

mitreattack/download_stix.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,11 @@ def download_stix(stix_version: str, domain: str, download_dir: str, release: st
2727
ATT&CK release to download.
2828
known_hash : str
2929
SHA256 hash of the ATT&CK release.
30+
31+
Raises
32+
------
33+
ValueError
34+
Raised if `stix_version` is not "2.0" or "2.1".
3035
"""
3136
release_download_dir = pathlib.Path(f"{download_dir}/v{release}")
3237
release_download_dir.mkdir(parents=True, exist_ok=True)
@@ -36,6 +41,8 @@ def download_stix(stix_version: str, domain: str, download_dir: str, release: st
3641
download_url = f"https://raw.githubusercontent.com/mitre/cti/ATT%26CK-v{release}/{domain}-attack/{fname}"
3742
elif stix_version == "2.1":
3843
download_url = f"https://raw.githubusercontent.com/mitre-attack/attack-stix-data/master/{domain}-attack/{domain}-attack-{release}.json"
44+
else:
45+
raise ValueError(f"Invalid STIX version: {stix_version}")
3946

4047
pooch.retrieve(download_url, known_hash=known_hash, fname=fname, path=str(release_download_dir))
4148

@@ -57,6 +64,11 @@ def download_domains(
5764
Version of STIX to download. Options are "2.0" or "2.1"
5865
attack_versions : List[str], optional
5966
List of specific ATT&CK versions to download. If provided, overrides all_versions behavior.
67+
68+
Raises
69+
------
70+
ValueError
71+
Raised if `stix_version` is not "2.0" or "2.1".
6072
"""
6173
for domain in domains:
6274
if domain == "pre" and stix_version == "2.1":
@@ -67,6 +79,8 @@ def download_domains(
6779
stix_hash_data = release_info.STIX20
6880
elif stix_version == "2.1":
6981
stix_hash_data = release_info.STIX21
82+
else:
83+
raise ValueError(f"Invalid STIX version: {stix_version}")
7084

7185
releases = {}
7286
if domain == "enterprise":

mitreattack/navlayers/core/layer.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import json
44
import traceback
55

6-
from mitreattack.navlayers.core.exceptions import UninitializedLayer, BadType, BadInput, handler
6+
from mitreattack.navlayers.core.exceptions import BadInput, BadType, UninitializedLayer, handler
77
from mitreattack.navlayers.core.layerobj import _LayerObj
88

99

@@ -61,6 +61,7 @@ def from_file(self, filename):
6161
:param filename: the target filename to load from
6262
"""
6363
fallback = False
64+
raw = ""
6465
with open(filename, "r", encoding="utf-16") as fio:
6566
try:
6667
raw = fio.read()

mitreattack/navlayers/exporters/excel_templates.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"""Contains ExcelTemplates class."""
22

33
import openpyxl
4-
from openpyxl.styles import Font, Alignment, Border, Side, PatternFill
4+
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
55

66
from mitreattack.navlayers.exporters.matrix_gen import MatrixGen
77

mitreattack/navlayers/exporters/svg_objects.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
"""Helper classes and functions for working with SVG objects."""
22

3-
import drawsvg
43
import colorsys
5-
import numpy as np
64
import os
5+
6+
import drawsvg
7+
import numpy as np
78
from PIL import ImageFont
89

910
from mitreattack.navlayers.core.gradient import Gradient

0 commit comments

Comments
 (0)