ServiceNow 監査ログ

以下でサポートされています。

このドキュメントでは、複数の方法を使用して ServiceNow 監査ログを Google Security Operations に取り込む方法について説明します。

オプション A: Cloud Run 関数を使用した GCS

この方法では、Cloud Run functions を使用して ServiceNow REST API に監査ログを定期的にクエリし、GCS バケットに保存します。Google Security Operations は、GCS バケットからログを収集します。

始める前に

次の前提条件を満たしていることを確認します。

  • Google SecOps インスタンス
  • 適切なロール(通常は admin または sys_audit テーブルへの読み取りアクセス権を持つユーザー)による ServiceNow テナントまたは API への特権アクセス
  • Cloud Storage API が有効になっている GCP プロジェクト
  • GCS バケットを作成および管理する権限
  • GCS バケットの IAM ポリシーを管理する権限
  • Cloud Run サービス、Pub/Sub トピック、Cloud Scheduler ジョブを作成する権限

ServiceNow の前提条件(ID、API キー、組織 ID、トークン)を収集する

  1. ServiceNow 管理コンソールにログインします。
  2. [System Security]> [Users and Groups] > [Users] に移動します。
  3. 新しいユーザーを作成するか、監査ログにアクセスするための適切な権限を持つ既存のユーザーを選択します。
  4. 次の詳細をコピーして安全な場所に保存します。

    • ユーザー名
    • パスワード
    • インスタンスの URL(例: https://instance.service-now.com

管理者以外のユーザーの ACL を構成する

管理者以外のユーザー アカウントを使用する場合は、カスタム アクセス制御リスト(ACL)を作成して、sys_audit テーブルへの読み取りアクセス権を付与する必要があります。

  1. 管理者として ServiceNow 管理コンソールにログインします。
  2. [System Security] > [Access Control(ACL)] に移動します。
  3. [New] をクリックします。
  4. 次の構成の詳細を指定します。
    • Type: [record] を選択します。
    • オペレーション: [読み取り] を選択します。
    • 名前: 「sys_audit」と入力します。
    • 説明: 「Allow read access to sys_audit table for Chronicle integration」と入力します。
  5. [Requires role] フィールドに、インテグレーション ユーザーに割り当てられたロール(chronicle_reader など)を追加します。
  6. [送信] をクリックします。
  7. ACL が有効で、ユーザーが sys_audit テーブルをクエリできることを確認します。

Google Cloud Storage バケットを作成する

  1. Google Cloud Console に移動します。
  2. プロジェクトを選択するか、新しいプロジェクトを作成します。
  3. ナビゲーション メニューで、[Cloud Storage > バケット] に移動します。
  4. [バケットを作成] をクリックします。
  5. 次の構成情報を提供してください。

    設定
    バケットに名前を付ける グローバルに一意の名前(servicenow-audit-logs など)を入力します。
    ロケーション タイプ ニーズに基づいて選択します(リージョン、デュアルリージョン、マルチリージョン)。
    ロケーション ロケーションを選択します(例: us-central1)。
    ストレージ クラス Standard(頻繁にアクセスされるログにおすすめ)
    アクセス制御 均一(推奨)
    保護ツール 省略可: オブジェクトのバージョニングまたは保持ポリシーを有効にする
  6. [作成] をクリックします。

Cloud Run functions のサービス アカウントを作成する

Cloud Run 関数には、GCS バケットに書き込み、Pub/Sub によって呼び出される権限を持つサービス アカウントが必要です。

サービス アカウントの作成

  1. GCP Console で、[IAM と管理>サービス アカウント] に移動します。
  2. [サービス アカウントを作成] をクリックします。
  3. 次の構成の詳細を指定します。
    • サービス アカウント名: 「servicenow-audit-collector-sa」と入力します。
    • サービス アカウントの説明: 「Service account for Cloud Run function to collect ServiceNow audit logs」と入力します。
  4. [作成して続行] をクリックします。
  5. [このサービス アカウントにプロジェクトへのアクセスを許可する] セクションで、次のロールを追加します。
    1. [ロールを選択] をクリックします。
    2. [ストレージ オブジェクト管理者] を検索して選択します。
    3. [+ 別のロールを追加] をクリックします。
    4. [Cloud Run 起動元] を検索して選択します。
    5. [+ 別のロールを追加] をクリックします。
    6. [Cloud Functions 起動元] を検索して選択します。
  6. [続行] をクリックします。
  7. [完了] をクリックします。

これらのロールは、次の目的で必要です。

  • Storage オブジェクト管理者: ログを GCS バケットに書き込み、状態ファイルを管理する
  • Cloud Run 起動元: Pub/Sub が関数を呼び出すことを許可する
  • Cloud Functions 起動元: 関数の呼び出しを許可する

GCS バケットに対する IAM 権限を付与する

GCS バケットに対する書き込み権限をサービス アカウントに付与します。

  1. [Cloud Storage] > [バケット] に移動します。
  2. バケット名をクリックします。
  3. [権限] タブに移動します。
  4. [アクセス権を付与] をクリックします。
  5. 次の構成の詳細を指定します。
    • プリンシパルを追加: サービス アカウントのメールアドレス(例: servicenow-audit-collector-sa@PROJECT_ID.iam.gserviceaccount.com)を入力します。
    • ロールを割り当てる: [Storage オブジェクト管理者] を選択します。
  6. [保存] をクリックします。

Pub/Sub トピックの作成

Cloud Scheduler がパブリッシュし、Cloud Run functions がサブスクライブする Pub/Sub トピックを作成します。

  1. GCP Console で、[Pub/Sub> トピック] に移動します。
  2. [トピックを作成] をクリックします。
  3. 次の構成の詳細を指定します。
    • トピック ID: 「servicenow-audit-trigger」と入力します。
    • その他の設定はデフォルトのままにします。
  4. [作成] をクリックします。

ログを収集する Cloud Run 関数を作成する

Cloud Run 関数は、Cloud Scheduler からの Pub/Sub メッセージによってトリガーされ、ServiceNow API からログを取得して GCS に書き込みます。

  1. GCP Console で、[Cloud Run] に移動します。
  2. [サービスを作成] をクリックします。
  3. [関数] を選択します(インライン エディタを使用して関数を作成します)。
  4. [構成] セクションで、次の構成の詳細を指定します。

    設定
    サービス名 servicenow-audit-collector
    リージョン GCS バケットと一致するリージョンを選択します(例: us-central1)。
    ランタイム [Python 3.12] 以降を選択します。
  5. [トリガー(省略可)] セクションで、次の操作を行います。

    1. [+ トリガーを追加] をクリックします。
    2. [Cloud Pub/Sub] を選択します。
    3. [Cloud Pub/Sub トピックを選択してください] で、Pub/Sub トピック(servicenow-audit-trigger)を選択します。
    4. [保存] をクリックします。
  6. [認証] セクションで、次の操作を行います。

    1. [認証が必要] を選択します。
    2. Identity and Access Management(IAM)を確認します。
  7. 下にスクロールして、[コンテナ、ネットワーキング、セキュリティ] を開きます。

  8. [セキュリティ] タブに移動します。

    • サービス アカウント: サービス アカウントを選択します(servicenow-audit-collector-sa)。
  9. [コンテナ] タブに移動します。

    1. [変数とシークレット] をクリックします。
    2. 環境変数ごとに [+ 変数を追加] をクリックします。
    変数名 値の例 説明
    GCS_BUCKET servicenow-audit-logs GCS バケット名
    GCS_PREFIX audit-logs ログファイルの接頭辞
    STATE_KEY audit-logs/state.json 状態ファイルのパス
    API_BASE_URL https://instance.service-now.com ServiceNow インスタンスの URL
    API_USERNAME your-username ServiceNow ユーザー名
    API_PASSWORD your-password ServiceNow のパスワード
    PAGE_SIZE 1000 1 ページあたりのレコード数
    MAX_PAGES 1000 取得する最大ページ数
  10. [変数とシークレット] セクションで、[リクエスト] まで下にスクロールします。

    • リクエストのタイムアウト: 600 秒(10 分)を入力します。
  11. [設定] タブに移動します。

    • [リソース] セクションで次の操作を行います。
      • メモリ: 512 MiB 以上を選択します。
      • CPU: [1] を選択します。
  12. [リビジョン スケーリング] セクションで、次の操作を行います。

    • [インスタンスの最小数] に「0」と入力します。
    • インスタンスの最大数: 100 と入力します(または、予想される負荷に基づいて調整します)。
  13. [作成] をクリックします。

  14. サービスが作成されるまで待ちます(1 ~ 2 分)。

  15. サービスを作成すると、インライン コードエディタが自動的に開きます。

関数コードを追加する

  1. [エントリ ポイント] フィールドに「main」と入力します。
  2. インライン コードエディタで、次の 2 つのファイルを作成します。

    • 最初のファイル: main.py:

          import functions_framework
          from google.cloud import storage
          import json
          import os
          import urllib3
          from datetime import datetime, timezone, timedelta
          import time
          import base64
      
          # Initialize HTTP client with timeouts
          http = urllib3.PoolManager(
              timeout=urllib3.Timeout(connect=5.0, read=30.0),
              retries=False,
          )
      
          # Initialize Storage client
          storage_client = storage.Client()
      
          # Environment variables
          GCS_BUCKET = os.environ.get('GCS_BUCKET')
          GCS_PREFIX = os.environ.get('GCS_PREFIX', 'audit-logs')
          STATE_KEY = os.environ.get('STATE_KEY', 'audit-logs/state.json')
          API_BASE = os.environ.get('API_BASE_URL')
          USERNAME = os.environ.get('API_USERNAME')
          PASSWORD = os.environ.get('API_PASSWORD')
          PAGE_SIZE = int(os.environ.get('PAGE_SIZE', '1000'))
          MAX_PAGES = int(os.environ.get('MAX_PAGES', '1000'))
      
          def parse_datetime(value: str) -> datetime:
              """Parse ServiceNow datetime string to datetime object."""
              # ServiceNow format: YYYY-MM-DD HH:MM:SS
              try:
                  return datetime.strptime(value, '%Y-%m-%d %H:%M:%S').replace(tzinfo=timezone.utc)
              except ValueError:
                  # Try ISO format as fallback
                  if value.endswith("Z"):
                      value = value[:-1] + "+00:00"
                  return datetime.fromisoformat(value)
      
          @functions_framework.cloud_event
          def main(cloud_event):
              """
              Cloud Run function triggered by Pub/Sub to fetch ServiceNow audit logs and write to GCS.
      
              Args:
                  cloud_event: CloudEvent object containing Pub/Sub message
              """
      
              if not all([GCS_BUCKET, API_BASE, USERNAME, PASSWORD]):
                  print('Error: Missing required environment variables')
                  return
      
              try:
                  # Get GCS bucket
                  bucket = storage_client.bucket(GCS_BUCKET)
      
                  # Load state
                  state = load_state(bucket, STATE_KEY)
      
                  # Determine time window
                  now = datetime.now(timezone.utc)
                  last_time = None
      
                  if isinstance(state, dict) and state.get("last_event_time"):
                      try:
                          last_time = parse_datetime(state["last_event_time"])
                          # Overlap by 2 minutes to catch any delayed events
                          last_time = last_time - timedelta(minutes=2)
                      except Exception as e:
                          print(f"Warning: Could not parse last_event_time: {e}")
      
                  if last_time is None:
                      last_time = now - timedelta(hours=24)
      
                  print(f"Fetching logs from {last_time.strftime('%Y-%m-%d %H:%M:%S')} to {now.strftime('%Y-%m-%d %H:%M:%S')}")
      
                  # Fetch logs
                  records, newest_event_time = fetch_logs(
                      api_base=API_BASE,
                      username=USERNAME,
                      password=PASSWORD,
                      start_time=last_time,
                      end_time=now,
                      page_size=PAGE_SIZE,
                      max_pages=MAX_PAGES,
                  )
      
                  if not records:
                      print("No new log records found.")
                      save_state(bucket, STATE_KEY, now.strftime('%Y-%m-%d %H:%M:%S'))
                      return
      
                  # Write to GCS as NDJSON
                  timestamp = now.strftime('%Y%m%d_%H%M%S')
                  object_key = f"{GCS_PREFIX}/logs_{timestamp}.ndjson"
                  blob = bucket.blob(object_key)
      
                  ndjson = '\n'.join([json.dumps(record, ensure_ascii=False) for record in records]) + '\n'
                  blob.upload_from_string(ndjson, content_type='application/x-ndjson')
      
                  print(f"Wrote {len(records)} records to gs://{GCS_BUCKET}/{object_key}")
      
                  # Update state with newest event time
                  if newest_event_time:
                      save_state(bucket, STATE_KEY, newest_event_time)
                  else:
                      save_state(bucket, STATE_KEY, now.strftime('%Y-%m-%d %H:%M:%S'))
      
                  print(f"Successfully processed {len(records)} records")
      
              except Exception as e:
                  print(f'Error processing logs: {str(e)}')
                  raise
      
          def load_state(bucket, key):
              """Load state from GCS."""
              try:
                  blob = bucket.blob(key)
                  if blob.exists():
                      state_data = blob.download_as_text()
                      return json.loads(state_data)
              except Exception as e:
                  print(f"Warning: Could not load state: {e}")
      
              return {}
      
          def save_state(bucket, key, last_event_time: str):
              """Save the last event timestamp to GCS state file."""
              try:
                  state = {'last_event_time': last_event_time}
                  blob = bucket.blob(key)
                  blob.upload_from_string(
                      json.dumps(state, indent=2),
                      content_type='application/json'
                  )
                  print(f"Saved state: last_event_time={last_event_time}")
              except Exception as e:
                  print(f"Warning: Could not save state: {e}")
      
          def fetch_logs(api_base: str, username: str, password: str, start_time: datetime, end_time: datetime, page_size: int, max_pages: int):
              """
              Fetch logs from ServiceNow sys_audit table with pagination and rate limiting.
      
              Args:
                  api_base: ServiceNow instance URL
                  username: ServiceNow username
                  password: ServiceNow password
                  start_time: Start time for log query
                  end_time: End time for log query
                  page_size: Number of records per page
                  max_pages: Maximum total pages to fetch
      
              Returns:
                  Tuple of (records list, newest_event_time string)
              """
              # Clean up base URL
              base_url = api_base.rstrip('/')
      
              endpoint = f"{base_url}/api/now/table/sys_audit"
      
              # Encode credentials using UTF-8
              auth_string = f"{username}:{password}"
              auth_bytes = auth_string.encode('utf-8')
              auth_b64 = base64.b64encode(auth_bytes).decode('utf-8')
      
              headers = {
                  'Authorization': f'Basic {auth_b64}',
                  'Accept': 'application/json',
                  'Content-Type': 'application/json',
                  'User-Agent': 'GoogleSecOps-ServiceNowCollector/1.0'
              }
      
              records = []
              newest_time = None
              page_num = 0
              backoff = 1.0
              offset = 0
      
              # Format timestamps for ServiceNow (YYYY-MM-DD HH:MM:SS)
              start_time_str = start_time.strftime('%Y-%m-%d %H:%M:%S')
      
              while True:
                  page_num += 1
      
                  if len(records) >= page_size * max_pages:
                      print(f"Reached max_pages limit ({max_pages})")
                      break
      
                  # Build query parameters
                  # Use >= operator for sys_created_on field (on or after)
                  params = []
                  params.append(f"sysparm_query=sys_created_on>={start_time_str}")
                  params.append(f"sysparm_display_value=true")
                  params.append(f"sysparm_limit={page_size}")
                  params.append(f"sysparm_offset={offset}")
      
                  url = f"{endpoint}?{'&'.join(params)}"
      
                  try:
                      response = http.request('GET', url, headers=headers)
      
                      # Handle rate limiting with exponential backoff
                      if response.status == 429:
                          retry_after = int(response.headers.get('Retry-After', str(int(backoff))))
                          print(f"Rate limited (429). Retrying after {retry_after}s...")
                          time.sleep(retry_after)
                          backoff = min(backoff * 2, 30.0)
                          continue
      
                      backoff = 1.0
      
                      if response.status != 200:
                          print(f"HTTP Error: {response.status}")
                          response_text = response.data.decode('utf-8')
                          print(f"Response body: {response_text}")
                          return [], None
      
                      data = json.loads(response.data.decode('utf-8'))
                      page_results = data.get('result', [])
      
                      if not page_results:
                          print(f"No more results (empty page)")
                          break
      
                      print(f"Page {page_num}: Retrieved {len(page_results)} events")
                      records.extend(page_results)
      
                      # Track newest event time
                      for event in page_results:
                          try:
                              event_time = event.get('sys_created_on')
                              if event_time:
                                  if newest_time is None or parse_datetime(event_time) > parse_datetime(newest_time):
                                      newest_time = event_time
                          except Exception as e:
                              print(f"Warning: Could not parse event time: {e}")
      
                      # Check for more results
                      if len(page_results) < page_size:
                          print(f"Reached last page (size={len(page_results)} < limit={page_size})")
                          break
      
                      # Move to next page
                      offset += page_size
      
                      # Small delay to avoid rate limiting
                      time.sleep(0.1)
      
                  except Exception as e:
                      print(f"Error fetching logs: {e}")
                      return [], None
      
              print(f"Retrieved {len(records)} total records from {page_num} pages")
              return records, newest_time
          ```
      
    • 2 つ目のファイル: requirements.txt:

      ```
      functions-framework==3.*
      google-cloud-storage==2.*
      urllib3>=2.0.0
      ```
      
  3. [デプロイ] をクリックして、関数を保存してデプロイします。

  4. デプロイが完了するまで待ちます(2 ~ 3 分)。

Cloud Scheduler ジョブの作成

Cloud Scheduler は、定期的に Pub/Sub トピックにメッセージをパブリッシュし、Cloud Run functions の関数をトリガーします。

  1. GCP Console で、[Cloud Scheduler] に移動します。
  2. [ジョブを作成] をクリックします。
  3. 次の構成情報を提供してください。

    設定
    名前 servicenow-audit-collector-hourly
    リージョン Cloud Run functions と同じリージョンを選択する
    周波数 0 * * * *(1 時間ごとに正時)
    タイムゾーン タイムゾーンを選択します(UTC を推奨)。
    ターゲット タイプ Pub/Sub
    トピック Pub/Sub トピック(servicenow-audit-trigger)を選択する
    メッセージ本文 {}(空の JSON オブジェクト)
  4. [作成] をクリックします。

スケジュールの頻度のオプション

  • ログの量とレイテンシの要件に基づいて頻度を選択します。

    頻度 CRON 式 ユースケース
    5 分毎 */5 * * * * 大容量、低レイテンシ
    15 分ごと */15 * * * * 検索量が普通
    1 時間ごと 0 * * * * 標準(推奨)
    6 時間ごと 0 */6 * * * 少量、バッチ処理
    毎日 0 0 * * * 履歴データの収集

統合をテストする

  1. Cloud Scheduler コンソールで、ジョブを見つけます。
  2. [強制実行] をクリックして、ジョブを手動でトリガーします。
  3. 数秒待ちます。
  4. Cloud Run > サービスに移動します。
  5. 関数名(servicenow-audit-collector)をクリックします。
  6. [Logs] タブをクリックします。
  7. 関数が正常に実行されたことを確認します。次の内容を確認します。

    Fetching logs from YYYY-MM-DD HH:MM:SS to YYYY-MM-DD HH:MM:SS
    Page 1: Retrieved X events
    Wrote X records to gs://bucket-name/audit-logs/logs_YYYYMMDD_HHMMSS.ndjson
    Successfully processed X records
    
  8. [Cloud Storage] > [バケット] に移動します。

  9. バケット名をクリックします。

  10. プレフィックス フォルダ(audit-logs/)に移動します。

  11. 現在のタイムスタンプで新しい .ndjson ファイルが作成されたことを確認します。

ログにエラーが表示された場合:

  • HTTP 401: 環境変数で API 認証情報を確認する
  • HTTP 403: アカウントに必要な権限(管理者ロールまたは sys_audit のカスタム ACL)があることを確認します。
  • HTTP 429: レート制限 - 関数はバックオフで自動的に再試行されます
  • 環境変数が不足している: 必要な変数がすべて設定されていることを確認します

Google SecOps サービス アカウントを取得する

Google SecOps は、一意のサービス アカウントを使用して GCS バケットからデータを読み取ります。このサービス アカウントにバケットへのアクセス権を付与する必要があります。

サービス アカウントのメールアドレスを取得する

  1. [SIEM 設定] > [フィード] に移動します。
  2. [Add New Feed] をクリックします。
  3. [単一フィードを設定] をクリックします。
  4. [フィード名] フィールドに、フィードの名前を入力します(例: ServiceNow Audit logs)。
  5. [ソースタイプ] として [Google Cloud Storage V2] を選択します。
  6. [ログタイプ] として [ServiceNow Audit] を選択します。
  7. [サービス アカウントを取得する] をクリックします。一意のサービス アカウント メールアドレスが表示されます(例:)。

    chronicle-12345678@chronicle-gcp-prod.iam.gserviceaccount.com
    
  8. このメールアドレスをコピーして、次のステップで使用します。

Google SecOps サービス アカウントに IAM 権限を付与する

Google SecOps サービス アカウントには、GCS バケットに対する Storage オブジェクト閲覧者ロールが必要です。

  1. [Cloud Storage] > [バケット] に移動します。
  2. バケット名をクリックします。
  3. [権限] タブに移動します。
  4. [アクセス権を付与] をクリックします。
  5. 次の構成の詳細を指定します。
    • プリンシパルを追加: Google SecOps サービス アカウントのメールアドレスを貼り付けます。
    • ロールを割り当てる: [ストレージ オブジェクト閲覧者] を選択します。
  6. [保存] をクリックします。

ServiceNow の監査ログを取り込むように Google SecOps でフィードを構成する

  1. [SIEM 設定] > [フィード] に移動します。
  2. [Add New Feed] をクリックします。
  3. [単一フィードを設定] をクリックします。
  4. [フィード名] フィールドに、フィードの名前を入力します(例: ServiceNow Audit logs)。
  5. [ソースタイプ] として [Google Cloud Storage V2] を選択します。
  6. [ログタイプ] として [ServiceNow Audit] を選択します。
  7. [次へ] をクリックします。
  8. 次の入力パラメータの値を指定します。

    • ストレージ バケットの URL: 接頭辞パスを含む GCS バケット URI を入力します。

      gs://servicenow-audit-logs/audit-logs/
      
      • 次のように置き換えます。

        • servicenow-audit-logs: GCS バケット名。
        • audit-logs: ログが保存される接頭辞/フォルダパス。
    • Source deletion option: 必要に応じて削除オプションを選択します。

      • なし: 転送後にファイルを削除しません(テストにおすすめ)。
      • 転送されたファイルを削除する: 転送が完了した後にファイルを削除します。
      • 転送されたファイルと空のディレクトリを削除する: 転送が完了した後にファイルと空のディレクトリを削除します。

    • ファイルの最大経過日数: 指定した日数以内に変更されたファイルを含めます。デフォルトは 180 日です。

    • アセットの名前空間: アセットの名前空間

    • Ingestion labels: このフィードのイベントに適用されるラベル。

  9. [次へ] をクリックします。

  10. [Finalize] 画面で新しいフィードの設定を確認し、[送信] をクリックします。

オプション B: syslog を使用した Bindplane エージェント

この方法では、Bindplane エージェントを使用して ServiceNow 監査ログを収集し、Google Security Operations に転送します。ServiceNow は監査ログの syslog をネイティブにサポートしていないため、スクリプトを使用して ServiceNow REST API をクエリし、syslog 経由で Bindplane エージェントにログを転送します。

始める前に

次の前提条件を満たしていることを確認してください。

  • Google SecOps インスタンス
  • Windows Server 2016 以降、または systemd を使用する Linux ホスト
  • Bindplane エージェントと ServiceNow 間のネットワーク接続
  • プロキシの背後で実行している場合は、Bindplane エージェントの要件に従ってファイアウォール ポートが開いていることを確認します。
  • 適切なロール(通常は admin または sys_audit テーブルへの読み取りアクセス権を持つユーザー)を持つ ServiceNow 管理コンソールまたはアプライアンスへの特権アクセス

Google SecOps の取り込み認証ファイルを取得する

  1. Google SecOps コンソールにログインします。
  2. [SIEM 設定] > [収集エージェント] に移動します。
  3. [ダウンロード] をクリックして、取り込み認証ファイルをダウンロードします。
  4. Bindplane をインストールするシステムにファイルを安全に保存します。

Google SecOps のお客様 ID を取得する

  1. Google SecOps コンソールにログインします。
  2. [SIEM 設定] > [プロファイル] に移動します。
  3. [組織の詳細情報] セクションから [お客様 ID] をコピーして保存します。

Bindplane エージェントをインストールする

次の手順に沿って、Windows または Linux オペレーティング システムに Bindplane エージェントをインストールします。

Windows のインストール

  1. 管理者としてコマンド プロンプトまたは PowerShell を開きます。
  2. 次のコマンドを実行します。

    msiexec /i "https://github.com/observIQ/bindplane-agent/releases/latest/download/observiq-otel-collector.msi" /quiet
    
  3. インストールが完了するまで待ちます。

  4. 次のコマンドを実行して、インストールの内容を確認します。

    sc query observiq-otel-collector
    

サービスは RUNNING と表示されます。

Linux のインストール

  1. root 権限または sudo 権限でターミナルを開きます。
  2. 次のコマンドを実行します。

    sudo sh -c "$(curl -fsSlL https://github.com/observiq/bindplane-agent/releases/latest/download/install_unix.sh)" install_unix.sh
    
  3. インストールが完了するまで待ちます。

  4. 次のコマンドを実行して、インストールの内容を確認します。

    sudo systemctl status observiq-otel-collector
    

サービスが [アクティブ(実行中)] と表示されます。

その他のインストール リソース

その他のインストール オプションとトラブルシューティングについては、Bindplane エージェントのインストール ガイドをご覧ください。

Syslog を取り込んで Google SecOps に送信するように Bindplane エージェントを構成する

構成ファイルを見つける

Linux: bash sudo nano /etc/bindplane-agent/config.yaml

Windows: cmd notepad "C:\Program Files\observIQ OpenTelemetry Collector\config.yaml"

構成ファイルを編集します。

config.yaml の内容全体を次の構成に置き換えます。

```yaml
receivers:
  udplog:
    listen_address: "0.0.0.0:514"

exporters:
  chronicle/servicenow_audit:
    compression: gzip
    creds_file_path: '/path/to/ingestion-authentication-file.json'
    customer_id: '<YOUR_CUSTOMER_ID>'
    endpoint: <CUSTOMER_REGION_ENDPOINT>
    log_type: 'SERVICENOW_AUDIT'
    raw_log_field: body
    ingestion_labels:
      service: servicenow

service:
  pipelines:
    logs/servicenow_to_chronicle:
      receivers:
        - udplog
      exporters:
        - chronicle/servicenow_audit
```

構成パラメータ

各プレースホルダを次のように置き換えます。

  • listen_address: リッスンする IP アドレスとポート。0.0.0.0:514 を使用して、ポート 514 のすべてのインターフェースをリッスンします。
  • creds_file_path: 取り込み認証ファイルのフルパス:
    • Linux: /etc/bindplane-agent/ingestion-auth.json
    • Windows: C:\Program Files\observIQ OpenTelemetry Collector\ingestion-auth.json
  • <YOUR_CUSTOMER_ID>: 前の手順の顧客 ID。
  • <CUSTOMER_REGION_ENDPOINT>: リージョン エンドポイント URL:
    • 米国: malachiteingestion-pa.googleapis.com
    • ヨーロッパ: europe-malachiteingestion-pa.googleapis.com
    • アジア: asia-southeast1-malachiteingestion-pa.googleapis.com
    • 完全なリストについては、リージョン エンドポイントをご覧ください。

構成ファイルを保存する

編集が完了したら、ファイルを保存します。 * Linux: Ctrl+OEnterCtrl+X の順に押します。 * Windows: [ファイル> 保存] をクリックします。

Bindplane エージェントを再起動して変更を適用する

  • Linux で Bindplane エージェントを再起動するには、次のコマンドを実行します。

    sudo systemctl restart observiq-otel-collector
    
    1. サービスが実行されていることを確認します。

      sudo systemctl status observiq-otel-collector
      
    2. ログでエラーを確認します。

      sudo journalctl -u observiq-otel-collector -f
      
  • Windows で Bindplane エージェントを再起動するには、次のいずれかのオプションを選択します。

    • 管理者としてコマンド プロンプトまたは PowerShell を使用します。

      net stop observiq-otel-collector && net start observiq-otel-collector
      
    • Services コンソールを使用する場合:

    1. Win+R キーを押して「services.msc」と入力し、Enter キーを押します。
    2. observIQ OpenTelemetry Collector を見つけます。
    3. 右クリックして [再起動] を選択します。

    4. サービスが実行されていることを確認します。

      sc query observiq-otel-collector
      
    5. ログでエラーを確認します。

      type "C:\Program Files\observIQ OpenTelemetry Collector\log\collector.log"
      

ServiceNow 監査ログを syslog に転送するスクリプトを作成する

ServiceNow は監査ログの syslog をネイティブにサポートしていないため、ServiceNow REST API をクエリしてログを syslog に転送するスクリプトを作成します。このスクリプトは定期的に実行するようにスケジュールできます。

Python スクリプトの例(Linux)

  • 次の内容で servicenow_audit_to_syslog.py という名前のファイルを作成します。

    import urllib3
    import json
    import datetime
    import base64
    import socket
    import time
    import os
    
    # ServiceNow API details
    BASE_URL = 'https://instance.service-now.com'  # Replace with your ServiceNow instance URL
    USERNAME = 'admin'  # Replace with your ServiceNow username
    PASSWORD = 'password'  # Replace with your ServiceNow password
    
    # Syslog details
    SYSLOG_SERVER = '127.0.0.1'  # Replace with your Bindplane agent IP
    SYSLOG_PORT = 514  # Replace with your Bindplane agent port
    
    # State file to keep track of last run
    STATE_FILE = '/tmp/servicenow_audit_last_run.txt'
    
    # Pagination settings
    PAGE_SIZE = 1000
    MAX_PAGES = 1000
    
    def get_last_run_timestamp():
        try:
            with open(STATE_FILE, 'r') as f:
                return f.read().strip()
        except:
            return '1970-01-01 00:00:00'
    
    def update_state_file(timestamp):
        with open(STATE_FILE, 'w') as f:
            f.write(timestamp)
    
    def send_to_syslog(message):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.sendto(message.encode(), (SYSLOG_SERVER, SYSLOG_PORT))
        sock.close()
    
    def get_audit_logs(last_run_timestamp):
        """
        Query ServiceNow sys_audit table with proper pagination.
        Uses sys_created_on field for timestamp filtering.
        """
        # Encode credentials using UTF-8
        auth_string = f"{USERNAME}:{PASSWORD}"
        auth_bytes = auth_string.encode('utf-8')
        auth_encoded = base64.b64encode(auth_bytes).decode('utf-8')
    
        # Setup HTTP client
        http = urllib3.PoolManager()
        headers = {
            'Authorization': f'Basic {auth_encoded}',
            'Accept': 'application/json'
        }
    
        results = []
        offset = 0
    
        # Format timestamp for ServiceNow (YYYY-MM-DD HH:MM:SS format)
        # Convert ISO format to ServiceNow format if needed
        if 'T' in last_run_timestamp:
            last_run_timestamp = last_run_timestamp.replace('T', ' ').split('.')[0]
    
        for page in range(MAX_PAGES):
            # Build query with pagination
            # Use >= operator for sys_created_on field (on or after)
            query_params = (
                f"sysparm_query=sys_created_on>={last_run_timestamp}"
                f"&sysparm_display_value=true"
                f"&sysparm_limit={PAGE_SIZE}"
                f"&sysparm_offset={offset}"
            )
    
            url = f"{BASE_URL}/api/now/table/sys_audit?{query_params}"
    
            try:
                response = http.request('GET', url, headers=headers)
    
                if response.status == 200:
                    data = json.loads(response.data.decode('utf-8'))
                    chunk = data.get('result', [])
                    results.extend(chunk)
    
                    # Stop if we got fewer records than PAGE_SIZE (last page)
                    if len(chunk) < PAGE_SIZE:
                        break
    
                    # Move to next page
                    offset += PAGE_SIZE
                else:
                    print(f"Error querying ServiceNow API: {response.status} - {response.data.decode('utf-8')}")
                    break
    
            except Exception as e:
                print(f"Exception querying ServiceNow API: {str(e)}")
                break
    
        return results
    
    def main():
        # Get last run timestamp
        last_run_timestamp = get_last_run_timestamp()
    
        # Current timestamp for this run
        current_timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    
        # Query ServiceNow API for audit logs
        audit_logs = get_audit_logs(last_run_timestamp)
    
        if audit_logs:
            # Send each log to syslog
            for log in audit_logs:
                # Format the log as JSON
                log_json = json.dumps(log)
    
                # Send to syslog
                send_to_syslog(log_json)
    
                # Sleep briefly to avoid flooding
                time.sleep(0.01)
    
            # Update state file
            update_state_file(current_timestamp)
    
            print(f"Successfully forwarded {len(audit_logs)} audit logs to syslog")
        else:
            print("No new audit logs to forward")
    
    if __name__ == "__main__":
        main()
    

スケジュールされた実行を設定する(Linux)

  • スクリプトを実行可能にします。

    chmod +x servicenow_audit_to_syslog.py
    
  • 1 時間ごとにスクリプトを実行する cron ジョブを作成します。

    crontab -e
    
  • 次の行を追加します。

    0 * * * * /usr/bin/python3 /path/to/servicenow_audit_to_syslog.py >> /tmp/servicenow_audit_to_syslog.log 2>&1
    

PowerShell スクリプトの例(Windows)

  • 次の内容で ServiceNow-Audit-To-Syslog.ps1 という名前のファイルを作成します。

    # ServiceNow API details
    $BaseUrl = 'https://instance.service-now.com'  # Replace with your ServiceNow instance URL
    $Username = 'admin'  # Replace with your ServiceNow username
    $Password = 'password'  # Replace with your ServiceNow password
    
    # Syslog details
    $SyslogServer = '127.0.0.1'  # Replace with your Bindplane agent IP
    $SyslogPort = 514  # Replace with your Bindplane agent port
    
    # State file to keep track of last run
    $StateFile = "$env:TEMP\ServiceNowAuditLastRun.txt"
    
    # Pagination settings
    $PageSize = 1000
    $MaxPages = 1000
    
    function Get-LastRunTimestamp {
        try {
            if (Test-Path $StateFile) {
                return Get-Content $StateFile
            } else {
                return '1970-01-01 00:00:00'
            }
        } catch {
            return '1970-01-01 00:00:00'
        }
    }
    
    function Update-StateFile {
        param([string]$Timestamp)
        Set-Content -Path $StateFile -Value $Timestamp
    }
    
    function Send-ToSyslog {
        param([string]$Message)
        $UdpClient = New-Object System.Net.Sockets.UdpClient
        $UdpClient.Connect($SyslogServer, $SyslogPort)
        $Encoding = [System.Text.Encoding]::ASCII
        $Bytes = $Encoding.GetBytes($Message)
        $UdpClient.Send($Bytes, $Bytes.Length)
        $UdpClient.Close()
    }
    
    function Get-AuditLogs {
        param([string]$LastRunTimestamp)
    
        # Create auth header using UTF-8 encoding
        $Auth = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("${Username}:${Password}"))
        $Headers = @{
            Authorization = "Basic ${Auth}"
            Accept = 'application/json'
        }
    
        $Results = @()
        $Offset = 0
    
        # Format timestamp for ServiceNow (YYYY-MM-DD HH:MM:SS format)
        # Convert ISO format to ServiceNow format if needed
        if ($LastRunTimestamp -match 'T') {
            $LastRunTimestamp = $LastRunTimestamp -replace 'T', ' '
            $LastRunTimestamp = $LastRunTimestamp -replace '\.\d+', ''
        }
    
        for ($page = 0; $page -lt $MaxPages; $page++) {
            # Build query with pagination
            # Use >= operator for sys_created_on field (on or after)
            $QueryParams = "sysparm_query=sys_created_on>=${LastRunTimestamp}&sysparm_display_value=true&sysparm_limit=${PageSize}&sysparm_offset=${Offset}"
            $Url = "${BaseUrl}/api/now/table/sys_audit?${QueryParams}"
    
            try {
                $Response = Invoke-RestMethod -Uri $Url -Headers $Headers -Method Get
                $Chunk = $Response.result
                $Results += $Chunk
    
                # Stop if we got fewer records than PageSize (last page)
                if ($Chunk.Count -lt $PageSize) {
                    break
                }
    
                # Move to next page
                $Offset += $PageSize
            } catch {
                Write-Error "Error querying ServiceNow API: $_"
                break
            }
        }
    
        return $Results
    }
    
    # Main execution
    $LastRunTimestamp = Get-LastRunTimestamp
    $CurrentTimestamp = (Get-Date).ToString('yyyy-MM-dd HH:mm:ss')
    
    $AuditLogs = Get-AuditLogs -LastRunTimestamp $LastRunTimestamp
    
    if ($AuditLogs -and $AuditLogs.Count -gt 0) {
        # Send each log to syslog
        foreach ($Log in $AuditLogs) {
            # Format the log as JSON
            $LogJson = $Log | ConvertTo-Json -Compress
    
            # Send to syslog
            Send-ToSyslog -Message $LogJson
    
            # Sleep briefly to avoid flooding
            Start-Sleep -Milliseconds 10
        }
    
        # Update state file
        Update-StateFile -Timestamp $CurrentTimestamp
    
        Write-Output "Successfully forwarded $($AuditLogs.Count) audit logs to syslog"
    } else {
        Write-Output "No new audit logs to forward"
    }
    

スケジュールされた実行を設定する(Windows)

  1. [タスク スケジューラ] を開きます。
  2. [タスクを作成] をクリックします。
  3. 次の構成を指定します。
    • 名前: ServiceNowAuditToSyslog
    • セキュリティ オプション: ユーザーがログインしているかどうかに関係なく実行する
  4. [トリガー] タブに移動します。
  5. [新規作成] をクリックし、1 時間ごとに実行するように設定します。
  6. [アクション] タブに移動します。
  7. [新規] をクリックして、次の項目を設定します。
    • アクション: プログラムの開始
    • プログラム/スクリプト: powershell.exe
    • Arguments: -ExecutionPolicy Bypass -File "C:\path\to\ServiceNow-Audit-To-Syslog.ps1"
  8. [OK] をクリックしてタスクを保存します。

ご不明な点がございましたら、コミュニティ メンバーや Google SecOps のプロフェッショナルから回答を得ることができます。