targetzero 0.3.2__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.
- targetzero/__init__.py +4 -0
- targetzero/__main__.py +6 -0
- targetzero/admins.py +109 -0
- targetzero/cli.py +366 -0
- targetzero/common/__init__.py +2 -0
- targetzero/common/changes.py +46 -0
- targetzero/common/config.py +83 -0
- targetzero/common/ids.py +17 -0
- targetzero/common/output.py +91 -0
- targetzero/common/resources.py +32 -0
- targetzero/common/roles.py +24 -0
- targetzero/common/schema.py +45 -0
- targetzero/config/approved_exposure.example.csv +4 -0
- targetzero/config/privileged_roles.yaml +50 -0
- targetzero/config/targetzero.example.yaml +57 -0
- targetzero/external/__init__.py +2 -0
- targetzero/external/dangling.py +106 -0
- targetzero/external/discover.py +181 -0
- targetzero/external/dnsinfo.py +54 -0
- targetzero/external/enrich.py +137 -0
- targetzero/external/http.py +33 -0
- targetzero/external/kev.py +222 -0
- targetzero/external/ports.py +63 -0
- targetzero/external/scan.py +260 -0
- targetzero/external/scope.py +54 -0
- targetzero/external/waf.py +202 -0
- targetzero/external/web.py +124 -0
- targetzero/gws/__init__.py +2 -0
- targetzero/gws/admins.py +230 -0
- targetzero/gws/changes.py +190 -0
- targetzero/gws/client.py +94 -0
- targetzero/gws/domains.py +36 -0
- targetzero/registers/__init__.py +2 -0
- targetzero/registers/exceptions.py +85 -0
- targetzero/registers/findings.py +108 -0
- targetzero/registers/inventory.py +142 -0
- targetzero/registers/manual_admins.py +43 -0
- targetzero/schemas/admins.schema.json +27 -0
- targetzero/schemas/alert_tests.schema.json +19 -0
- targetzero/schemas/config.schema.json +71 -0
- targetzero/schemas/exceptions.schema.json +20 -0
- targetzero/schemas/findings.schema.json +23 -0
- targetzero/schemas/inventory.schema.json +26 -0
- targetzero/schemas/summary.schema.json +36 -0
- targetzero/scorecard/__init__.py +2 -0
- targetzero/scorecard/scorecard.py +201 -0
- targetzero/templates/alert_tests.csv +1 -0
- targetzero/templates/exceptions.csv +1 -0
- targetzero/templates/findings.csv +1 -0
- targetzero/templates/inventory.csv +1 -0
- targetzero/templates/manual_admins.csv +1 -0
- targetzero/templates/origins.csv +1 -0
- targetzero/templates/recovery_page.md +51 -0
- targetzero/vendors/__init__.py +2 -0
- targetzero/vendors/cisco_asa.py +151 -0
- targetzero/vendors/common.py +84 -0
- targetzero/vendors/fortigate.py +176 -0
- targetzero/vendors/panos.py +141 -0
- targetzero/vendors/redfish.py +124 -0
- targetzero/vendors/vsphere.py +108 -0
- targetzero-0.3.2.dist-info/METADATA +116 -0
- targetzero-0.3.2.dist-info/RECORD +66 -0
- targetzero-0.3.2.dist-info/WHEEL +4 -0
- targetzero-0.3.2.dist-info/entry_points.txt +2 -0
- targetzero-0.3.2.dist-info/licenses/LICENSE +202 -0
- targetzero-0.3.2.dist-info/licenses/NOTICE +7 -0
targetzero/__init__.py
ADDED
targetzero/__main__.py
ADDED
targetzero/admins.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Turn unified admin records into the Zero 1 and Zero 2 counts.
|
|
3
|
+
|
|
4
|
+
Records are one row per account and role. Counts are per account:
|
|
5
|
+
|
|
6
|
+
- Zero 1: the account holds at least one privileged role permanently and is
|
|
7
|
+
not a break-glass account.
|
|
8
|
+
- Zero 2: the account is not a service account and either has no MFA method
|
|
9
|
+
that counts (none, does-not-count, unknown) or MFA is not enforced for it.
|
|
10
|
+
|
|
11
|
+
The PowerShell module implements the same rules (Export-T0AdminSummary); keep
|
|
12
|
+
both in step.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from collections.abc import Iterable, Mapping, Sequence
|
|
18
|
+
from datetime import date
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
from targetzero.common.ids import make_id
|
|
22
|
+
from targetzero.common.output import base_name, write_csv, write_summary
|
|
23
|
+
|
|
24
|
+
FIELDS = (
|
|
25
|
+
"id",
|
|
26
|
+
"source",
|
|
27
|
+
"system",
|
|
28
|
+
"account",
|
|
29
|
+
"role",
|
|
30
|
+
"account_type",
|
|
31
|
+
"privileged",
|
|
32
|
+
"permanent",
|
|
33
|
+
"end_date",
|
|
34
|
+
"mfa_class",
|
|
35
|
+
"mfa_enforced",
|
|
36
|
+
"separate_admin_account",
|
|
37
|
+
"break_glass",
|
|
38
|
+
"last_logon",
|
|
39
|
+
"last_verified",
|
|
40
|
+
"notes",
|
|
41
|
+
)
|
|
42
|
+
MFA_RANK = {"none": 0, "does-not-count": 1, "unknown": 2, "mfa": 3, "phishing-resistant": 4}
|
|
43
|
+
ENFORCED_RANK = {"N": 0, "unknown": 1, "Y": 2}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def record_id(source: str, system: str, account: str, role: str) -> str:
|
|
47
|
+
return make_id(source, system, account, role)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def account_id(source: str, system: str, account: str) -> str:
|
|
51
|
+
return make_id(source, system, account)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def count_items(
|
|
55
|
+
records: Iterable[Mapping[str, str]],
|
|
56
|
+
) -> tuple[list[dict[str, str]], list[dict[str, str]]]:
|
|
57
|
+
"""Return (zero1_items, zero2_items) for a list of admin records."""
|
|
58
|
+
accounts: dict[str, list[Mapping[str, str]]] = {}
|
|
59
|
+
for r in records:
|
|
60
|
+
accounts.setdefault(account_id(r["source"], r["system"], r["account"]), []).append(r)
|
|
61
|
+
|
|
62
|
+
zero1, zero2 = [], []
|
|
63
|
+
for item_id, rows in sorted(accounts.items()):
|
|
64
|
+
permanent = sorted(
|
|
65
|
+
{r["role"] for r in rows if r["privileged"] == "Y" and r["permanent"] == "Y"}
|
|
66
|
+
)
|
|
67
|
+
if permanent and not any(r["break_glass"] == "Y" for r in rows):
|
|
68
|
+
zero1.append({"id": item_id, "reason": "Permanent " + ", ".join(permanent)})
|
|
69
|
+
|
|
70
|
+
if all(r.get("account_type") == "service" for r in rows):
|
|
71
|
+
continue
|
|
72
|
+
mfa = min((r["mfa_class"] for r in rows), key=lambda c: MFA_RANK.get(c, 0))
|
|
73
|
+
enforced = min((r["mfa_enforced"] for r in rows), key=lambda e: ENFORCED_RANK.get(e, 0))
|
|
74
|
+
if MFA_RANK.get(mfa, 0) < MFA_RANK["mfa"] or enforced != "Y":
|
|
75
|
+
zero2.append({"id": item_id, "reason": f"MFA: {mfa}; enforced: {enforced}"})
|
|
76
|
+
return zero1, zero2
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def write_admin_outputs(
|
|
80
|
+
directory: Path,
|
|
81
|
+
*,
|
|
82
|
+
source: str,
|
|
83
|
+
records: Sequence[Mapping[str, str]],
|
|
84
|
+
tool: str,
|
|
85
|
+
run_date: date,
|
|
86
|
+
complete: bool = True,
|
|
87
|
+
notes: Sequence[str] = (),
|
|
88
|
+
) -> list[Path]:
|
|
89
|
+
"""Write <1>_<source>_admins.csv plus the Zero 1 and Zero 2 summaries."""
|
|
90
|
+
record_file = f"{base_name(1, source, 'admins')}.csv"
|
|
91
|
+
rows = [{f: r.get(f, "") for f in FIELDS} for r in records]
|
|
92
|
+
paths = [write_csv(directory / record_file, rows, FIELDS)]
|
|
93
|
+
zero1, zero2 = count_items(rows)
|
|
94
|
+
for zero, name, items in ((1, "admins", zero1), (2, "mfa", zero2)):
|
|
95
|
+
paths.append(
|
|
96
|
+
write_summary(
|
|
97
|
+
directory,
|
|
98
|
+
zero=zero,
|
|
99
|
+
source=source,
|
|
100
|
+
name=name,
|
|
101
|
+
items=items,
|
|
102
|
+
tool=tool,
|
|
103
|
+
run_date=run_date,
|
|
104
|
+
complete=complete,
|
|
105
|
+
notes=notes,
|
|
106
|
+
record_file=record_file,
|
|
107
|
+
)
|
|
108
|
+
)
|
|
109
|
+
return paths
|
targetzero/cli.py
ADDED
|
@@ -0,0 +1,366 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Command-line entry point: `targetzero <command>`."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
import json
|
|
8
|
+
import shutil
|
|
9
|
+
import sys
|
|
10
|
+
from datetime import date
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from targetzero import __version__
|
|
14
|
+
from targetzero.common.config import ConfigError, load_config
|
|
15
|
+
from targetzero.common.output import read_csv
|
|
16
|
+
from targetzero.common.resources import example_config_dir, templates_dir
|
|
17
|
+
from targetzero.common.schema import SCHEMAS, validate, validate_summary
|
|
18
|
+
from targetzero.scorecard import scorecard
|
|
19
|
+
|
|
20
|
+
# Register file name -> schema, for `targetzero validate` without --schema.
|
|
21
|
+
CSV_SCHEMAS = {
|
|
22
|
+
"manual_admins": "admins",
|
|
23
|
+
"inventory": "inventory",
|
|
24
|
+
"findings": "findings",
|
|
25
|
+
"exceptions": "exceptions",
|
|
26
|
+
"alert_tests": "alert_tests",
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _date(value: str) -> date:
|
|
31
|
+
try:
|
|
32
|
+
return date.fromisoformat(value)
|
|
33
|
+
except ValueError as exc:
|
|
34
|
+
raise argparse.ArgumentTypeError(f"not a date (YYYY-MM-DD): {value}") from exc
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def cmd_init(args: argparse.Namespace) -> int:
|
|
38
|
+
target = Path(args.dir).resolve()
|
|
39
|
+
registers = target / "registers"
|
|
40
|
+
registers.mkdir(parents=True, exist_ok=True)
|
|
41
|
+
examples = example_config_dir()
|
|
42
|
+
copies = [
|
|
43
|
+
(examples / "targetzero.example.yaml", target / "targetzero.yaml"),
|
|
44
|
+
(examples / "privileged_roles.yaml", target / "privileged_roles.yaml"),
|
|
45
|
+
(examples / "approved_exposure.example.csv", registers / "approved_exposure.csv"),
|
|
46
|
+
]
|
|
47
|
+
copies += [(t, registers / t.name) for t in sorted(templates_dir().glob("*.csv"))]
|
|
48
|
+
copies.append((templates_dir() / "recovery_page.md", registers / "recovery" / "_template.md"))
|
|
49
|
+
for source, destination in copies:
|
|
50
|
+
if destination.exists():
|
|
51
|
+
print(f"kept {destination}")
|
|
52
|
+
continue
|
|
53
|
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
54
|
+
shutil.copyfile(source, destination)
|
|
55
|
+
print(f"created {destination}")
|
|
56
|
+
print("\nNext: edit targetzero.yaml, then run the inventory scripts for your platforms.")
|
|
57
|
+
return 0
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def cmd_scorecard(args: argparse.Namespace) -> int:
|
|
61
|
+
config = load_config(args.config)
|
|
62
|
+
card = scorecard.build(config, args.date)
|
|
63
|
+
paths = scorecard.write(config, card)
|
|
64
|
+
print(scorecard.render_text(card))
|
|
65
|
+
print("\nWritten:\n " + "\n ".join(str(p) for p in paths))
|
|
66
|
+
return 0
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def cmd_validate(args: argparse.Namespace) -> int:
|
|
70
|
+
failed = False
|
|
71
|
+
for name in args.files:
|
|
72
|
+
path = Path(name)
|
|
73
|
+
if path.name.endswith(".summary.json"):
|
|
74
|
+
problems = validate_summary(json.loads(path.read_text(encoding="utf-8")))
|
|
75
|
+
else:
|
|
76
|
+
schema = args.schema or CSV_SCHEMAS.get(path.stem)
|
|
77
|
+
if not schema:
|
|
78
|
+
print(f"{path}: cannot tell which schema to use; pass --schema", file=sys.stderr)
|
|
79
|
+
failed = True
|
|
80
|
+
continue
|
|
81
|
+
problems = [
|
|
82
|
+
f"row {n}: {p}"
|
|
83
|
+
for n, row in enumerate(read_csv(path), start=2)
|
|
84
|
+
for p in validate(row, schema)
|
|
85
|
+
]
|
|
86
|
+
failed = failed or bool(problems)
|
|
87
|
+
print(f"{path}: {'OK' if not problems else f'{len(problems)} problem(s)'}")
|
|
88
|
+
for problem in problems:
|
|
89
|
+
print(f" {problem}")
|
|
90
|
+
return 1 if failed else 0
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _print_paths(paths: list[Path]) -> int:
|
|
94
|
+
for path in paths:
|
|
95
|
+
print(f"written {path}")
|
|
96
|
+
for path in paths:
|
|
97
|
+
if path.name.endswith(".summary.json"):
|
|
98
|
+
data = json.loads(path.read_text(encoding="utf-8"))
|
|
99
|
+
state = "" if data["complete"] else " (incomplete)"
|
|
100
|
+
print(f"Zero {data['zero']} {data['source']}/{data['name']}: {data['count']}{state}")
|
|
101
|
+
for note in data.get("notes", []):
|
|
102
|
+
print(f" note: {note}")
|
|
103
|
+
return 0
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def cmd_registers(args: argparse.Namespace) -> int:
|
|
107
|
+
from targetzero.registers import findings, inventory, manual_admins
|
|
108
|
+
|
|
109
|
+
config = load_config(args.config)
|
|
110
|
+
runners = {
|
|
111
|
+
"manual-admins": manual_admins.run,
|
|
112
|
+
"inventory": inventory.count,
|
|
113
|
+
"findings": findings.count,
|
|
114
|
+
}
|
|
115
|
+
return _print_paths(runners[args.register](config, args.date))
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def cmd_external(args: argparse.Namespace) -> int:
|
|
119
|
+
from targetzero.external import dangling, discover, enrich, kev, scan, waf
|
|
120
|
+
|
|
121
|
+
config = load_config(args.config)
|
|
122
|
+
if args.check == "scan":
|
|
123
|
+
if not args.authorised:
|
|
124
|
+
print(
|
|
125
|
+
"error: confirm with --authorised that you own or may scan every address in "
|
|
126
|
+
"scope.ip_ranges. Run it from outside your own network.",
|
|
127
|
+
file=sys.stderr,
|
|
128
|
+
)
|
|
129
|
+
return 2
|
|
130
|
+
paths = scan.run(
|
|
131
|
+
config,
|
|
132
|
+
args.date,
|
|
133
|
+
use_nmap=not args.no_nmap,
|
|
134
|
+
use_internetdb=args.internetdb,
|
|
135
|
+
max_hosts=args.max_hosts,
|
|
136
|
+
timeout=args.timeout,
|
|
137
|
+
)
|
|
138
|
+
elif args.check == "discover":
|
|
139
|
+
zones = []
|
|
140
|
+
for spec in args.zone_file:
|
|
141
|
+
file, _, origin = spec.partition(":")
|
|
142
|
+
zones.append((Path(file), origin or None))
|
|
143
|
+
paths = discover.run(config, args.date, use_crtsh=not args.no_crtsh, zone_files=zones)
|
|
144
|
+
elif args.check == "waf":
|
|
145
|
+
paths = waf.run(config, args.date, test_origins=args.authorised)
|
|
146
|
+
elif args.check == "enrich":
|
|
147
|
+
paths = enrich.run(config, args.date)
|
|
148
|
+
elif args.check == "dangling-dns":
|
|
149
|
+
paths = dangling.run(config, args.date)
|
|
150
|
+
else:
|
|
151
|
+
paths = kev.run(config, args.date, use_nvd=not args.no_nvd, recent_days=args.recent_days)
|
|
152
|
+
return _print_paths(paths)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _confirm(question: str) -> bool:
|
|
156
|
+
try:
|
|
157
|
+
return input(f"{question} Type yes to continue: ").strip().lower() == "yes"
|
|
158
|
+
except EOFError:
|
|
159
|
+
return False
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _print_results(results: list[dict[str, str]], paths: list[Path]) -> int:
|
|
163
|
+
for r in results:
|
|
164
|
+
print(
|
|
165
|
+
f"{r['status']:<8} {r.get('plan_id', ''):<6} {r['account']:<40} {r['action']:<20} "
|
|
166
|
+
f"{r['detail']}"
|
|
167
|
+
)
|
|
168
|
+
print("\nLog:\n " + "\n ".join(str(p) for p in paths))
|
|
169
|
+
return 1 if any(r["status"] == "failed" for r in results) else 0
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def cmd_gws(args: argparse.Namespace) -> int:
|
|
173
|
+
from targetzero.gws import admins, changes, client, domains
|
|
174
|
+
|
|
175
|
+
config = load_config(args.config)
|
|
176
|
+
if args.check == "apply":
|
|
177
|
+
if args.apply and not args.yes and not _confirm(f"Apply the actions in {args.plan}?"):
|
|
178
|
+
print("Nothing changed.")
|
|
179
|
+
return 1
|
|
180
|
+
gws = client.connect(
|
|
181
|
+
config, scopes=client.WRITE_SCOPES if args.apply else client.READ_SCOPES
|
|
182
|
+
)
|
|
183
|
+
results, paths = changes.apply_plan(
|
|
184
|
+
config, gws, Path(args.plan), args.date, apply=args.apply
|
|
185
|
+
)
|
|
186
|
+
return _print_results(results, paths)
|
|
187
|
+
gws = client.connect(config)
|
|
188
|
+
if args.check == "admins":
|
|
189
|
+
return _print_paths(admins.run(config, args.date, gws, days=args.days))
|
|
190
|
+
return _print_paths(domains.run(config, args.date, gws))
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def cmd_vendors(args: argparse.Namespace) -> int:
|
|
194
|
+
from targetzero.vendors import cisco_asa, common, fortigate, panos, redfish, vsphere
|
|
195
|
+
|
|
196
|
+
config = load_config(args.config)
|
|
197
|
+
break_glass = set(config.break_glass(args.vendor))
|
|
198
|
+
offline = {"fortigate": fortigate.collect, "panos": panos.collect, "asa": cisco_asa.collect}
|
|
199
|
+
if args.vendor in offline:
|
|
200
|
+
devices = [offline[args.vendor](Path(f), break_glass) for f in args.files]
|
|
201
|
+
elif args.vendor == "redfish":
|
|
202
|
+
context = redfish.ssl_context(args.ca_bundle, args.insecure)
|
|
203
|
+
user, password = redfish.credentials()
|
|
204
|
+
devices = [
|
|
205
|
+
redfish.collect(redfish.Redfish(h, user, password, context), h, break_glass)
|
|
206
|
+
for h in args.host
|
|
207
|
+
]
|
|
208
|
+
else:
|
|
209
|
+
context = redfish.ssl_context(args.ca_bundle, args.insecure)
|
|
210
|
+
devices = []
|
|
211
|
+
for host in args.host:
|
|
212
|
+
instance = vsphere.connect(host, context)
|
|
213
|
+
try:
|
|
214
|
+
devices.append(
|
|
215
|
+
vsphere.collect(
|
|
216
|
+
instance.RetrieveContent(), host, break_glass, mfa_via_idp=args.mfa_via_idp
|
|
217
|
+
)
|
|
218
|
+
)
|
|
219
|
+
finally:
|
|
220
|
+
vsphere.disconnect(instance)
|
|
221
|
+
return _print_paths(
|
|
222
|
+
common.write_outputs(
|
|
223
|
+
config,
|
|
224
|
+
args.date,
|
|
225
|
+
args.vendor,
|
|
226
|
+
devices,
|
|
227
|
+
tool=f"targetzero vendors {args.vendor}",
|
|
228
|
+
)
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
233
|
+
parser = argparse.ArgumentParser(prog="targetzero", description=__doc__)
|
|
234
|
+
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
235
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
236
|
+
|
|
237
|
+
p = sub.add_parser("init", help="create targetzero.yaml and empty registers")
|
|
238
|
+
p.add_argument("dir", nargs="?", default=".", help="folder to set up (default: current)")
|
|
239
|
+
p.set_defaults(func=cmd_init)
|
|
240
|
+
|
|
241
|
+
p = sub.add_parser("scorecard", help="build the scorecard from today's summaries")
|
|
242
|
+
p.add_argument("--config", help="path to targetzero.yaml")
|
|
243
|
+
p.add_argument("--date", type=_date, default=date.today(), help="run date (default: today)")
|
|
244
|
+
p.set_defaults(func=cmd_scorecard)
|
|
245
|
+
|
|
246
|
+
common = argparse.ArgumentParser(add_help=False)
|
|
247
|
+
common.add_argument("--config", help="path to targetzero.yaml")
|
|
248
|
+
common.add_argument(
|
|
249
|
+
"--date", type=_date, default=date.today(), help="run date (default: today)"
|
|
250
|
+
)
|
|
251
|
+
|
|
252
|
+
p = sub.add_parser("registers", help="count the hand-maintained registers")
|
|
253
|
+
p.add_argument("register", choices=["manual-admins", "inventory", "findings"])
|
|
254
|
+
p.add_argument("--config", help="path to targetzero.yaml")
|
|
255
|
+
p.add_argument("--date", type=_date, default=date.today(), help="run date (default: today)")
|
|
256
|
+
p.set_defaults(func=cmd_registers)
|
|
257
|
+
|
|
258
|
+
ext = sub.add_parser("external", help="checks from outside: scan, discover, kev")
|
|
259
|
+
ext_sub = ext.add_subparsers(dest="check", required=True)
|
|
260
|
+
p = ext_sub.add_parser("scan", parents=[common], help="open ports vs approved list (Zero 4)")
|
|
261
|
+
p.add_argument(
|
|
262
|
+
"--authorised",
|
|
263
|
+
action="store_true",
|
|
264
|
+
help="confirm you own or may scan every address in scope",
|
|
265
|
+
)
|
|
266
|
+
p.add_argument("--no-nmap", action="store_true", help="use the built-in scanner")
|
|
267
|
+
p.add_argument(
|
|
268
|
+
"--internetdb", action="store_true", help="also ask Shodan InternetDB (free, no key)"
|
|
269
|
+
)
|
|
270
|
+
p.add_argument("--max-hosts", type=int, default=1024)
|
|
271
|
+
p.add_argument("--timeout", type=float, default=1.5, help="seconds per port (built-in)")
|
|
272
|
+
p = ext_sub.add_parser(
|
|
273
|
+
"discover", parents=[common], help="find names and addresses, update the inventory (Zero 5)"
|
|
274
|
+
)
|
|
275
|
+
p.add_argument("--no-crtsh", action="store_true", help="skip certificate transparency")
|
|
276
|
+
p.add_argument(
|
|
277
|
+
"--zone-file",
|
|
278
|
+
action="append",
|
|
279
|
+
default=[],
|
|
280
|
+
metavar="FILE[:ORIGIN]",
|
|
281
|
+
help="DNS zone file export; repeat for more zones",
|
|
282
|
+
)
|
|
283
|
+
p = ext_sub.add_parser(
|
|
284
|
+
"kev", parents=[common], help="match CISA KEV against the inventory (Zero 6)"
|
|
285
|
+
)
|
|
286
|
+
p.add_argument("--no-nvd", action="store_true", help="skip NVD version checks")
|
|
287
|
+
p.add_argument(
|
|
288
|
+
"--recent-days",
|
|
289
|
+
type=int,
|
|
290
|
+
default=30,
|
|
291
|
+
help="without a version, report KEV entries this recent (default 30)",
|
|
292
|
+
)
|
|
293
|
+
p = ext_sub.add_parser(
|
|
294
|
+
"waf", parents=[common], help="web names behind a WAF/CDN, origins closed (Zero 4)"
|
|
295
|
+
)
|
|
296
|
+
p.add_argument(
|
|
297
|
+
"--authorised",
|
|
298
|
+
action="store_true",
|
|
299
|
+
help="also test origins in registers/origins.csv (must be in scope)",
|
|
300
|
+
)
|
|
301
|
+
ext_sub.add_parser(
|
|
302
|
+
"enrich", parents=[common], help="suggest product, version and support status (Zero 5)"
|
|
303
|
+
)
|
|
304
|
+
ext_sub.add_parser(
|
|
305
|
+
"dangling-dns",
|
|
306
|
+
parents=[common],
|
|
307
|
+
help="DNS records pointing to unclaimed resources (Zero 5)",
|
|
308
|
+
)
|
|
309
|
+
ext.set_defaults(func=cmd_external)
|
|
310
|
+
|
|
311
|
+
g = sub.add_parser("gws", help="Google Workspace checks")
|
|
312
|
+
g_sub = g.add_subparsers(dest="check", required=True)
|
|
313
|
+
p = g_sub.add_parser("admins", parents=[common], help="admins and MFA (Zero 1, 2)")
|
|
314
|
+
p.add_argument("--days", type=int, default=30, help="sign-in history to read (default 30)")
|
|
315
|
+
g_sub.add_parser("domains", parents=[common], help="domains, for discovery (Zero 5)")
|
|
316
|
+
p = g_sub.add_parser(
|
|
317
|
+
"apply", parents=[common], help="apply a reviewed role plan (dry run unless --apply)"
|
|
318
|
+
)
|
|
319
|
+
p.add_argument("plan", help="1_gws_role-plan.csv with the action column filled in")
|
|
320
|
+
p.add_argument("--apply", action="store_true", help="make the changes")
|
|
321
|
+
p.add_argument("--yes", action="store_true", help="do not ask for confirmation")
|
|
322
|
+
g.set_defaults(func=cmd_gws)
|
|
323
|
+
|
|
324
|
+
v = sub.add_parser("vendors", help="firewall and VPN collectors (offline config files)")
|
|
325
|
+
v_sub = v.add_subparsers(dest="vendor", required=True)
|
|
326
|
+
for name, label in (
|
|
327
|
+
("fortigate", "FortiGate .conf backups"),
|
|
328
|
+
("panos", "PAN-OS running-config.xml files"),
|
|
329
|
+
("asa", "Cisco ASA running-config text files"),
|
|
330
|
+
):
|
|
331
|
+
p = v_sub.add_parser(name, parents=[common], help=label)
|
|
332
|
+
p.add_argument("files", nargs="+", help="all devices of this vendor, in one run")
|
|
333
|
+
for name, label in (
|
|
334
|
+
("redfish", "iDRAC, iLO and other Redfish management cards (live, read-only)"),
|
|
335
|
+
("vsphere", "vCenter or ESXi (live, read-only; needs targetzero[vsphere])"),
|
|
336
|
+
):
|
|
337
|
+
p = v_sub.add_parser(name, parents=[common], help=label)
|
|
338
|
+
p.add_argument("--host", action="append", required=True, help="repeat for more hosts")
|
|
339
|
+
p.add_argument("--ca-bundle", help="CA file for self-signed management certificates")
|
|
340
|
+
p.add_argument("--insecure", action="store_true", help="do not verify certificates")
|
|
341
|
+
if name == "vsphere":
|
|
342
|
+
p.add_argument(
|
|
343
|
+
"--mfa-via-idp",
|
|
344
|
+
action="store_true",
|
|
345
|
+
help="your identity source enforces MFA for these admins",
|
|
346
|
+
)
|
|
347
|
+
v.set_defaults(func=cmd_vendors)
|
|
348
|
+
|
|
349
|
+
p = sub.add_parser("validate", help="check summaries or register CSVs against the schemas")
|
|
350
|
+
p.add_argument("files", nargs="+")
|
|
351
|
+
p.add_argument("--schema", choices=[s for s in SCHEMAS if s not in ("summary", "config")])
|
|
352
|
+
p.set_defaults(func=cmd_validate)
|
|
353
|
+
return parser
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def main(argv: list[str] | None = None) -> int:
|
|
357
|
+
args = build_parser().parse_args(argv)
|
|
358
|
+
try:
|
|
359
|
+
return int(args.func(args))
|
|
360
|
+
except ConfigError as exc:
|
|
361
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
362
|
+
return 2
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
if __name__ == "__main__":
|
|
366
|
+
sys.exit(main())
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Change log and rollback plan for change commands (same format as Save-T0ChangeLog).
|
|
3
|
+
|
|
4
|
+
changes_<name>_<timestamp>.json every planned action with its status
|
|
5
|
+
rollback_<name>_<timestamp>.csv a plan that the same command can apply to undo the run
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
from collections.abc import Mapping, Sequence
|
|
12
|
+
from datetime import UTC, datetime
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from targetzero.common.output import write_csv
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def save_change_log(
|
|
20
|
+
directory: Path,
|
|
21
|
+
name: str,
|
|
22
|
+
changes: Sequence[Mapping[str, Any]],
|
|
23
|
+
rollback: Sequence[Mapping[str, str]],
|
|
24
|
+
fields: Sequence[str],
|
|
25
|
+
*,
|
|
26
|
+
dry_run: bool,
|
|
27
|
+
) -> list[Path]:
|
|
28
|
+
stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
|
|
29
|
+
log = directory / f"{'dryrun' if dry_run else 'changes'}_{name}_{stamp}.json"
|
|
30
|
+
log.write_text(
|
|
31
|
+
json.dumps(
|
|
32
|
+
{
|
|
33
|
+
"tool": name,
|
|
34
|
+
"dry_run": dry_run,
|
|
35
|
+
"timestamp": datetime.now(UTC).isoformat(timespec="seconds"),
|
|
36
|
+
"changes": list(changes),
|
|
37
|
+
},
|
|
38
|
+
indent=2,
|
|
39
|
+
)
|
|
40
|
+
+ "\n",
|
|
41
|
+
encoding="utf-8",
|
|
42
|
+
)
|
|
43
|
+
paths = [log]
|
|
44
|
+
if rollback and not dry_run:
|
|
45
|
+
paths.append(write_csv(directory / f"rollback_{name}_{stamp}.csv", rollback, fields))
|
|
46
|
+
return paths
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Load and validate targetzero.yaml."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import yaml
|
|
12
|
+
|
|
13
|
+
from targetzero.common.schema import validate
|
|
14
|
+
|
|
15
|
+
ENV_VAR = "TARGETZERO_CONFIG"
|
|
16
|
+
DEFAULT_LOCATIONS = (Path("targetzero.yaml"), Path("config") / "targetzero.yaml")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class ConfigError(Exception):
|
|
20
|
+
"""The configuration file is missing or invalid."""
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True)
|
|
24
|
+
class Config:
|
|
25
|
+
path: Path
|
|
26
|
+
data: dict[str, Any]
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def organisation(self) -> str:
|
|
30
|
+
return str(self.data["organisation"])
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def output_dir(self) -> Path:
|
|
34
|
+
return self._resolve(self.data.get("output_dir", "output"))
|
|
35
|
+
|
|
36
|
+
@property
|
|
37
|
+
def registers_dir(self) -> Path:
|
|
38
|
+
return self._resolve(self.data.get("registers_dir", "registers"))
|
|
39
|
+
|
|
40
|
+
def owner(self, zero: int) -> str:
|
|
41
|
+
return str(self.data.get("owners", {}).get(str(zero), ""))
|
|
42
|
+
|
|
43
|
+
def break_glass(self, source: str) -> list[str]:
|
|
44
|
+
return [a.lower() for a in self.data.get("break_glass", {}).get(source, [])]
|
|
45
|
+
|
|
46
|
+
def threshold(self, name: str, default: int) -> int:
|
|
47
|
+
return int(self.data.get("thresholds", {}).get(name, default))
|
|
48
|
+
|
|
49
|
+
def _resolve(self, value: str) -> Path:
|
|
50
|
+
path = Path(value).expanduser()
|
|
51
|
+
return path if path.is_absolute() else (self.path.parent / path).resolve()
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def find_config(explicit: str | os.PathLike[str] | None = None) -> Path:
|
|
55
|
+
if explicit:
|
|
56
|
+
return Path(explicit)
|
|
57
|
+
if os.environ.get(ENV_VAR):
|
|
58
|
+
return Path(os.environ[ENV_VAR])
|
|
59
|
+
for candidate in DEFAULT_LOCATIONS:
|
|
60
|
+
if candidate.exists():
|
|
61
|
+
return candidate
|
|
62
|
+
raise ConfigError(
|
|
63
|
+
f"No configuration found. Run 'targetzero init', pass --config, or set {ENV_VAR}."
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def load_config(explicit: str | os.PathLike[str] | None = None) -> Config:
|
|
68
|
+
path = find_config(explicit).resolve()
|
|
69
|
+
if not path.is_file():
|
|
70
|
+
raise ConfigError(f"Configuration file not found: {path}")
|
|
71
|
+
try:
|
|
72
|
+
data = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
|
|
73
|
+
except yaml.YAMLError as exc:
|
|
74
|
+
raise ConfigError(f"{path} is not valid YAML: {exc}") from exc
|
|
75
|
+
if not isinstance(data, dict):
|
|
76
|
+
raise ConfigError(f"{path} must contain a mapping at the top level")
|
|
77
|
+
# YAML reads `1:` as an integer key; the schema expects strings.
|
|
78
|
+
if isinstance(data.get("owners"), dict):
|
|
79
|
+
data["owners"] = {str(k): v for k, v in data["owners"].items()}
|
|
80
|
+
problems = validate(data, "config")
|
|
81
|
+
if problems:
|
|
82
|
+
raise ConfigError(f"{path} is invalid:\n " + "\n ".join(problems))
|
|
83
|
+
return Config(path=path, data=data)
|
targetzero/common/ids.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Stable item ids: <source>:<part>/<part>... without spaces or semicolons.
|
|
3
|
+
|
|
4
|
+
Exceptions refer to these ids, so the same thing must get the same id on every
|
|
5
|
+
run. Parts are lowercased and whitespace or semicolons become hyphens.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
|
|
12
|
+
_UNSAFE = re.compile(r"[\s;]+")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def make_id(source: str, *parts: str) -> str:
|
|
16
|
+
cleaned = [_UNSAFE.sub("-", p.strip().lower()).strip("-") for p in parts if p.strip()]
|
|
17
|
+
return f"{source}:{'/'.join(cleaned)}"
|