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?

Amazon Cognitoの認証ログをCloudTrailから追う

Last updated at Posted at 2025-04-17

前置き

GenUの環境でPoCしていたのですが、直近でのユーザの使用履歴を確認したいと思いました。このアプリケーションはユーザ認証にCognitoを使っています。
本来であればCloudWatchLogsに認証ログを出力するのが一般的なんでしょう。しかしデフォルトではログは有効化されていなく、CloudTrailから追うか~となりました。

CloudTrailで検索して、検索結果をjsonで保存

CloudTrailのイベント履歴のイベントソース「cognito-idp.amazonaws.com」の「InitiateAuth」から認証履歴を追うことができます。
image.png
CloudTrailは他のログもたくさん出るし、探すの大変。ってことでAWS CLIのlookup-eventsを使用しました。

aws cloudtrail lookup-events \
  --lookup-attributes AttributeKey=EventSource,AttributeValue=cognito-idp.amazonaws.com \
  --max-results 50 \
  --query "Events[?EventName=='InitiateAuth'].{Time:EventTime, User:Username, Source:Resources[0].ResourceName}" \
  --output table

ここで注意したいのがCloudTrailの「lookup-events」APIは最大50件/リクエストの仕様であることです。
つまりオプションの「--max-results」を100件にしても意味ないし、このオプション自体を削除してもデフォルトの50件になってしまうということです。

ということで、lookup-eventsのオプション「--next-token」を使ったスクリプトを生成AI君に作らせました。

#!/bin/bash

START="2025-01-15T00:00:00Z"
END="2025-04-15T23:59:59Z"
OUTFILE="cognito_events.json"

# 最初のページ
echo "{" > "$OUTFILE"
aws cloudtrail lookup-events \
  --lookup-attributes AttributeKey=EventSource,AttributeValue=cognito-idp.amazonaws.com \
  --start-time "$START" \
  --end-time "$END" \
  --max-results 50 \
  --output json > first_page.json

# 書き出し
jq '.Events' first_page.json > events_array.json
NEXT_TOKEN=$(jq -r '.NextToken' first_page.json)

# 追加ページがあればループ
while [[ "$NEXT_TOKEN" != "null" && "$NEXT_TOKEN" != "" ]]; do
    echo "Fetching next page..."
    aws cloudtrail lookup-events \
      --lookup-attributes AttributeKey=EventSource,AttributeValue=cognito-idp.amazonaws.com \
      --start-time "$START" \
      --end-time "$END" \
      --max-results 50 \
      --next-token "$NEXT_TOKEN" \
      --output json > next_page.json

    # マージして連結
    jq '.Events' next_page.json >> events_array.json
    NEXT_TOKEN=$(jq -r '.NextToken' next_page.json)
done

# まとめて JSON として整形
jq -s '{Events: add}' events_array.json > "$OUTFILE"

echo "✅ 90日分のCognitoイベントを $OUTFILE に保存しました!"

jqコマンドを使って抽出。その結果からユーザを特定

今回はどのユーザが認証したかの履歴を追いたかったので「Sub:」の文字列を抽出しました。

jq '.Events[] | select(.EventName == "InitiateAuth") | .CloudTrailEvent | fromjson | {Time: .eventTime, Sub: .additionalEventData.sub}' cognito_events.json

あとは抽出されたユーザ名からどのユーザが使用しているかを調べることができました。

image.png

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?