Bitwarden Enterprise 이벤트 로그 수집
이 문서에서는 Google Cloud Storage를 사용하여 Bitwarden Enterprise 이벤트 로그를 Google Security Operations에 수집하는 방법을 설명합니다. 파서는 원시 JSON 형식 이벤트 로그를 SecOps UDM을 준수하는 구조화된 형식으로 변환합니다. 사용자 세부정보, IP 주소, 이벤트 유형과 같은 관련 필드를 추출하여 일관된 보안 분석을 위해 해당 UDM 필드에 매핑합니다.
시작하기 전에
다음 기본 요건이 충족되었는지 확인합니다.
- Google SecOps 인스턴스
- Bitwarden 테넌트에 대한 액세스 권한
- Cloud Storage API가 사용 설정된 GCP 프로젝트
- GCS 버킷을 만들고 관리할 수 있는 권한
- GCS 버킷의 IAM 정책을 관리할 수 있는 권한
- Cloud Run 서비스, Pub/Sub 주제, Cloud Scheduler 작업을 만들 수 있는 권한
Bitwarden API 키 및 URL 가져오기
- Bitwarden 관리 콘솔에서 설정 > 조직 정보 > API 키 보기로 이동합니다.
- 다음 세부정보를 복사하여 안전한 위치에 저장합니다.
- Client ID
- 클라이언트 보안 비밀번호
리전에 따라 Bitwarden 엔드포인트를 확인합니다.
- IDENTITY_URL =
https://identity.bitwarden.com/connect/token(EU:https://identity.bitwarden.eu/connect/token) - API_BASE =
https://api.bitwarden.com(EU:https://api.bitwarden.eu)
- IDENTITY_URL =
Google Cloud Storage 버킷 만들기
- Google Cloud Console로 이동합니다.
- 프로젝트를 선택하거나 새 프로젝트를 만듭니다.
- 탐색 메뉴에서 Cloud Storage> 버킷으로 이동합니다.
- 버킷 만들기를 클릭합니다.
다음 구성 세부정보를 제공합니다.
설정 값 버킷 이름 지정 전역적으로 고유한 이름 (예: bitwarden-events)을 입력합니다.위치 유형 필요에 따라 선택 (리전, 이중 리전, 멀티 리전) 위치 위치를 선택합니다 (예: us-central1).스토리지 클래스 Standard (자주 액세스하는 로그에 권장) 액세스 제어 균일 (권장) 보호 도구 선택사항: 객체 버전 관리 또는 보관 정책 사용 설정 만들기를 클릭합니다.
Bitwarden API 기본 요건 수집
이전 단계에서 Bitwarden API 사용자 인증 정보를 이미 수집했습니다.
- 클라이언트 ID: Bitwarden 관리 콘솔의 조직 클라이언트 ID
- 클라이언트 보안 비밀번호: Bitwarden 관리 콘솔의 조직 클라이언트 보안 비밀번호
- IDENTITY_URL:
https://identity.bitwarden.com/connect/token(또는 EU 엔드포인트) - API_BASE:
https://api.bitwarden.com(또는 EU 엔드포인트)
Cloud Run 함수의 서비스 계정 만들기
Cloud Run 함수에는 GCS 버킷에 쓸 수 있고 Pub/Sub에서 호출할 수 있는 권한이 있는 서비스 계정이 필요합니다.
서비스 계정 만들기
- GCP 콘솔에서 IAM 및 관리자 > 서비스 계정으로 이동합니다.
- 서비스 계정 만들기를 클릭합니다.
- 다음 구성 세부정보를 제공합니다.
- 서비스 계정 이름:
bitwarden-events-collector-sa을 입력합니다. - 서비스 계정 설명:
Service account for Cloud Run function to collect Bitwarden Enterprise Event logs을 입력합니다.
- 서비스 계정 이름:
- 만들고 계속하기를 클릭합니다.
- 이 서비스 계정에 프로젝트에 대한 액세스 권한 부여 섹션에서 다음 역할을 추가합니다.
- 역할 선택을 클릭합니다.
- 스토리지 객체 관리자를 검색하여 선택합니다.
- + 다른 역할 추가를 클릭합니다.
- Cloud Run 호출자를 검색하여 선택합니다.
- + 다른 역할 추가를 클릭합니다.
- Cloud Functions 호출자를 검색하여 선택합니다.
- 계속을 클릭합니다.
- 완료를 클릭합니다.
이러한 역할은 다음 작업에 필요합니다.
- 스토리지 객체 관리자: GCS 버킷에 로그를 쓰고 상태 파일을 관리합니다.
- Cloud Run 호출자: Pub/Sub가 함수를 호출하도록 허용
- Cloud Functions 호출자: 함수 호출 허용
GCS 버킷에 대한 IAM 권한 부여
GCS 버킷에 대한 쓰기 권한을 서비스 계정에 부여합니다.
- Cloud Storage> 버킷으로 이동합니다.
- 버킷 이름을 클릭합니다.
- 권한 탭으로 이동합니다.
- 액세스 권한 부여를 클릭합니다.
- 다음 구성 세부정보를 제공합니다.
- 주 구성원 추가: 서비스 계정 이메일 (예:
bitwarden-events-collector-sa@PROJECT_ID.iam.gserviceaccount.com)을 입력합니다. - 역할 할당: 스토리지 객체 관리자를 선택합니다.
- 주 구성원 추가: 서비스 계정 이메일 (예:
- 저장을 클릭합니다.
게시/구독 주제 만들기
Cloud Scheduler가 게시하고 Cloud Run 함수가 구독할 Pub/Sub 주제를 만듭니다.
- GCP Console에서 Pub/Sub > 주제로 이동합니다.
- 주제 만들기를 클릭합니다.
- 다음 구성 세부정보를 제공합니다.
- 주제 ID:
bitwarden-events-trigger를 입력합니다. - 다른 설정은 기본값으로 둡니다.
- 주제 ID:
- 만들기를 클릭합니다.
로그를 수집하는 Cloud Run 함수 만들기
Cloud Run 함수는 Cloud Scheduler의 Pub/Sub 메시지에 의해 트리거되어 Bitwarden Events API에서 로그를 가져오고 이를 GCS에 씁니다.
- GCP 콘솔에서 Cloud Run으로 이동합니다.
- 서비스 만들기를 클릭합니다.
- 함수를 선택합니다 (인라인 편집기를 사용하여 함수 만들기).
구성 섹션에서 다음 구성 세부정보를 제공합니다.
설정 값 서비스 이름 bitwarden-events-collector리전 GCS 버킷과 일치하는 리전을 선택합니다 (예: us-central1).런타임 Python 3.12 이상 선택 트리거 (선택사항) 섹션에서 다음을 수행합니다.
- + 트리거 추가를 클릭합니다.
- Cloud Pub/Sub를 선택합니다.
- Cloud Pub/Sub 주제 선택에서 Pub/Sub 주제 (
bitwarden-events-trigger)를 선택합니다. - 저장을 클릭합니다.
인증 섹션에서 다음을 구성합니다.
- 인증 필요를 선택합니다.
- ID 및 액세스 관리 (IAM)를 확인합니다.
아래로 스크롤하고 컨테이너, 네트워킹, 보안을 펼칩니다.
보안 탭으로 이동합니다.
- 서비스 계정: 서비스 계정 (
bitwarden-events-collector-sa)을 선택합니다.
- 서비스 계정: 서비스 계정 (
컨테이너 탭으로 이동합니다.
- 변수 및 보안 비밀을 클릭합니다.
- 각 환경 변수에 대해 + 변수 추가를 클릭합니다.
변수 이름 예시 값 GCS_BUCKETbitwarden-eventsGCS_PREFIXbitwarden/eventsSTATE_KEYbitwarden/events/state.jsonBW_CLIENT_IDorganization.your-client-idBW_CLIENT_SECRETyour-client-secretIDENTITY_URLhttps://identity.bitwarden.com/connect/tokenAPI_BASEhttps://api.bitwarden.comMAX_PAGES10변수 및 보안 비밀 섹션에서 요청까지 아래로 스크롤합니다.
- 요청 제한 시간:
600초 (10분)를 입력합니다.
- 요청 제한 시간:
설정 탭으로 이동합니다.
- 리소스 섹션에서 다음을 수행합니다.
- 메모리: 512MiB 이상을 선택합니다.
- CPU: 1을 선택합니다.
- 리소스 섹션에서 다음을 수행합니다.
버전 확장 섹션에서 다음을 수행합니다.
- 최소 인스턴스 수:
0를 입력합니다. - 최대 인스턴스 수:
100을 입력합니다 (또는 예상 부하에 따라 조정).
- 최소 인스턴스 수:
만들기를 클릭합니다.
서비스가 생성될 때까지 기다립니다 (1~2분).
서비스가 생성되면 인라인 코드 편집기가 자동으로 열립니다.
함수 코드 추가
- 함수 진입점에 main을 입력합니다.
인라인 코드 편집기에서 다음 두 파일을 만듭니다.
- 첫 번째 파일: main.py:
import functions_framework from google.cloud import storage import json import os import urllib3 from datetime import datetime, timezone 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() @functions_framework.cloud_event def main(cloud_event): """ Cloud Run function triggered by Pub/Sub to fetch events from Bitwarden API and write to GCS. Args: cloud_event: CloudEvent object containing Pub/Sub message """ # Get environment variables bucket_name = os.environ.get('GCS_BUCKET') prefix = os.environ.get('GCS_PREFIX', 'bitwarden/events').strip('/') state_key = os.environ.get('STATE_KEY', 'bitwarden/events/state.json') # Bitwarden API credentials identity_url = os.environ.get('IDENTITY_URL', 'https://identity.bitwarden.com/connect/token') api_base = os.environ.get('API_BASE', 'https://api.bitwarden.com').rstrip('/') client_id = os.environ.get('BW_CLIENT_ID') client_secret = os.environ.get('BW_CLIENT_SECRET') max_pages = int(os.environ.get('MAX_PAGES', '10')) if not all([bucket_name, client_id, client_secret]): print('Error: Missing required environment variables') return try: # Get GCS bucket bucket = storage_client.bucket(bucket_name) # Load state (continuation token) state = load_state(bucket, state_key) continuation_token = state.get('continuationToken') print(f'Processing events with continuation token: {continuation_token}') # Get OAuth token access_token = get_oauth_token(identity_url, client_id, client_secret) # Fetch events from Bitwarden API run_timestamp = int(datetime.now(timezone.utc).timestamp()) pages = 0 total_events = 0 written_files = [] while pages < max_pages: events_data = fetch_events(api_base, access_token, continuation_token) # Extract events array from API response events = events_data.get('data', []) # Only write file if there are events if events: gcs_key = write_events_jsonl(bucket, events, prefix, run_timestamp, pages) if gcs_key: written_files.append(gcs_key) total_events += len(events) pages += 1 # Check for next page token next_token = events_data.get('continuationToken') if next_token: continuation_token = next_token continue else: # No more pages break # Save state only if there are more pages to continue in next run # If we hit MAX_PAGES and there's still a continuation token, save it # Otherwise, clear the state (set to None) save_state(bucket, state_key, { 'continuationToken': continuation_token if pages >= max_pages and continuation_token else None }) print(f'Successfully processed {total_events} events across {pages} pages') print(f'Files written: {len(written_files)}') except Exception as e: print(f'Error processing events: {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: {str(e)}') return {} def save_state(bucket, key, state): """Save state to GCS.""" try: blob = bucket.blob(key) blob.upload_from_string( json.dumps(state), content_type='application/json' ) except Exception as e: print(f'Warning: Could not save state: {str(e)}') def get_oauth_token(identity_url, client_id, client_secret): """Get OAuth 2.0 access token from Bitwarden.""" body_data = { 'grant_type': 'client_credentials', 'scope': 'api.organization', 'client_id': client_id, 'client_secret': client_secret } encoded_data = '&'.join([f'{k}={v}' for k, v in body_data.items()]).encode('utf-8') response = http.request( 'POST', identity_url, body=encoded_data, headers={'Content-Type': 'application/x-www-form-urlencoded'} ) if response.status != 200: raise Exception(f'Failed to get OAuth token: {response.status} {response.data.decode("utf-8")}') token_data = json.loads(response.data.decode('utf-8')) return token_data['access_token'] def fetch_events(api_base, access_token, continuation_token=None): """Fetch events from Bitwarden API with pagination.""" url = f'{api_base}/public/events' if continuation_token: url += f'?continuationToken={continuation_token}' response = http.request( 'GET', url, headers={ 'Authorization': f'Bearer {access_token}', 'Accept': 'application/json' } ) if response.status == 429: retry_after = int(response.headers.get('Retry-After', '60')) print(f'Rate limited (429). Retrying after {retry_after}s...') import time time.sleep(retry_after) return fetch_events(api_base, access_token, continuation_token) if response.status != 200: raise Exception(f'Failed to fetch events: {response.status} {response.data.decode("utf-8")}') return json.loads(response.data.decode('utf-8')) def write_events_jsonl(bucket, events, prefix, run_timestamp, page_index): """ Write events in JSONL format (one JSON object per line). Only writes if there are events to write. Returns the GCS key of the written file. """ if not events: return None # Build JSONL content: one event per line lines = [json.dumps(event, separators=(',', ':')) for event in events] jsonl_content = '\n'.join(lines) + '\n' # JSONL format with trailing newline # Generate unique filename with page number to avoid conflicts timestamp_str = datetime.fromtimestamp(run_timestamp, tz=timezone.utc).strftime('%Y/%m/%d/%H%M%S') key = f'{prefix}/{timestamp_str}-page{page_index:05d}-bitwarden-events.jsonl' blob = bucket.blob(key) blob.upload_from_string( jsonl_content, content_type='application/x-ndjson' ) print(f'Wrote {len(events)} events to {key}') return key- 두 번째 파일: requirements.txt:
functions-framework==3.* google-cloud-storage==2.* urllib3>=2.0.0배포를 클릭하여 함수를 저장하고 배포합니다.
배포가 완료될 때까지 기다립니다 (2~3분).
Cloud Scheduler 작업 만들기
Cloud Scheduler는 일정 간격으로 Pub/Sub 주제에 메시지를 게시하여 Cloud Run 함수를 트리거합니다.
- GCP Console에서 Cloud Scheduler로 이동합니다.
- 작업 만들기를 클릭합니다.
다음 구성 세부정보를 제공합니다.
설정 값 이름 bitwarden-events-hourly리전 Cloud Run 함수와 동일한 리전 선택 주파수 0 * * * *(매시간 정각)시간대 시간대 선택 (UTC 권장) 타겟 유형 Pub/Sub 주제 Pub/Sub 주제 ( bitwarden-events-trigger)를 선택합니다.메일 본문 {}(빈 JSON 객체)만들기를 클릭합니다.
일정 빈도 옵션
로그 볼륨 및 지연 시간 요구사항에 따라 빈도를 선택합니다.
빈도 크론 표현식 사용 사례 5분마다 */5 * * * *대용량, 저지연 15분마다 */15 * * * *검색량 보통 1시간마다 0 * * * *일반(권장) 6시간마다 0 */6 * * *양이 적은 일괄 처리 매일 0 0 * * *이전 데이터 수집
통합 테스트
- Cloud Scheduler 콘솔에서 작업을 찾습니다.
- 강제 실행을 클릭하여 작업을 수동으로 트리거합니다.
- 몇 초 동안 기다립니다.
- Cloud Run > 서비스로 이동합니다.
- 함수 이름 (
bitwarden-events-collector)을 클릭합니다. - 로그 탭을 클릭합니다.
함수가 성공적으로 실행되었는지 확인합니다. 다음 항목을 찾습니다.
Processing events with continuation token: None Page 1: Retrieved X events Wrote X events to bitwarden/events/YYYY/MM/DD/HHMMSS-page00000-bitwarden-events.jsonl Successfully processed X events across 1 pagesCloud Storage> 버킷으로 이동합니다.
버킷 이름을 클릭합니다.
접두사 폴더 (
bitwarden/events/)로 이동합니다.현재 타임스탬프를 사용하여 새
.jsonl파일이 생성되었는지 확인합니다.
로그에 오류가 표시되면 다음 단계를 따르세요.
- HTTP 401: 환경 변수에서 API 사용자 인증 정보 확인
- HTTP 403: 계정에 필요한 권한이 있고 조직 설정에서 이벤트 기능이 사용 설정되어 있는지 확인합니다.
- HTTP 429: 비율 제한 - 함수가 백오프를 사용하여 자동으로 재시도됩니다.
- 환경 변수 누락: 필수 변수가 모두 설정되었는지 확인
Google SecOps 서비스 계정 가져오기
Google SecOps는 고유한 서비스 계정을 사용하여 GCS 버킷에서 데이터를 읽습니다. 이 서비스 계정에 버킷에 대한 액세스 권한을 부여해야 합니다.
서비스 계정 이메일 가져오기
- SIEM 설정> 피드로 이동합니다.
- 새 피드 추가를 클릭합니다.
- 단일 피드 구성을 클릭합니다.
- 피드 이름 필드에 피드 이름을 입력합니다(예:
Bitwarden Events). - 소스 유형으로 Google Cloud Storage V2를 선택합니다.
- 로그 유형으로 Bitwarden 이벤트를 선택합니다.
서비스 계정 가져오기를 클릭합니다. 고유한 서비스 계정 이메일이 표시됩니다(예:
chronicle-12345678@chronicle-gcp-prod.iam.gserviceaccount.com다음 단계에서 사용할 수 있도록 이 이메일 주소를 복사합니다.
Google SecOps 서비스 계정에 IAM 권한 부여
Google SecOps 서비스 계정에는 GCS 버킷에 대한 스토리지 객체 뷰어 역할이 필요합니다.
- Cloud Storage> 버킷으로 이동합니다.
- 버킷 이름을 클릭합니다.
- 권한 탭으로 이동합니다.
- 액세스 권한 부여를 클릭합니다.
- 다음 구성 세부정보를 제공합니다.
- 주 구성원 추가: Google SecOps 서비스 계정 이메일을 붙여넣습니다.
- 역할 할당: 스토리지 객체 뷰어를 선택합니다.
저장을 클릭합니다.
Bitwarden Enterprise 이벤트 로그를 수집하도록 Google SecOps에서 피드 구성
- SIEM 설정> 피드로 이동합니다.
- 새 피드 추가를 클릭합니다.
- 단일 피드 구성을 클릭합니다.
- 피드 이름 필드에 피드 이름을 입력합니다(예:
Bitwarden Events). - 소스 유형으로 Google Cloud Storage V2를 선택합니다.
- 로그 유형으로 Bitwarden 이벤트를 선택합니다.
- 다음을 클릭합니다.
다음 입력 매개변수의 값을 지정합니다.
스토리지 버킷 URL: 다음 접두사 경로를 사용하여 GCS 버킷 URI를 입력합니다.
gs://bitwarden-events/bitwarden/events/다음과 같이 바꿉니다.
bitwarden-events: GCS 버킷 이름입니다.bitwarden/events/: 로그가 저장되는 접두사/폴더 경로입니다.
소스 삭제 옵션: 환경설정에 따라 삭제 옵션을 선택합니다.
- 삭제 안함: 전송 후 파일을 삭제하지 않습니다 (테스트에 권장).
- 전송된 파일 삭제: 전송이 완료되면 파일을 삭제합니다.
전송된 파일 및 빈 디렉터리 삭제: 전송이 완료되면 파일과 빈 디렉터리를 삭제합니다.
최대 파일 기간: 지난 일수 동안 수정된 파일을 포함합니다. 기본값은 180일입니다.
애셋 네임스페이스: 애셋 네임스페이스입니다.
수집 라벨: 이 피드의 이벤트에 적용할 라벨입니다.
다음을 클릭합니다.
확정 화면에서 새 피드 구성을 검토한 다음 제출을 클릭합니다.
UDM 매핑 테이블
| 로그 필드 | UDM 매핑 | 로직 |
|---|---|---|
| actingUserId | target.user.userid | enriched.actingUser.userId가 비어 있거나 null인 경우 이 필드는 target.user.userid 필드를 채우는 데 사용됩니다. |
| collectionID | security_result.detection_fields.key | security_result의 detection_fields 내 키 필드를 채웁니다. |
| collectionID | security_result.detection_fields.value | security_result의 detection_fields 내에 있는 값 필드를 채웁니다. |
| 날짜 | metadata.event_timestamp | 파싱되어 타임스탬프 형식으로 변환되고 event_timestamp에 매핑됩니다. |
| enriched.actingUser.accessAll | security_result.rule_labels.key | security_result의 rule_labels 내에서 값을 'Access_All'로 설정합니다. |
| enriched.actingUser.accessAll | security_result.rule_labels.value | 강화된.actingUser.accessAll에서 문자열로 변환된 값으로 security_result의 rule_labels 내 값 필드를 채웁니다. |
| enriched.actingUser.email | target.user.email_addresses | target.user 내의 email_addresses 필드를 채웁니다. |
| enriched.actingUser.id | metadata.product_log_id | 메타데이터 내의 product_log_id 필드를 채웁니다. |
| enriched.actingUser.id | target.labels.key | target.labels 내에서 값을 'ID'로 설정합니다. |
| enriched.actingUser.id | target.labels.value | 강화된.actingUser.id의 값으로 target.labels 내의 값 필드를 채웁니다. |
| enriched.actingUser.name | target.user.user_display_name | target.user 내의 user_display_name 필드를 채웁니다. |
| enriched.actingUser.object | target.labels.key | target.labels 내에서 값을 'Object'로 설정합니다. |
| enriched.actingUser.object | target.labels.value | 강화된.actingUser.object의 값으로 target.labels 내의 값 필드를 채웁니다. |
| enriched.actingUser.resetPasswordEnrolled | target.labels.key | target.labels 내에서 값을 'ResetPasswordEnrolled'로 설정합니다. |
| enriched.actingUser.resetPasswordEnrolled | target.labels.value | 강화된.actingUser.resetPasswordEnrolled에서 문자열로 변환된 값으로 target.labels 내의 값 필드를 채웁니다. |
| enriched.actingUser.twoFactorEnabled | security_result.rule_labels.key | security_result의 rule_labels 내에서 값을 'Two Factor Enabled'로 설정합니다. |
| enriched.actingUser.twoFactorEnabled | security_result.rule_labels.value | 강화된.actingUser.twoFactorEnabled에서 문자열로 변환된 값으로 security_result의 rule_labels 내 값 필드를 채웁니다. |
| enriched.actingUser.userId | target.user.userid | target.user 내의 userid 필드를 채웁니다. |
| enriched.collection.id | additional.fields.key | additional.fields 내에서 값을 'Collection ID'로 설정합니다. |
| enriched.collection.id | additional.fields.value.string_value | enriched.collection.id의 값으로 additional.fields 내의 string_value 필드를 채웁니다. |
| enriched.collection.object | additional.fields.key | additional.fields 내에서 값을 'Collection Object'로 설정합니다. |
| enriched.collection.object | additional.fields.value.string_value | enriched.collection.object의 값으로 additional.fields 내의 string_value 필드를 채웁니다. |
| enriched.type | metadata.product_event_type | 메타데이터 내의 product_event_type 필드를 채웁니다. |
| groupId | target.user.group_identifiers | target.user 내의 group_identifiers 배열에 값을 추가합니다. |
| ipAddress | principal.ip | 필드에서 IP 주소를 추출하여 principal.ip에 매핑했습니다. |
| 해당 사항 없음 | extensions.auth | 파서에 의해 빈 객체가 생성됩니다. |
| 해당 사항 없음 | metadata.event_type | enriched.type과 주 구성원 및 타겟 정보의 존재 여부에 따라 결정됩니다. 가능한 값: USER_LOGIN, STATUS_UPDATE, GENERIC_EVENT |
| 해당 사항 없음 | security_result.action | enriched.type을 기반으로 결정됩니다. 가능한 값: ALLOW, BLOCK |
| 객체 | additional.fields.key | additional.fields 내의 값을 'Object'로 설정합니다. |
| 객체 | additional.fields.value | object의 값으로 additional.fields 내의 value 필드를 채웁니다. |
도움이 더 필요한가요? 커뮤니티 회원 및 Google SecOps 전문가에게 문의하여 답변을 받으세요.