Created
August 13, 2021 07:27
-
-
Save kaysush/511bb01eb22a5a75a6547d94517baa8c to your computer and use it in GitHub Desktop.
Google Cloud Function to filter "Open To Internet" firewall rules
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import base64 | |
import json | |
import requests | |
def filter_rule(event, context): | |
"""Triggered from a message on a Cloud Pub/Sub topic. | |
Args: | |
event (dict): Event payload. | |
context (google.cloud.functions.Context): Metadata for the event. | |
""" | |
URL = "https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX" | |
HEADERS = {"content-type":"application/json"} | |
pubsub_message = base64.b64decode(event['data']).decode('utf-8') | |
parsed = json.loads(pubsub_message) | |
print(parsed) | |
data = get_data(parsed) | |
source_ranges = data["sourceRanges"] | |
if '0.0.0.0/0' in source_ranges: | |
print('Found an open to internet rule') | |
name = data["name"] | |
network = data["network"] | |
creation_time = data["creationTimestamp"] | |
message = f"An open to internet firewall rule *{name}* created in network {network} at *{creation_time}*." | |
salck_payload = json.dumps({"text" : message}) | |
r = requests.post(URL, data=salck_payload, headers=HEADERS) | |
print(r.status_code, r.reason) | |
def get_data(parsed): | |
try: | |
return parsed["asset"]["resource"]["data"] | |
except: | |
return parsed["priorAsset"]["resource"]["data"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment