クレデンシャル発行を検知したい場合があったので、以下のように作ってみました
フィルター条件はこちらになります
Liggingフィルター条件
logName="projects/[PROJECT ID]/logs/cloudaudit.googleapis.com%2Factivity"
protoPayload.methodName="google.iam.admin.v1.CreateServiceAccountKey"
クレデンシャルを作られたログのみをpubsubにsinkします
PROJECT_ID=シンクを作るproject
gcloud config set project ${PROJECT_ID}
gcloud logging sinks create credential-create-sink pubsub.googleapis.com/projects/${PROJECT_ID}/topics/credentials_notification --log-filter="logName=¥"projects/${PROJECT_ID}/logs/cloudaudit.googleapis.com%2Factivity¥" protoPayload.methodName=¥"google.iam.admin.v1.CreateServiceAccountKey¥""
SERVICE_ACCOUNT=sinkで作成されたサービスアカウント
gcloud pubsub topics add-iam-policy-binding syslog-sink-topic \
--member serviceAccount:${SERVICE_ACCOUNT} --role roles/pubsub.publisher
pub/subに来た通知をslackに通知します
サンプルプログラム
import base64, os, json, time
import urllib.request
channel = os.environ.get('SLACK_CHANNEL')
url = os.environ.get('WEBHOOK_URL')
def send_slack(payload):
headers = {'Content-Type': 'application/json'}
req = urllib.request.Request(url, data=payload, headers=headers, method='POST')
try:
with urllib.request.urlopen(req) as res:
body = res.read()
except urllib.error.HTTPError as err:
print(err.code)
except urllib.error.URLError as err:
print(err.reason)
def main_handler(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.
"""
pubsub_message = json.loads(base64.b64decode(event['data']).decode('utf-8'))
message = """
TimeStamp: %s
CreateUser: %s
Project: %s
ServiceAccount: %s
""" % (
pubsub_message[u'receiveTimestamp'],
pubsub_message[u'protoPayload'][u'authenticationInfo'][u'principalEmail'],
pubsub_message[u'resource'][u'labels'][u'project_id'],
pubsub_message[u'resource'][u'labels'][u'email_id']
)
print(message)
payload={
'channel': channel,
'username': 'Credential informer',
'attachments': [{
'pretext': 'Credential created.',
'color': '#00F35A',
'text': message,
}]
}
send_slack(json.dumps(payload).encode('utf-8'))