Add support for proxy to Azure plugin.

This commit is contained in:
Marsell Kukuljevic 2024-11-07 15:54:45 +01:00
parent 270d9ac22c
commit d4b0c9497d
9 changed files with 47 additions and 29 deletions

Binary file not shown.

View File

@ -95,7 +95,7 @@ def check_keyvault(item, params, section):
state=State.UNKNOWN,
summary="Capacity: N/A",
)
if latency is not None:
yield Result(
@ -112,7 +112,7 @@ def check_keyvault(item, params, section):
state=State.UNKNOWN,
summary="Latency: N/A",
)
if hits is not None:
yield Metric(

View File

@ -38,7 +38,14 @@ def get_url(req, default):
raise e
def get_token(tenant, username, password):
def set_proxy(req, proxy):
if proxy is None or proxy == '':
return
match = re.match('(https?)://(.+?)/?$', proxy, re.I)
req.set_proxy(match[2], match[1].lower())
def get_token(tenant, username, password, proxy):
data = parse.urlencode({
'username': username,
'password': password,
@ -52,6 +59,7 @@ def get_token(tenant, username, password):
req = request.Request(f'https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token',
data=str.encode(data))
set_proxy(req, proxy)
res = get_url(req, None)
if res is None:
@ -62,31 +70,32 @@ def get_token(tenant, username, password):
return token
def get_json(token, path, version='2023-07-01'):
def get_json(token, proxy, path, version='2023-07-01'):
url = f"https://management.azure.com{path}{'?' in path and '&' or '?'}api-version={version}"
req = request.Request(url, headers={'Authorization': f'Bearer {token}'})
set_proxy(req, proxy)
res = get_url(req, "[]")
data = json.loads(res)
return data['value']
def list_subscriptions(token):
return get_json(token, '/subscriptions')
def list_subscriptions(token, proxy):
return get_json(token, proxy, '/subscriptions')
def list_vaults(token, subscription):
return get_json(token, f'/subscriptions/{subscription}/resources?$filter=resourceType%20eq%20%27Microsoft.KeyVault%2Fvaults%27')
def list_vaults(token, proxy, subscription):
return get_json(token, proxy, f'/subscriptions/{subscription}/resources?$filter=resourceType%20eq%20%27Microsoft.KeyVault%2Fvaults%27')
def list_firewalls(token, subscription):
return get_json(token, f'/subscriptions/{subscription}/resources?$filter=resourceType%20eq%20%27Microsoft.Network%2FazureFirewalls%27')
def list_firewalls(token, proxy, subscription):
return get_json(token, proxy, f'/subscriptions/{subscription}/resources?$filter=resourceType%20eq%20%27Microsoft.Network%2FazureFirewalls%27')
def list_defender_alerts(token, subscription):
return get_json(token, f'/subscriptions/{subscription}/providers/Microsoft.Security/alerts', '2022-01-01')
def list_defender_alerts(token, proxy, subscription):
return get_json(token, proxy, f'/subscriptions/{subscription}/providers/Microsoft.Security/alerts', '2022-01-01')
def get_recent_metrics(token, path, metrics):
def get_recent_metrics(token, proxy, path, metrics):
end = datetime.now()
start = end - timedelta(minutes=2)
@ -94,7 +103,7 @@ def get_recent_metrics(token, path, metrics):
end_str = end.isoformat().split('.')[0] + 'Z'
metrics_str = ','.join(metrics)
return get_json(token, f'{path}/providers/microsoft.insights/metrics?metricnames={metrics_str}&timespan={start_str}/{end_str}', '2023-10-01')
return get_json(token, proxy, f'{path}/providers/microsoft.insights/metrics?metricnames={metrics_str}&timespan={start_str}/{end_str}', '2023-10-01')
def metrics_to_lookup(metrics):
@ -112,25 +121,26 @@ def metrics_to_lookup(metrics):
def get_args(argv):
if len(argv) != 5 or argv[1] not in ['keyvault', 'firewall', 'defender']:
print(f"{sys.argv[0]} <command> <tenand ID> <username> <password>", file=sys.stderr)
if (len(argv) != 5 and len(argv) != 6) or argv[1] not in ['keyvault', 'firewall', 'defender']:
print(f"{sys.argv[0]} <command> <tenant ID> <username> <password> <proxy>", file=sys.stderr)
print(f"Valid commands are: 'keyvault', 'firewall', 'defender'", file=sys.stderr)
print(f"Proxy is an optional argument", file=sys.stderr)
exit(1)
return argv[1], argv[2], argv[3], argv[4]
return argv[1], argv[2], argv[3], argv[4], (argv[5] if len(argv) == 6 else None)
def print_json(obj):
print(json.dumps(obj))
command, tenant, username, password = get_args(sys.argv)
token = get_token(tenant, username, password)
command, tenant, username, password, proxy = get_args(sys.argv)
token = get_token(tenant, username, password, proxy)
for subscription in list_subscriptions(token):
for subscription in list_subscriptions(token, proxy):
subscription_id = subscription['subscriptionId']
if command == 'defender':
for alert in list_defender_alerts(token, subscription_id):
for alert in list_defender_alerts(token, proxy, subscription_id):
properties = alert['properties']
status = properties['status']
@ -152,8 +162,8 @@ for subscription in list_subscriptions(token):
})
elif command == 'firewall':
for firewall in list_firewalls(token, subscription_id):
metrics = get_recent_metrics(token, firewall['id'], FIREWALL_METRICS)
for firewall in list_firewalls(token, proxy, subscription_id):
metrics = get_recent_metrics(token, proxy, firewall['id'], FIREWALL_METRICS)
print_json({
'type': command,
'name': firewall['name'],
@ -163,8 +173,8 @@ for subscription in list_subscriptions(token):
})
elif command == 'keyvault':
for vault in list_vaults(token, subscription_id):
metrics = get_recent_metrics(token, vault['id'], VAULT_METRICS)
for vault in list_vaults(token, proxy, subscription_id):
metrics = get_recent_metrics(token, proxy, vault['id'], VAULT_METRICS)
print_json({
'type': command,
'name': vault['name'],

View File

@ -3,4 +3,4 @@
echo '<<<azure_defender:sep(0)>>>'
dir=$(dirname -- "${BASH_SOURCE[0]}")
"$dir"/agent_azure_common defender "$1" "$2" "$3"
"$dir"/agent_azure_common defender "$1" "$2" "$3" "$4"

View File

@ -3,4 +3,4 @@
echo '<<<azure_firewall:sep(0)>>>'
dir=$(dirname -- "${BASH_SOURCE[0]}")
"$dir"/agent_azure_common firewall "$1" "$2" "$3"
"$dir"/agent_azure_common firewall "$1" "$2" "$3" "$4"

View File

@ -3,4 +3,4 @@
echo '<<<azure_keyvault:sep(0)>>>'
dir=$(dirname -- "${BASH_SOURCE[0]}")
"$dir"/agent_azure_common keyvault "$1" "$2" "$3"
"$dir"/agent_azure_common keyvault "$1" "$2" "$3" "$4"

View File

@ -16,7 +16,8 @@ def agent_azure_args(params, hostname, ipaddress):
return [
params["tenant"],
params["username"],
password
password,
params.get("proxy") or "" # optional
]
special_agent_info["azure_keyvault"] = agent_azure_args

View File

@ -48,6 +48,13 @@ def _discovery(title):
allow_empty=False,
),
),
(
"proxy",
TextInput(
title=_("Proxy"),
),
),
],
)