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/gws/admins.py
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Google Workspace admins (Zero 1 and Zero 2).
|
|
3
|
+
|
|
4
|
+
Records one row per admin and role, in the unified admin format:
|
|
5
|
+
|
|
6
|
+
- Roles come from role assignments; super admins without an explicit
|
|
7
|
+
assignment are added from the user list (isAdmin).
|
|
8
|
+
- Google Workspace has no general expiry on role assignments. An assignment
|
|
9
|
+
is treated as time-bound only when it carries a condition on request.time.
|
|
10
|
+
- MFA class comes from the second factors the admin actually used to sign in
|
|
11
|
+
during the last --days days (Reports API, login events). Not enrolled in
|
|
12
|
+
2-Step Verification means none. Enrolled but no sign-in seen means unknown.
|
|
13
|
+
- MFA is enforced when 2-Step Verification is enforced for the admin.
|
|
14
|
+
- Separate admin account: N when the admin sent mail in the sample days.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from collections.abc import Iterable, Mapping
|
|
20
|
+
from datetime import UTC, date, datetime, timedelta
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
from targetzero.admins import record_id, write_admin_outputs
|
|
25
|
+
from targetzero.common.config import Config
|
|
26
|
+
from targetzero.common.output import run_dir, write_csv
|
|
27
|
+
from targetzero.common.roles import privileged_roles
|
|
28
|
+
from targetzero.gws.changes import PLAN_FIELDS
|
|
29
|
+
from targetzero.gws.client import Gws
|
|
30
|
+
|
|
31
|
+
SOURCE = "gws"
|
|
32
|
+
|
|
33
|
+
# login_challenge_method values from the Reports API login audit.
|
|
34
|
+
CHALLENGE_CLASS = {
|
|
35
|
+
"security_key": "phishing-resistant",
|
|
36
|
+
"passkey": "phishing-resistant",
|
|
37
|
+
"google_authenticator": "mfa",
|
|
38
|
+
"google_prompt": "mfa",
|
|
39
|
+
"totp": "mfa",
|
|
40
|
+
"offline_otp": "mfa",
|
|
41
|
+
"backup_code": "mfa",
|
|
42
|
+
"internal_two_factor": "mfa",
|
|
43
|
+
"idv_preregistered_phone": "does-not-count",
|
|
44
|
+
"idv_any_phone": "does-not-count",
|
|
45
|
+
}
|
|
46
|
+
RANK = {"does-not-count": 1, "mfa": 3, "phishing-resistant": 4}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def classify(enrolled: bool, methods: Iterable[str]) -> tuple[str, list[str]]:
|
|
50
|
+
"""Weakest second factor used counts: one SMS sign-in shows SMS still works."""
|
|
51
|
+
if not enrolled:
|
|
52
|
+
return "none", []
|
|
53
|
+
classes = [CHALLENGE_CLASS[m] for m in methods if m in CHALLENGE_CLASS]
|
|
54
|
+
unknown = sorted(
|
|
55
|
+
{m for m in methods if m not in CHALLENGE_CLASS and m not in ("password", "none")}
|
|
56
|
+
)
|
|
57
|
+
if not classes:
|
|
58
|
+
return "unknown", unknown
|
|
59
|
+
return min(classes, key=RANK.__getitem__), unknown
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def login_methods(gws: Gws, emails: Iterable[str], days: int) -> dict[str, set[str]]:
|
|
63
|
+
start = (datetime.now(UTC) - timedelta(days=days)).strftime("%Y-%m-%dT%H:%M:%S.000Z")
|
|
64
|
+
found: dict[str, set[str]] = {}
|
|
65
|
+
for email in emails:
|
|
66
|
+
events = gws.pages(
|
|
67
|
+
gws.reports.activities().list,
|
|
68
|
+
"items",
|
|
69
|
+
userKey=email,
|
|
70
|
+
applicationName="login",
|
|
71
|
+
eventName="login_success",
|
|
72
|
+
startTime=start,
|
|
73
|
+
)
|
|
74
|
+
for activity in events:
|
|
75
|
+
for event in activity.get("events", []):
|
|
76
|
+
for parameter in event.get("parameters", []):
|
|
77
|
+
if parameter.get("name") == "login_challenge_method":
|
|
78
|
+
values = parameter.get("multiValue") or [parameter.get("value", "")]
|
|
79
|
+
found.setdefault(email, set()).update(v for v in values if v)
|
|
80
|
+
return found
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def mail_senders(gws: Gws, sample_days: int = 7) -> tuple[set[str], bool]:
|
|
84
|
+
"""Users who sent mail on recent days. Usage reports lag about three days."""
|
|
85
|
+
senders: set[str] = set()
|
|
86
|
+
ok = False
|
|
87
|
+
for offset in range(3, 3 + sample_days):
|
|
88
|
+
day = (date.today() - timedelta(days=offset)).isoformat()
|
|
89
|
+
try:
|
|
90
|
+
reports = gws.pages(
|
|
91
|
+
gws.reports.userUsageReport().get,
|
|
92
|
+
"usageReports",
|
|
93
|
+
userKey="all",
|
|
94
|
+
date=day,
|
|
95
|
+
parameters="gmail:num_emails_sent",
|
|
96
|
+
)
|
|
97
|
+
except Exception: # noqa: S112 - the report for a day may not exist yet
|
|
98
|
+
continue
|
|
99
|
+
ok = True
|
|
100
|
+
for report in reports:
|
|
101
|
+
for parameter in report.get("parameters", []):
|
|
102
|
+
if (
|
|
103
|
+
parameter.get("name") == "gmail:num_emails_sent"
|
|
104
|
+
and int(parameter.get("intValue", 0)) > 0
|
|
105
|
+
):
|
|
106
|
+
senders.add(report.get("entity", {}).get("userEmail", "").lower())
|
|
107
|
+
return senders, ok
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def is_time_bound(assignment: Mapping[str, Any]) -> bool:
|
|
111
|
+
return "request.time" in str(assignment.get("condition", ""))
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def collect(
|
|
115
|
+
gws: Gws, config: Config, days: int
|
|
116
|
+
) -> tuple[list[dict[str, str]], list[str], list[dict[str, str]]]:
|
|
117
|
+
notes: list[str] = []
|
|
118
|
+
privileged = privileged_roles(config, "gws")
|
|
119
|
+
break_glass = set(config.break_glass(SOURCE))
|
|
120
|
+
roles = {
|
|
121
|
+
r["roleId"]: r
|
|
122
|
+
for r in gws.pages(gws.directory.roles().list, "items", customer=gws.customer)
|
|
123
|
+
}
|
|
124
|
+
users = {
|
|
125
|
+
u["id"]: u
|
|
126
|
+
for u in gws.pages(
|
|
127
|
+
gws.directory.users().list, "users", customer=gws.customer, query="isAdmin=true"
|
|
128
|
+
)
|
|
129
|
+
}
|
|
130
|
+
delegated = gws.pages(
|
|
131
|
+
gws.directory.users().list, "users", customer=gws.customer, query="isDelegatedAdmin=true"
|
|
132
|
+
)
|
|
133
|
+
users |= {u["id"]: u for u in delegated}
|
|
134
|
+
assignments = gws.pages(gws.directory.roleAssignments().list, "items", customer=gws.customer)
|
|
135
|
+
|
|
136
|
+
pairs: list[tuple[dict[str, Any], dict[str, Any], dict[str, Any] | None]] = []
|
|
137
|
+
covered: set[str] = set()
|
|
138
|
+
for assignment in assignments:
|
|
139
|
+
assignee = users.get(assignment.get("assignedTo", ""))
|
|
140
|
+
if assignee is None:
|
|
141
|
+
if assignment.get("assigneeType", "user") != "user":
|
|
142
|
+
notes.append(
|
|
143
|
+
f"Role {assignment.get('roleId')} assigned to a group: list its members "
|
|
144
|
+
"in manual_admins.csv"
|
|
145
|
+
)
|
|
146
|
+
continue
|
|
147
|
+
role = roles.get(assignment["roleId"], {"roleName": assignment["roleId"]})
|
|
148
|
+
pairs.append((assignee, role, assignment))
|
|
149
|
+
if role.get("isSuperAdminRole"):
|
|
150
|
+
covered.add(assignee["id"])
|
|
151
|
+
for candidate in users.values():
|
|
152
|
+
if candidate.get("isAdmin") and candidate["id"] not in covered:
|
|
153
|
+
pairs.append((candidate, {"roleName": "Super Admin", "isSuperAdminRole": True}, None))
|
|
154
|
+
|
|
155
|
+
emails = sorted({u["primaryEmail"].lower() for u, _, _ in pairs})
|
|
156
|
+
methods = login_methods(gws, emails, days)
|
|
157
|
+
senders, usage_ok = mail_senders(gws)
|
|
158
|
+
if not usage_ok:
|
|
159
|
+
notes.append("Gmail usage reports unavailable: separate_admin_account left empty")
|
|
160
|
+
|
|
161
|
+
records = []
|
|
162
|
+
plan: list[dict[str, str]] = []
|
|
163
|
+
for user, role, grant in pairs:
|
|
164
|
+
email = user["primaryEmail"].lower()
|
|
165
|
+
name = str(role.get("roleName", "")).replace("_", " ")
|
|
166
|
+
if role.get("isSuperAdminRole"):
|
|
167
|
+
name = "Super Admin"
|
|
168
|
+
mfa_class, unmapped = classify(bool(user.get("isEnrolledIn2Sv")), methods.get(email, set()))
|
|
169
|
+
extra = [f"org unit {user.get('orgUnitPath', '/')}"]
|
|
170
|
+
if user.get("suspended"):
|
|
171
|
+
extra.append("suspended")
|
|
172
|
+
if unmapped:
|
|
173
|
+
extra.append("unmapped sign-in methods: " + ", ".join(unmapped))
|
|
174
|
+
if mfa_class == "unknown":
|
|
175
|
+
extra.append(f"no sign-in in the last {days} days")
|
|
176
|
+
if grant and grant.get("scopeType") == "ORG_UNIT":
|
|
177
|
+
extra.append("role limited to an org unit")
|
|
178
|
+
records.append(
|
|
179
|
+
{
|
|
180
|
+
"id": record_id(SOURCE, gws.customer, email, name),
|
|
181
|
+
"source": SOURCE,
|
|
182
|
+
"system": gws.customer,
|
|
183
|
+
"account": email,
|
|
184
|
+
"role": name,
|
|
185
|
+
"account_type": "user",
|
|
186
|
+
"privileged": "Y"
|
|
187
|
+
if role.get("isSuperAdminRole") or name.casefold() in privileged
|
|
188
|
+
else "N",
|
|
189
|
+
"permanent": "N" if grant and is_time_bound(grant) else "Y",
|
|
190
|
+
"mfa_class": mfa_class,
|
|
191
|
+
"mfa_enforced": "Y" if user.get("isEnforcedIn2Sv") else "N",
|
|
192
|
+
"separate_admin_account": ("N" if email in senders else "Y") if usage_ok else "",
|
|
193
|
+
"break_glass": "Y" if email in break_glass else "N",
|
|
194
|
+
"last_logon": user.get("lastLoginTime", ""),
|
|
195
|
+
"notes": "; ".join(extra),
|
|
196
|
+
}
|
|
197
|
+
)
|
|
198
|
+
plan.append(
|
|
199
|
+
{
|
|
200
|
+
"plan_id": f"P{len(plan) + 1:04d}",
|
|
201
|
+
"account": email,
|
|
202
|
+
"user_id": user["id"],
|
|
203
|
+
"role": name,
|
|
204
|
+
"role_id": str(role.get("roleId", "")),
|
|
205
|
+
"role_assignment_id": str(grant.get("roleAssignmentId", "")) if grant else "",
|
|
206
|
+
"scope_type": str(grant.get("scopeType", "CUSTOMER")) if grant else "CUSTOMER",
|
|
207
|
+
"super_admin": "Y" if role.get("isSuperAdminRole") else "N",
|
|
208
|
+
"org_unit": user.get("orgUnitPath", "/"),
|
|
209
|
+
"break_glass": "Y" if email in break_glass else "N",
|
|
210
|
+
"mfa_class": mfa_class,
|
|
211
|
+
}
|
|
212
|
+
)
|
|
213
|
+
return records, notes, plan
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def run(config: Config, run_date: date, gws: Gws, days: int = 30) -> list[Path]:
|
|
217
|
+
records, notes, plan = collect(gws, config, days)
|
|
218
|
+
directory = run_dir(config.output_dir, run_date)
|
|
219
|
+
plan_path = write_csv(directory / "1_gws_role-plan.csv", plan, PLAN_FIELDS)
|
|
220
|
+
return [
|
|
221
|
+
plan_path,
|
|
222
|
+
*write_admin_outputs(
|
|
223
|
+
directory,
|
|
224
|
+
source=SOURCE,
|
|
225
|
+
records=records,
|
|
226
|
+
tool="targetzero gws admins",
|
|
227
|
+
run_date=run_date,
|
|
228
|
+
notes=notes,
|
|
229
|
+
),
|
|
230
|
+
]
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Apply the reviewed Google Workspace role plan (1_gws_role-plan.csv). Dry run unless applied.
|
|
3
|
+
|
|
4
|
+
Actions in the plan's action column:
|
|
5
|
+
|
|
6
|
+
revoke remove the role (super admins without an explicit assignment: remove
|
|
7
|
+
super admin status)
|
|
8
|
+
move-ou move the admin into target_org_unit, e.g. /Admins
|
|
9
|
+
restore-role assign the role again (used by rollback)
|
|
10
|
+
restore-super-admin make the user super admin again (used by rollback)
|
|
11
|
+
|
|
12
|
+
Safety: break-glass accounts are never changed, and it refuses to leave fewer than two super
|
|
13
|
+
admins. Every applied change is logged with a rollback plan next to it.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from collections.abc import Callable, Mapping
|
|
19
|
+
from datetime import date
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from targetzero.common.changes import save_change_log
|
|
24
|
+
from targetzero.common.config import Config
|
|
25
|
+
from targetzero.common.output import read_csv, run_dir
|
|
26
|
+
from targetzero.gws.client import Gws
|
|
27
|
+
|
|
28
|
+
PLAN_FIELDS = (
|
|
29
|
+
"plan_id",
|
|
30
|
+
"account",
|
|
31
|
+
"user_id",
|
|
32
|
+
"role",
|
|
33
|
+
"role_id",
|
|
34
|
+
"role_assignment_id",
|
|
35
|
+
"scope_type",
|
|
36
|
+
"super_admin",
|
|
37
|
+
"org_unit",
|
|
38
|
+
"break_glass",
|
|
39
|
+
"mfa_class",
|
|
40
|
+
"action",
|
|
41
|
+
"target_org_unit",
|
|
42
|
+
"justification",
|
|
43
|
+
)
|
|
44
|
+
ACTIONS = ("revoke", "move-ou", "restore-role", "restore-super-admin")
|
|
45
|
+
UNDO = {
|
|
46
|
+
"revoke": "restore-role",
|
|
47
|
+
"restore-role": "revoke",
|
|
48
|
+
"restore-super-admin": "revoke",
|
|
49
|
+
"move-ou": "move-ou",
|
|
50
|
+
}
|
|
51
|
+
MIN_SUPER_ADMINS = 2
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def calls_for(gws: Gws, row: Mapping[str, str]) -> list[tuple[str, Callable[[], Any]]]:
|
|
55
|
+
"""(description, call) pairs for one plan row."""
|
|
56
|
+
directory = gws.directory
|
|
57
|
+
user = row["user_id"] or row["account"]
|
|
58
|
+
action = row["action"]
|
|
59
|
+
if action == "revoke" and row["role_assignment_id"]:
|
|
60
|
+
assignment = row["role_assignment_id"]
|
|
61
|
+
return [
|
|
62
|
+
(
|
|
63
|
+
f"delete role assignment {assignment}",
|
|
64
|
+
lambda: (
|
|
65
|
+
directory.roleAssignments()
|
|
66
|
+
.delete(customer=gws.customer, roleAssignmentId=assignment)
|
|
67
|
+
.execute()
|
|
68
|
+
),
|
|
69
|
+
)
|
|
70
|
+
]
|
|
71
|
+
if action in ("revoke", "restore-super-admin") and row["super_admin"] == "Y":
|
|
72
|
+
status = action == "restore-super-admin"
|
|
73
|
+
return [
|
|
74
|
+
(
|
|
75
|
+
f"set super admin {status} for {row['account']}",
|
|
76
|
+
lambda: (
|
|
77
|
+
directory.users().makeAdmin(userKey=user, body={"status": status}).execute()
|
|
78
|
+
),
|
|
79
|
+
)
|
|
80
|
+
]
|
|
81
|
+
if action == "restore-role":
|
|
82
|
+
body = {"roleId": row["role_id"], "assignedTo": row["user_id"], "scopeType": "CUSTOMER"}
|
|
83
|
+
return [
|
|
84
|
+
(
|
|
85
|
+
f"assign role {row['role']}",
|
|
86
|
+
lambda: (
|
|
87
|
+
directory.roleAssignments().insert(customer=gws.customer, body=body).execute()
|
|
88
|
+
),
|
|
89
|
+
)
|
|
90
|
+
]
|
|
91
|
+
if action == "move-ou":
|
|
92
|
+
target = row["target_org_unit"]
|
|
93
|
+
return [
|
|
94
|
+
(
|
|
95
|
+
f"move to {target}",
|
|
96
|
+
lambda: (
|
|
97
|
+
directory.users().update(userKey=user, body={"orgUnitPath": target}).execute()
|
|
98
|
+
),
|
|
99
|
+
)
|
|
100
|
+
]
|
|
101
|
+
raise ValueError(f"cannot {action} this row")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def apply_plan(
|
|
105
|
+
config: Config, gws: Gws, plan: Path, run_date: date, *, apply: bool = False
|
|
106
|
+
) -> tuple[list[dict[str, str]], list[Path]]:
|
|
107
|
+
rows = [r for r in read_csv(plan) if r.get("action")]
|
|
108
|
+
break_glass = set(config.break_glass("gws"))
|
|
109
|
+
super_admins = len(
|
|
110
|
+
gws.pages(gws.directory.users().list, "users", customer=gws.customer, query="isAdmin=true")
|
|
111
|
+
)
|
|
112
|
+
losing = {
|
|
113
|
+
r["account"].lower()
|
|
114
|
+
for r in rows
|
|
115
|
+
if r["action"] == "revoke"
|
|
116
|
+
and r.get("super_admin") == "Y"
|
|
117
|
+
and r.get("break_glass") != "Y"
|
|
118
|
+
and r["account"].lower() not in break_glass
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
results: list[dict[str, str]] = []
|
|
122
|
+
rollback: list[dict[str, str]] = []
|
|
123
|
+
for row in rows:
|
|
124
|
+
result = {
|
|
125
|
+
"plan_id": row.get("plan_id", ""),
|
|
126
|
+
"account": row["account"],
|
|
127
|
+
"role": row.get("role", ""),
|
|
128
|
+
"action": row["action"],
|
|
129
|
+
"status": "",
|
|
130
|
+
"detail": "",
|
|
131
|
+
}
|
|
132
|
+
account = row["account"].lower()
|
|
133
|
+
refuse = ""
|
|
134
|
+
if row["action"] not in ACTIONS:
|
|
135
|
+
refuse = f"unknown action '{row['action']}'"
|
|
136
|
+
elif row.get("break_glass") == "Y" or account in break_glass:
|
|
137
|
+
refuse = "break-glass account: never changed"
|
|
138
|
+
elif row["action"] == "move-ou" and not row.get("target_org_unit", "").startswith("/"):
|
|
139
|
+
refuse = "move-ou needs target_org_unit, e.g. /Admins"
|
|
140
|
+
elif account in losing and super_admins - len(losing) < MIN_SUPER_ADMINS:
|
|
141
|
+
refuse = (
|
|
142
|
+
f"would leave fewer than {MIN_SUPER_ADMINS} super admins "
|
|
143
|
+
f"({super_admins} now, {len(losing)} planned to go)"
|
|
144
|
+
)
|
|
145
|
+
if refuse:
|
|
146
|
+
results.append(result | {"status": "refused", "detail": refuse})
|
|
147
|
+
continue
|
|
148
|
+
try:
|
|
149
|
+
calls = calls_for(gws, row)
|
|
150
|
+
except ValueError as exc:
|
|
151
|
+
results.append(result | {"status": "refused", "detail": str(exc)})
|
|
152
|
+
continue
|
|
153
|
+
description = " + ".join(d for d, _ in calls)
|
|
154
|
+
if not apply:
|
|
155
|
+
results.append(result | {"status": "dry-run", "detail": f"would {description}"})
|
|
156
|
+
continue
|
|
157
|
+
try:
|
|
158
|
+
for _, call in calls:
|
|
159
|
+
response = call()
|
|
160
|
+
if row["action"] == "restore-role" and isinstance(response, dict):
|
|
161
|
+
row["role_assignment_id"] = str(response.get("roleAssignmentId", ""))
|
|
162
|
+
except Exception as exc:
|
|
163
|
+
results.append(result | {"status": "failed", "detail": str(exc)})
|
|
164
|
+
continue
|
|
165
|
+
results.append(result | {"status": "applied", "detail": description})
|
|
166
|
+
back = {f: row.get(f, "") for f in PLAN_FIELDS}
|
|
167
|
+
back["action"] = UNDO[row["action"]]
|
|
168
|
+
if row["action"] == "move-ou":
|
|
169
|
+
back["target_org_unit"], back["org_unit"] = (
|
|
170
|
+
row.get("org_unit", "/"),
|
|
171
|
+
row["target_org_unit"],
|
|
172
|
+
)
|
|
173
|
+
if (
|
|
174
|
+
row["action"] == "revoke"
|
|
175
|
+
and row.get("super_admin") == "Y"
|
|
176
|
+
and not row["role_assignment_id"]
|
|
177
|
+
):
|
|
178
|
+
back["action"] = "restore-super-admin"
|
|
179
|
+
back["justification"] = f"Rollback of {row['action']} {date.today().isoformat()}"
|
|
180
|
+
rollback.append(back)
|
|
181
|
+
|
|
182
|
+
paths = save_change_log(
|
|
183
|
+
run_dir(config.output_dir, run_date),
|
|
184
|
+
"gws_roles",
|
|
185
|
+
results,
|
|
186
|
+
rollback,
|
|
187
|
+
PLAN_FIELDS,
|
|
188
|
+
dry_run=not apply,
|
|
189
|
+
)
|
|
190
|
+
return results, paths
|
targetzero/gws/client.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Authenticated Admin SDK clients.
|
|
3
|
+
|
|
4
|
+
Two ways to sign in, picked from the credentials file:
|
|
5
|
+
|
|
6
|
+
- Service account with domain-wide delegation ("type": "service_account"):
|
|
7
|
+
impersonates gws.admin_subject. Suited to scheduled runs.
|
|
8
|
+
- OAuth desktop client ("installed" in the file): opens a browser once and
|
|
9
|
+
signs in as the admin running the script. Suited to small tenants.
|
|
10
|
+
|
|
11
|
+
Only read-only scopes are requested by the inventory commands.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from targetzero.common.config import Config, ConfigError
|
|
21
|
+
|
|
22
|
+
READ_SCOPES = (
|
|
23
|
+
"https://www.googleapis.com/auth/admin.directory.user.readonly",
|
|
24
|
+
"https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly",
|
|
25
|
+
"https://www.googleapis.com/auth/admin.directory.domain.readonly",
|
|
26
|
+
"https://www.googleapis.com/auth/admin.reports.audit.readonly",
|
|
27
|
+
"https://www.googleapis.com/auth/admin.reports.usage.readonly",
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
# Only for `targetzero gws apply`. Add these to the domain-wide delegation entry only when you
|
|
32
|
+
# want to make changes, and remove them again afterwards.
|
|
33
|
+
WRITE_SCOPES = (
|
|
34
|
+
*READ_SCOPES,
|
|
35
|
+
"https://www.googleapis.com/auth/admin.directory.user",
|
|
36
|
+
"https://www.googleapis.com/auth/admin.directory.rolemanagement",
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class Gws:
|
|
41
|
+
"""Thin wrapper so tests can replace the API with a fake."""
|
|
42
|
+
|
|
43
|
+
def __init__(self, directory: Any, reports: Any, customer: str) -> None:
|
|
44
|
+
self.directory = directory
|
|
45
|
+
self.reports = reports
|
|
46
|
+
self.customer = customer
|
|
47
|
+
|
|
48
|
+
def pages(self, method: Any, key: str, **params: Any) -> list[dict[str, Any]]:
|
|
49
|
+
items: list[dict[str, Any]] = []
|
|
50
|
+
token = None
|
|
51
|
+
while True:
|
|
52
|
+
# Some list calls (domains) do not accept pageToken at all.
|
|
53
|
+
extra: dict[str, str] = {"pageToken": token} if token else {}
|
|
54
|
+
response = method(**params, **extra).execute()
|
|
55
|
+
items += response.get(key, [])
|
|
56
|
+
token = response.get("nextPageToken")
|
|
57
|
+
if not token:
|
|
58
|
+
return items
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def connect(config: Config, scopes: tuple[str, ...] = READ_SCOPES) -> Gws:
|
|
62
|
+
try:
|
|
63
|
+
from google.oauth2 import service_account
|
|
64
|
+
from google_auth_oauthlib.flow import InstalledAppFlow
|
|
65
|
+
from googleapiclient.discovery import build
|
|
66
|
+
except ImportError as exc:
|
|
67
|
+
raise ConfigError(
|
|
68
|
+
"Google Workspace support is not installed: pip install 'targetzero[gws]'"
|
|
69
|
+
) from exc
|
|
70
|
+
|
|
71
|
+
settings = config.data.get("gws", {})
|
|
72
|
+
file = settings.get("credentials_file", "")
|
|
73
|
+
if not file:
|
|
74
|
+
raise ConfigError("gws.credentials_file is not set in targetzero.yaml")
|
|
75
|
+
path = Path(file).expanduser()
|
|
76
|
+
if not path.is_absolute():
|
|
77
|
+
path = config.path.parent / path
|
|
78
|
+
info = json.loads(path.read_text(encoding="utf-8"))
|
|
79
|
+
credentials: Any
|
|
80
|
+
if info.get("type") == "service_account":
|
|
81
|
+
subject = settings.get("admin_subject", "")
|
|
82
|
+
if not subject:
|
|
83
|
+
raise ConfigError("gws.admin_subject is required with a service account")
|
|
84
|
+
credentials = service_account.Credentials.from_service_account_info( # type: ignore[no-untyped-call]
|
|
85
|
+
info, scopes=list(scopes), subject=subject
|
|
86
|
+
)
|
|
87
|
+
elif "installed" in info:
|
|
88
|
+
flow = InstalledAppFlow.from_client_config(info, scopes=list(scopes))
|
|
89
|
+
credentials = flow.run_local_server(port=0, open_browser=True)
|
|
90
|
+
else:
|
|
91
|
+
raise ConfigError(f"{path} is neither a service account key nor an OAuth desktop client")
|
|
92
|
+
directory = build("admin", "directory_v1", credentials=credentials, cache_discovery=False)
|
|
93
|
+
reports = build("admin", "reports_v1", credentials=credentials, cache_discovery=False)
|
|
94
|
+
return Gws(directory, reports, settings.get("customer_id", "my_customer"))
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Google Workspace domains, as a seed for `targetzero external discover` (Zero 5)."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from datetime import date
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from targetzero.common.config import Config
|
|
10
|
+
from targetzero.common.output import run_dir, write_csv
|
|
11
|
+
from targetzero.gws.client import Gws
|
|
12
|
+
|
|
13
|
+
FIELDS = ("domain", "verified", "primary", "kind")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def run(config: Config, run_date: date, gws: Gws) -> list[Path]:
|
|
17
|
+
rows = []
|
|
18
|
+
for d in gws.pages(gws.directory.domains().list, "domains", customer=gws.customer):
|
|
19
|
+
rows.append(
|
|
20
|
+
{
|
|
21
|
+
"domain": d["domainName"].lower(),
|
|
22
|
+
"verified": "Y" if d.get("verified") else "N",
|
|
23
|
+
"primary": "Y" if d.get("isPrimary") else "N",
|
|
24
|
+
"kind": "domain",
|
|
25
|
+
}
|
|
26
|
+
)
|
|
27
|
+
for alias in d.get("domainAliases", []):
|
|
28
|
+
rows.append(
|
|
29
|
+
{
|
|
30
|
+
"domain": alias["domainAliasName"].lower(),
|
|
31
|
+
"verified": "Y" if alias.get("verified") else "N",
|
|
32
|
+
"primary": "N",
|
|
33
|
+
"kind": "alias",
|
|
34
|
+
}
|
|
35
|
+
)
|
|
36
|
+
return [write_csv(run_dir(config.output_dir, run_date) / "5_gws_domains.csv", rows, FIELDS)]
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Check registers/exceptions.csv against the Target 0 rules.
|
|
3
|
+
|
|
4
|
+
An exception is valid only when it says what and why, names a compensating
|
|
5
|
+
control, is signed by a manager on a date, and expires at most 90 days after
|
|
6
|
+
signing. Anything else is a gap, not an exception.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from datetime import date
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from targetzero.common.output import read_csv
|
|
16
|
+
from targetzero.common.schema import validate
|
|
17
|
+
|
|
18
|
+
REQUIRED = (
|
|
19
|
+
"description",
|
|
20
|
+
"compensating_control",
|
|
21
|
+
"accepted_by",
|
|
22
|
+
"signed_date",
|
|
23
|
+
"expiry_date",
|
|
24
|
+
"items",
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class ExceptionRecord:
|
|
30
|
+
id: str
|
|
31
|
+
zero: int | None
|
|
32
|
+
items: set[str]
|
|
33
|
+
expiry_date: date | None
|
|
34
|
+
problems: list[str] = field(default_factory=list)
|
|
35
|
+
|
|
36
|
+
@property
|
|
37
|
+
def valid(self) -> bool:
|
|
38
|
+
return not self.problems
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _parse_date(value: str) -> date | None:
|
|
42
|
+
try:
|
|
43
|
+
return date.fromisoformat(value) if value else None
|
|
44
|
+
except ValueError:
|
|
45
|
+
return None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def check_row(row: dict[str, str], run_date: date, max_days: int) -> ExceptionRecord:
|
|
49
|
+
problems = validate(row, "exceptions")
|
|
50
|
+
for column in REQUIRED:
|
|
51
|
+
if not row.get(column):
|
|
52
|
+
problems.append(f"{column} is empty")
|
|
53
|
+
signed = _parse_date(row.get("signed_date", ""))
|
|
54
|
+
expiry = _parse_date(row.get("expiry_date", ""))
|
|
55
|
+
if signed and signed > run_date:
|
|
56
|
+
problems.append(f"signed_date {signed} is in the future")
|
|
57
|
+
if expiry and expiry < run_date:
|
|
58
|
+
problems.append(f"expired on {expiry}")
|
|
59
|
+
if signed and expiry:
|
|
60
|
+
if expiry <= signed:
|
|
61
|
+
problems.append("expiry_date is not after signed_date")
|
|
62
|
+
elif (expiry - signed).days > max_days:
|
|
63
|
+
problems.append(f"runs {(expiry - signed).days} days; the maximum is {max_days}")
|
|
64
|
+
zero = row.get("zero", "")
|
|
65
|
+
items = {i.strip() for i in row.get("items", "").split(";") if i.strip()}
|
|
66
|
+
return ExceptionRecord(
|
|
67
|
+
id=row.get("id") or "(no id)",
|
|
68
|
+
zero=int(zero) if zero.isdigit() else None,
|
|
69
|
+
items=items,
|
|
70
|
+
expiry_date=expiry,
|
|
71
|
+
problems=sorted(set(problems), key=problems.index),
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def load_exceptions(path: Path, run_date: date, max_days: int = 90) -> list[ExceptionRecord]:
|
|
76
|
+
"""Read and check every exception. A missing file means no exceptions."""
|
|
77
|
+
if not path.exists():
|
|
78
|
+
return []
|
|
79
|
+
records = [check_row(row, run_date, max_days) for row in read_csv(path)]
|
|
80
|
+
seen: set[str] = set()
|
|
81
|
+
for record in records:
|
|
82
|
+
if record.id in seen:
|
|
83
|
+
record.problems.append("duplicate id")
|
|
84
|
+
seen.add(record.id)
|
|
85
|
+
return records
|