-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenable_disabled_privilege_zone_rules.py
More file actions
198 lines (154 loc) · 5.53 KB
/
Copy pathenable_disabled_privilege_zone_rules.py
File metadata and controls
198 lines (154 loc) · 5.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
#!/usr/bin/env python3
"""
Enable disabled BloodHound Enterprise / BloodHound CE Privilege Zone Rules.
This script enumerates asset group tags, finds disabled tag selectors, and enables them.
By default it runs in dry-run mode. Pass --apply to make changes.
Authentication:
1. API token signed auth:
--token-id "$BHE_TOKEN_ID" --token-key "$BHE_TOKEN_KEY"
2. Temporary browser JWT:
--jwt "$BHE_JWT"
Example:
python enable_disabled_privilege_zone_rules.py \
--tenant-url https://example.bloodhoundenterprise.io \
--token-id "$BHE_TOKEN_ID" \
--token-key "$BHE_TOKEN_KEY" \
--apply
"""
import argparse
import base64
import datetime as dt
import hashlib
import hmac
import json
import sys
import requests
def sign_headers(token_id, token_key, method, uri, body=b""):
now = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
key = token_key.encode()
op_key = hmac.new(key, f"{method.upper()}{uri}".encode(), hashlib.sha256).digest()
date_key = hmac.new(op_key, now[:13].encode(), hashlib.sha256).digest()
sig = hmac.new(date_key, body or b"", hashlib.sha256).digest()
return {
"Authorization": f"bhesignature {token_id}",
"RequestDate": now,
"Signature": base64.b64encode(sig).decode(),
}
class BHE:
def __init__(self, base_url, jwt=None, token_id=None, token_key=None):
self.base_url = base_url.rstrip("/")
self.jwt = jwt
self.token_id = token_id
self.token_key = token_key
self.session = requests.Session()
def request(self, method, path, params=None, payload=None):
body = json.dumps(payload).encode() if payload is not None else None
headers = {"Accept": "application/json"}
if payload is not None:
headers["Content-Type"] = "application/json"
req = requests.Request(
method=method,
url=self.base_url + path,
params=params,
data=body,
headers=headers,
)
prepped = self.session.prepare_request(req)
# Signed auth must include the query string in the request URI.
uri_to_sign = prepped.path_url
if self.jwt:
prepped.headers["Authorization"] = f"Bearer {self.jwt}"
else:
prepped.headers.update(
sign_headers(
self.token_id,
self.token_key,
method,
uri_to_sign,
body or b"",
)
)
resp = self.session.send(prepped, timeout=60)
if not resp.ok:
print(f"\nHTTP {resp.status_code} for {method} {uri_to_sign}", file=sys.stderr)
print(resp.text, file=sys.stderr)
resp.raise_for_status()
return resp.json() if resp.content else {}
def get_all(self, path, key, params=None, limit=1000):
skip = 0
while True:
q = dict(params or {})
q.update({"skip": skip, "limit": limit})
data = self.request("GET", path, params=q).get("data", {})
items = data.get(key, [])
if not items:
break
yield from items
if len(items) < limit:
break
skip += limit
def main():
parser = argparse.ArgumentParser(
description="Enable all disabled BloodHound Enterprise Privilege Zone Rules."
)
parser.add_argument(
"--tenant-url",
required=True,
help="Example: https://shinybits.bloodhoundenterprise.io",
)
parser.add_argument("--jwt", help="Temporary browser JWT bearer token")
parser.add_argument("--token-id", help="BHE API token ID")
parser.add_argument("--token-key", help="BHE API token key")
parser.add_argument(
"--apply",
action="store_true",
help="Actually enable rules. Default is dry-run.",
)
args = parser.parse_args()
if not args.jwt and not (args.token_id and args.token_key):
parser.error("Provide either --jwt or both --token-id and --token-key")
bhe = BHE(
base_url=args.tenant_url,
jwt=args.jwt,
token_id=args.token_id,
token_key=args.token_key,
)
disabled_rules = []
tags = list(
bhe.get_all(
"/api/v2/asset-group-tags",
"tags",
params={"counts": "true"},
)
)
for tag in tags:
tag_id = tag["id"]
tag_name = tag.get("name", "<unnamed tag>")
selectors = bhe.get_all(
f"/api/v2/asset-group-tags/{tag_id}/selectors",
"selectors",
)
for selector in selectors:
if selector.get("disabled_at"):
disabled_rules.append((tag, selector))
print(
f"Found disabled rule: "
f"tag='{tag_name}' tag_id={tag_id} "
f"selector='{selector.get('name')}' selector_id={selector['id']}"
)
print(f"\nFound {len(disabled_rules)} disabled rule(s).")
if not args.apply:
print("Dry-run only. Re-run with --apply to enable these rules.")
return
for tag, selector in disabled_rules:
tag_id = tag["id"]
selector_id = selector["id"]
bhe.request(
"PATCH",
f"/api/v2/asset-group-tags/{tag_id}/selectors/{selector_id}",
payload={"disabled": False},
)
print(f"Enabled selector_id={selector_id} on tag_id={tag_id}")
print("\nDone.")
if __name__ == "__main__":
main()