0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

GCPでクレデンシャルが発行されたことを検知したい

Posted at

クレデンシャル発行を検知したい場合があったので、以下のように作ってみました

全体像
image.png

フィルター条件はこちらになります

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'))
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?